-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathscigraph_client.py
2039 lines (1762 loc) · 85.7 KB
/
scigraph_client.py
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""WARNING: DO NOT MODIFY THIS FILE
IT IS AUTOMATICALLY GENERATED BY scigraph.py
AND WILL BE OVERWRITTEN
Swagger Version: 2.0, API Version: 1.0.1
generated for http://localhost:9000/scigraph/swagger.json
by scigraph.py
"""
import re
import copy
import inspect
import builtins
from urllib.parse import parse_qs
import requests
from ast import literal_eval
from json import dumps
from urllib import parse
BASEPATH = 'https://scicrunch.org/api/1/scigraph'
exten_mapping = {'application/graphml+xml': 'graphml+xml', 'application/graphson': 'graphson', 'application/javascript': 'javascript', 'application/json': 'json', 'application/xgmml': 'xgmml', 'application/xml': 'xml', 'image/jpeg': 'jpeg', 'image/png': 'png', 'text/csv': 'csv', 'text/gml': 'gml', 'text/html': 'html', 'text/plain': 'plain', 'text/plain; charset=utf-8': 'plain; charset=utf-8', 'text/tab-separated-values': 'tab-separated-values'}
class restService:
""" Base class for SciGraph rest services. """
_api_key = None
def __init__(self, cache=False, safe_cache=False, key=None):
self._session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=1000, pool_maxsize=1000)
self._session.mount('http://', adapter)
if cache:
#print('WARNING: cache enabled, if you mutate the contents of return values you will mutate the cache!')
self._cache = dict()
if safe_cache:
self._get = self._safe_cache_get
else:
self._get = self._cache_get
else:
self._get = self._normal_get
if key is not None:
self.api_key = key
raise DeprecationWarning('this way of passing keys will be deprecated soon')
@property
def api_key(self):
return self._api_key
@api_key.setter
def api_key(self, value):
self._api_key = value
def __del__(self):
self._session.close()
def _safe_url(self, url):
return url.replace(self.api_key, '[secure]') if self.api_key else url
@property
def _last_url(self):
return self._safe_url(self.__last_url)
def _normal_get(self, method, url, params=None, output=None):
s = self._session
if self.api_key is not None:
params['key'] = self.api_key
if method == 'POST':
req = requests.Request(method=method, url=url, data=params)
else:
req = requests.Request(method=method, url=url, params=params)
if output:
req.headers['Accept'] = output
prep = req.prepare()
if self._verbose: print(self._safe_url(prep.url))
try:
resp = s.send(prep)
self.__last_url = resp.url
except requests.exceptions.ConnectionError as e:
host_port = prep.url.split(prep.path_url)[0]
raise ConnectionError(f'Could not connect to {host_port}. '
'Are SciGraph services running?') from e
if resp.status_code == 401:
raise ConnectionError(f'{resp.reason}. '
f'Did you set {self.__class__.__name__}.api_key'
' = my_api_key?')
elif not resp.ok:
return None
elif resp.headers['content-type'] == 'application/json':
return resp.json()
elif resp.headers['content-type'].startswith('text/plain'):
return resp.text
else:
return resp
def _cache_get(self, method, url, params=None, output=None):
if params:
pkey = '?' + '&'.join(['%s=%s' % (k,v) for k,v in sorted(params.items()) if v is not None])
else:
pkey = ''
key = url + pkey + ' ' + method + ' ' + str(output)
if key in self._cache:
if self._verbose:
print('cache hit', key)
self.__last_url, resp = self._cache[key]
else:
resp = self._normal_get(method, url, params, output)
self._cache[key] = self.__last_url, resp
return resp
def _safe_cache_get(self, *args, **kwargs):
""" If cached values might be used in a context where they
could be mutated, then safe_cache = True should be set
and this wrapper will protect the output """
return copy.deepcopy(self._cache_get(*args, **kwargs)) # prevent mutation of the cache
def _make_rest(self, default=None, **kwargs):
kwargs = {k:v for k, v in kwargs.items() if v}
param_rest = '&'.join(['%s={%s}' % (arg, arg) for arg in kwargs if arg != default])
param_rest = param_rest if param_rest else ''
return param_rest
class Analyzer(restService):
""" Analysis services """
def __init__(self, basePath=None, verbose=False, cache=False, safe_cache=False, key=None):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key)
def enrich(self, sample, ontologyClass, path, callback=None, output='application/json'):
""" Class Enrichment Service from: /analyzer/enrichment
Arguments:
sample: A list of CURIEs for nodes whose attributes are to be tested for
enrichment. For example, a list of genes.
ontologyClass: CURIE for parent ontology class for the attribute to be tested.
For example, GO biological process
path: A path expression that connects sample nodes to attribute class nodes
callback: Name of the JSONP callback ('fn' by default). Supplying this
parameter or requesting a javascript media type will cause a
JSONP response to be rendered.
outputs:
application/json
"""
kwargs = {'sample': sample, 'ontologyClass': ontologyClass, 'path': path, 'callback': callback}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/analyzer/enrichment').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def enrichPost(self, output='application/json'):
""" from: /analyzer/enrichment
Arguments:
outputs:
application/json
"""
kwargs = {}
# type caste not needed
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/analyzer/enrichment').format(**kwargs)
requests_params = kwargs
output = self._get('POST', url, requests_params, output)
return output if output else []
class Annotations(restService):
""" Annotation services """
def __init__(self, basePath=None, verbose=False, cache=False, safe_cache=False, key=None):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key)
def annotate(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='text/plain; charset=utf-8'):
""" Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
outputs:
text/plain; charset=utf-8
"""
kwargs = {'content': content, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def annotatePost(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None, output='application/json'):
""" Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
ignoreTag: HTML tags that should not be annotated
stylesheet: CSS stylesheets to add to the HEAD
scripts: JavaScripts that should to add to the HEAD
targetId: A set of element IDs to annotate
targetClass: A set of CSS class names to annotate
outputs:
application/json
"""
kwargs = {'content': content, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers, 'ignoreTag': ignoreTag, 'stylesheet': stylesheet, 'scripts': scripts, 'targetId': targetId, 'targetClass': targetClass}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations').format(**kwargs)
requests_params = kwargs
output = self._get('POST', url, requests_params, output)
return output if output else None
def getEntitiesAndContent(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='application/json'):
""" Get embedded annotations as well as a separate list from: /annotations/complete
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
outputs:
application/json
"""
kwargs = {'content': content, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations/complete').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else []
def postEntitiesAndContent(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='application/json'):
""" Get embedded annotations as well as a separate list from: /annotations/complete
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
outputs:
application/json
"""
kwargs = {'content': content, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations/complete').format(**kwargs)
requests_params = kwargs
output = self._get('POST', url, requests_params, output)
return output if output else []
def getEntities(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='application/json'):
""" Get entities from text from: /annotations/entities
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
outputs:
application/json
"""
kwargs = {'content': content, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations/entities').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else []
def postEntities(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='application/json'):
""" Get entities from text from: /annotations/entities
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
outputs:
application/json
"""
kwargs = {'content': content, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations/entities').format(**kwargs)
requests_params = kwargs
output = self._get('POST', url, requests_params, output)
return output if output else []
def annotateUrl(self, url, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, ignoreTag=None, stylesheet=None, scripts=None, targetId=None, targetClass=None, output='text/html'):
""" Annotate a URL from: /annotations/url
Arguments:
url:
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Should only the longest entity be returned for an overlapping group
includeAbbrev: Should abbreviations be included
includeAcronym: Should acronyms be included
includeNumbers: Should numbers be included
ignoreTag: HTML tags that should not be annotated
stylesheet: CSS stylesheets to add to the HEAD
scripts: JavaScripts that should to add to the HEAD
targetId: A set of element IDs to annotate
targetClass: A set of CSS class names to annotate
outputs:
text/html
"""
kwargs = {'url': url, 'includeCat': includeCat, 'excludeCat': excludeCat, 'minLength': minLength, 'longestOnly': longestOnly, 'includeAbbrev': includeAbbrev, 'includeAcronym': includeAcronym, 'includeNumbers': includeNumbers, 'ignoreTag': ignoreTag, 'stylesheet': stylesheet, 'scripts': scripts, 'targetId': targetId, 'targetClass': targetClass}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/annotations/url').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
class CypherBase(restService):
""" Cypher utility services """
def __init__(self, basePath=None, verbose=False, cache=False, safe_cache=False, key=None):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key)
def getCuries(self, callback=None, output='application/json'):
""" Get the curie map from: /cypher/curies
Arguments:
callback: Name of the JSONP callback ('fn' by default). Supplying this
parameter or requesting a javascript media type will cause a
JSONP response to be rendered.
outputs:
application/json
"""
kwargs = {'callback': callback}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/cypher/curies').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else {}
def execute(self, cypherQuery, limit, output='text/plain'):
""" Execute an arbitrary Cypher query. from: /cypher/execute
Arguments:
cypherQuery: The cypher query to execute
limit: Limit
outputs:
text/plain
application/json
"""
kwargs = {'cypherQuery': cypherQuery, 'limit': limit}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/cypher/execute').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def resolve(self, cypherQuery, output='text/plain'):
""" Cypher query resolver from: /cypher/resolve
Arguments:
cypherQuery: The cypher query to resolve
outputs:
text/plain
"""
kwargs = {'cypherQuery': cypherQuery}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/cypher/resolve').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
class Cypher(CypherBase):
@staticmethod
def fix_quotes(string, s1=':["', s2='"],'):
out = []
def subsplit(sstr, s=s2):
#print(s)
if s == '",' and sstr.endswith('"}'): # special case for end of record
s = '"}'
if s:
string, *rest = sstr.rsplit(s, 1)
else:
string = sstr
rest = '',
if rest:
#print('>>>>', string)
#print('>>>>', rest)
r, = rest
if s == '"],':
fixed_string = Cypher.fix_quotes(string, '","', '') + s + r
else:
fixed_string = string.replace('"', r'\"') + s + r
return fixed_string
for sub1 in string.split(s1):
ss = subsplit(sub1)
if ss is None:
if s1 == ':["':
out.append(Cypher.fix_quotes(sub1, ':"', '",'))
else:
out.append(sub1)
else:
out.append(ss)
return s1.join(out)
def fix_cypher(self, record):
rep = re.sub(r'({|, )(\S+)(: "|: \[)', r'\1"\2"\3',
self.fix_quotes(record.strip()).
split(']', 1)[1] .
replace(':"', ': "') .
replace(':[', ': [') .
replace('",', '", ') .
replace('"],', '"], ') .
replace('\n', '\\n') .
replace('xml:lang="en"', r'xml:lang=\"en\"')
)
try:
value = {self.qname(k):v for k, v in literal_eval(rep).items()}
except (ValueError, SyntaxError) as e:
print(repr(record))
print(repr(rep))
raise e
return value
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._setCuries()
def _setCuries(self):
try:
self._curies = self.getCuries()
except ConnectionError:
self._curies = {}
self._inv = {v:k for k, v in self._curies.items()}
@property
def api_key(self):
# note that using properties means that
# if you want to use properties at all in
# a subClass hierarchy you have to reimplement
# them every single time to be aware if the
# parent class value chanes
if isinstance(restService.api_key, str):
return restService.api_key
else:
return self._api_key
@api_key.setter
def api_key(self, value):
old_key = self.api_key
self._api_key = value
if old_key is None and value is not None:
self._setCuries()
def qname(self, iri):
for prefix, curie in self._inv.items():
if iri.startswith(prefix):
return iri.replace(prefix, curie + ':')
else:
return iri
def execute(self, query, limit, output='text/plain'):
if output == 'text/plain':
out = super().execute(query, limit, output)
rows = []
if out:
for raw in out.split('|')[3:-1]:
record = raw.strip()
if record:
d = self.fix_cypher(record)
rows.append(d)
return rows
else:
return super().execute(query, limit, output)
class DynamicBase(restService):
""" Dynamic Cypher resources """
def __init__(self, basePath=None, verbose=False, cache=False, safe_cache=False, key=None):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key)
def multiquery_relationship_id(self, relationship, id, output='application/json'):
""" actually include parent class properties like owl is supposed to ... from: /dynamic/multiquery/{relationship}/{id}
Arguments:
relationship: ontology id of the relationship to traverse
id: ontology id of the starting point
Query:
MATCH path = (start:Class{iri: "${id}"})
-[:subClassOf|${relationship}*]
->(end)
RETURN path
/* // apparently broken
MATCH (start:Class{iri: "${id}"})
-[:subClassOf*0..20]
-(intermediate)
-[${relationship}*]
->(end)
RETURN end
*/
/*
MATCH (start:Class{iri: "${id}"})
-[:subClassOf*]
->(superClass)
WITH superClass
MATCH (superClass)-[:${relationship}*]->(superpart)
RETURN superpart
UNION
MATCH (start:Class{iri: "${id}"})
-[:${relationship}*]->(superpart)
RETURN superpart
*/
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
if id and id.startswith('http:'):
id = parse.quote(id, safe='')
kwargs = {'relationship': relationship, 'id': id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('id', **kwargs)
url = self._basePath + ('/dynamic/multiquery/{relationship}/{id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'id'}
output = self._get('GET', url, requests_params, output)
return output if output else None
def neurons_connectedRegions(self, start_id=None, target_predicate=None, output='application/json'):
""" Get connected anatomical regions by starting location and target relationship from: /dynamic/neurons/connectedRegions
Arguments:
start_id: The starting location (eg UBERON:0001759)
target_predicate: The predicate for the type of connectivity (eg
ilxtr:hasPresynapticTerminalsIn)
Query:
MATCH (blank)-
[entrytype:ilxtr:hasSomaLocatedIn|ilxtr:hasAxonLocatedIn|ilxtr:hasDendriteLocatedIn|ilxtr:hasPresynapticTerminalsIn]
->(location:Class{iri: '${start_id}'})
WITH entrytype, blank
MATCH (phenotype)<-[:${target_predicate}]-(blank)
// WHERE NOT (phenotype.iri =~ ".*_:.*")
RETURN phenotype
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {'start_id': start_id, 'target_predicate': target_predicate}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/neurons/connectedRegions').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def neurons_connectivity(self, start_id=None, output='application/json'):
""" Get connected anatomical regions by neuron type from: /dynamic/neurons/connectivity
Arguments:
start_id: The starting location (eg UBERON:0001759)
Query:
MATCH (blank)-
[entrytype:ilxtr:hasSomaLocatedIn|ilxtr:hasAxonLocatedIn|ilxtr:hasDendriteLocatedIn|ilxtr:hasPresynapticTerminalsIn]
->(location:Class{iri: '${start_id}'})
WITH location, entrytype, blank
MATCH (phenotype)<-[predicate]-(blank)<-[:equivalentClass]-(neuron)
WHERE NOT (phenotype.iri =~ ".*_:.*")
// RETURN phenotype, (phenotype)-[predicate]-(neuron) as e
// WITH location, predicate, phenotype, neuron
RETURN location, entrytype, neuron, predicate, phenotype
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {'start_id': start_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/neurons/connectivity').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_artifactLabels_artifact_id(self, artifact_id, output='application/json'):
""" Get the graph of all parcellation labels for a single artifact WARNING this can return no results from: /dynamic/prod/sparc/artifactLabels/{artifact-id}
Arguments:
artifact_id: ontology id of the parcellation artifact
Query:
MATCH path = (label)
-[:subClassOf]->(root)
-[:ilxtr:isDefinedBy]->(a)<-[:subClassOf*0..2]
-(artifact:Class{iri: "${artifact-id}"})
WHERE label.iri <> "http://www.w3.org/2002/07/owl#Nothing"
RETURN path
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
if artifact_id and artifact_id.startswith('http:'):
artifact_id = parse.quote(artifact_id, safe='')
kwargs = {'artifact_id': artifact_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/prod/sparc/artifactLabels/{artifact_id}').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_artifactRoots_artifact_id(self, artifact_id, output='application/json'):
""" Get the graph of all parcellation label roots for a single artifact WARNING this can return no results from: /dynamic/prod/sparc/artifactRoots/{artifact-id}
Arguments:
artifact_id: ontology id of the parcellation artifact
Query:
MATCH path = (root)
-[:ilxtr:isDefinedBy]->(a)<-[:subClassOf*0..2]
-(artifact:Class{iri: "${artifact-id}"})
RETURN path
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
if artifact_id and artifact_id.startswith('http:'):
artifact_id = parse.quote(artifact_id, safe='')
kwargs = {'artifact_id': artifact_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/prod/sparc/artifactRoots/{artifact_id}').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_organList(self, output='application/json'):
""" Get the list of all FMA organ identifiers relevant to SPARC from: /dynamic/prod/sparc/organList
Arguments:
Query:
MATCH (n)
WHERE n.iri IN [
"http://purl.org/sig/ont/fma/fma7195",
"http://purl.org/sig/ont/fma/fma7088",
"http://purl.org/sig/ont/fma/fma7197",
"http://purl.org/sig/ont/fma/fma7198",
"http://purl.org/sig/ont/fma/fma7203",
"http://purl.org/sig/ont/fma/fma7148",
"http://purl.org/sig/ont/fma/fma7196",
"http://purl.org/sig/ont/fma/fma14543",
"http://purl.org/sig/ont/fma/fma7201",
"http://purl.org/sig/ont/fma/fma7200",
"http://purl.org/sig/ont/fma/fma7199",
"http://purl.org/sig/ont/fma/fma15900",
"http://purl.org/sig/ont/fma/fma45659",
"http://purl.org/sig/ont/fma/fma7157",
"http://purl.org/sig/ont/fma/fma9903",
"http://purl.org/sig/ont/fma/fma9906",
"http://purl.org/sig/ont/fma/fma7647",
"http://purl.org/sig/ont/fma/fma50801"]
RETURN n
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {}
# type caste not needed
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/prod/sparc/organList').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_organParts_id(self, id, output='application/json'):
""" Get the parts list for an organ including nerves and blood vessles from: /dynamic/prod/sparc/organParts/{id}
Arguments:
id: ontology id of the organ
Query:
// NOTE: continuous with seems like it is what we want, but it causes
// MASSIVE memory usage in creatTree :/
// all parts of and directly connected to organ or parts of organ
MATCH path = (start:Class{iri: "${id}"})
-[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(part)
-[:fma:arterial_supply|fma:nerve_supply|fma:venous_drainage|fma:continuous_with*0..1]->(sup)
-[:fma:constitutional_part|fma:branch_of|fma:tributary_of|fma:branch*0..1]->(a_bit_more)
RETURN path
UNION
// return the major artery for any arteries supplying the organ directly
MATCH path = (start:Class{iri: "${id}"})
-[:fma:arterial_supply|fma:venous_drainage]->(vessel)
-[:fma:branch_of|fma:tributary_of]->(more_vessel)
-[:fma:branch_of|fma:tributary_of|fma:regional_part_of]->(even_more_vessel)
RETURN path
//
//
//
//
//
//
/*
MATCH path = (start:Class{iri: "${id}"})
-[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(part)
WHERE NOT (part)-[:fma:regional_part|fma:constitutional_part|fma:related_part]->()
RETURN path
UNION
MATCH path = (start:Class{iri: "${id}"})
-[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(part)
-[:fma:connected_to*1]->(thing)
RETURN path
UNION
MATCH ppath = (start:Class{iri: "${id}"})
-[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(part)
// can't exclude here otherwise we miss nerves of the containing parts
// WHERE NOT (part)-[:fma:regional_part|fma:constitutional_part|fma:related_part]->()
WITH start, ppath, part
MATCH path = (part)
-[:fma:nerve_supply*1]->(nerve)
-[:fma:branch_of*0..20]->(more_nerve)
WHERE NOT (more_nerve)-[:fma:branch_of]->()
// WHERE more_nerve <> part
RETURN path
UNION
MATCH ppath = (start:Class{iri: "${id}"})
-[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(part)
// can't exclude here otherwise we miss nerves of the containing parts
// WHERE NOT (part)-[:fma:regional_part|fma:constitutional_part|fma:related_part]->()
WITH start, ppath, part
MATCH path = (part)
-[:fma:arterial_supply*1]->(artery)
RETURN path
UNION
MATCH path = (start:Class{iri: "${id}"})
-[:fma:arterial_supply]->(artery)
-[:fma:branch_of]->(more_artery)
RETURN path
// UNION
// MATCH ppath = (start:Class{iri: "${id}"})
// -[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(part)
// -[:fma:arterial_supply*1]->(artery)
// WITH start, ppath, artery
// MATCH path = (artery)
// -[:fma:branch_of*1]->(more_artery)
// WHERE NOT more_artery IN nodes(ppath)
// works but slow as fuck
// WHERE NOT (start)
// -[:fma:regional_part|fma:constitutional_part|fma:related_part*0..20]->(more_artery)
// WHERE NOT more_artery IN nodes(ppath)
// WHERE NOT more_artery IN nodes(path)[0..-2]
// WHERE more_artery <> part AND more_artery <> artery
// WHERE length([n IN nodes(path) WHERE more_artery = n]) < 2
// WHERE more_artery IS NOT NULL
// WHERE NONE (p in collect(part) WHERE more_artery.id = p.id)
// WHERE NOT more_artery IN collect(part)
// RETURN path
*/
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
if id and id.startswith('http:'):
id = parse.quote(id, safe='')
kwargs = {'id': id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest('id', **kwargs)
url = self._basePath + ('/dynamic/prod/sparc/organParts/{id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'id'}
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_parcellationArtifacts(self, output='application/json'):
""" Get the graph of all parcellation artifacts for all species from: /dynamic/prod/sparc/parcellationArtifacts
Arguments:
Query:
MATCH path = (artifact)
-[:subClassOf*0..2]->(parent)
-[:ilxtr:isDefinedInTaxon]->(species)
WHERE artifact.iri <> "http://www.w3.org/2002/07/owl#Nothing"
RETURN path
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
kwargs = {}
# type caste not needed
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/prod/sparc/parcellationArtifacts').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_parcellationArtifacts_species_id(self, species_id, output='application/json'):
""" Get the graph of all parcellation artifacts for a single species from: /dynamic/prod/sparc/parcellationArtifacts/{species-id}
Arguments:
species_id: ontology id of the species
Query:
MATCH (parent)
-[:ilxtr:isDefinedInTaxon]->(species:Class{iri: "${species-id}"})
WITH parent
MATCH path = (artifact)
-[:subClassOf*0..2]->(parent)
WHERE artifact.iri <> "http://www.w3.org/2002/07/owl#Nothing"
RETURN path
outputs:
application/json
application/graphson
application/xml
application/graphml+xml
application/xgmml
text/gml
text/csv
text/tab-separated-values
image/jpeg
image/png
"""
if species_id and species_id.startswith('http:'):
species_id = parse.quote(species_id, safe='')
kwargs = {'species_id': species_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
param_rest = self._make_rest(None, **kwargs)
url = self._basePath + ('/dynamic/prod/sparc/parcellationArtifacts/{species_id}').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def prod_sparc_parcellationGraph(self, output='application/json'):
""" Get the graph of all parcellation labels for all species from: /dynamic/prod/sparc/parcellationGraph
Arguments:
Query:
MATCH path = (artifact)