-
Notifications
You must be signed in to change notification settings - Fork 124
/
scigraph_client.py
3250 lines (2776 loc) · 141 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/sparc-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
_hrx = re.compile('^https?://')
def __init__(self, cache=False, safe_cache=False, key=None, do_error=False):
self._session = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=1000, pool_maxsize=1000)
self._session.mount('http://', adapter)
self._do_error = do_error
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:
if self._do_error:
resp.raise_for_status()
else:
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, do_error=False):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key, do_error=do_error)
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()}
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
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, do_error=False):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key, do_error=do_error)
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()}
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()}
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()}
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()}
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()}
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()}
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()}
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, do_error=False):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key, do_error=do_error)
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()}
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', **kwargs):
""" 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}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
url = self._basePath + (f'{"/cypher/execute.json" if output == "application/json" else "/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', **kwargs):
""" Cypher query resolver from: /cypher/resolve
Arguments:
cypherQuery: The cypher query to resolve
outputs:
text/plain
"""
kwargs = {'cypherQuery': cypherQuery, **kwargs}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
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', **kwargs):
if output == 'text/plain':
out = super().execute(query, limit, output, **kwargs)
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, **kwargs)
class DynamicBase(restService):
""" Dynamic Cypher resources """
def __init__(self, basePath=None, verbose=False, cache=False, safe_cache=False, key=None, do_error=False):
if basePath is None:
basePath = BASEPATH
self._basePath = basePath
self._verbose = verbose
super().__init__(cache=cache, safe_cache=safe_cache, key=key, do_error=do_error)
def demos_apinat_bundles_start_id(self, start_id, output='application/json'):
""" Return the paths to somas from an anatomical region (aka connected-somas) from: /dynamic/demos/apinat/bundles/{start-id}
Arguments:
start_id: ontology id of the starting point
Query:
MATCH path1 = (start:Class{iri: "${start-id}"})
-[:apinatomy:annotates]->(start_housing)
-[:apinatomy:subtypes*0..1]->()
-[:apinatomy:clones*0..1]->(layer_or_end)
-[:apinatomy:layers*0..1]->()
-[:apinatomy:bundles]->(linkStart)
-[:apinatomy:prevChainEndLevels|apinatomy:prev|apinatomy:source*1..]->(link)
-[:apinatomy:targetOf|apinatomy:sourceOf]->(linkSoma) // axon or dendrite root
-[:apinatomy:conveyingLyph]->()
-[:apinatomy:supertype*0..1]->(soma:NamedIndividual)
-[:apinatomy:ontologyTerms]->(c:Class{iri: "http://uri.neuinfo.org/nif/nifstd/nlx_154731"})
WITH path1, link
OPTIONAL MATCH path2 = (link)
-[:apinatomy:fasciculatesIn|apinatomy:endsIn]->(layer_or_end)
-[:apinatomy:layerIn*0..1]->(end)
-[:apinatomy:ontologyTerms]->(external)
RETURN path1, path2
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()}
url = self._basePath + ('/dynamic/demos/apinat/bundles/{start_id}').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_housing_lyphs(self, output='application/json'):
""" List all the housing lyphs (neuronal processes) for all starting points. from: /dynamic/demos/apinat/housing-lyphs
Arguments:
Query:
MATCH path = (c:Class{iri: "http://uri.neuinfo.org/nif/nifstd/nlx_154731"})
-[:apinatomy:annotates]->(soma:NamedIndividual) // soma lyph
-[:apinatomy:conveys]->(somaLink) // link connecting soma to axon and dendrite
-[:apinatomy:target|apinatomy:source]->(root) // axon or dendrite root
-[:apinatomy:controlNodes|apinatomy:rootOf*1..2]->(chain) // axon or dendrite tree
-[:apinatomy:housingLyphs]->(housing) // list of lyphs housing the trees
-[:apinatomy:ontologyTerms*0..1]->(external) // external ids for the housing lyphs
WHERE soma.`https://apinatomy.org/uris/readable/generated` IS NULL
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
url = self._basePath + ('/dynamic/demos/apinat/housing-lyphs').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_housing_lyphs_start_id(self, start_id, output='application/json'):
""" List all the housing lyphs for a starting point. from: /dynamic/demos/apinat/housing-lyphs/{start-id}
Arguments:
start_id: ontology id of the starting point
Query:
MATCH path1 = (c:Class{iri: "http://uri.neuinfo.org/nif/nifstd/nlx_154731"})
-[:apinatomy:annotates]->(soma:NamedIndividual) // soma lyph
-[:apinatomy:conveys]->(somaLink) // link connecting soma to axon and dendrite
-[:apinatomy:target|apinatomy:source]->(root) // axon or dendrite root
-[:apinatomy:internalIn]->(layer_or_end)
-[:apinatomy:cloneOf*0..1]->()
-[:apinatomy:supertype*0..1]->()
-[:apinatomy:ontologyTerms]->(layer_or_end_external:Class{iri: '${start-id}'})
WHERE soma.`https://apinatomy.org/uris/readable/generated` IS NULL
WITH path1, root
MATCH path2 = (root)
-[:apinatomy:controlNodes|apinatomy:rootOf*1..2]->(chain) // axon or dendrite tree
-[:apinatomy:housingLyphs]->(housing) // list of lyphs housing the trees
-[:apinatomy:ontologyTerms*0..1]->(external) // external ids for the housing lyphs
RETURN path1, path2
UNION
MATCH path1 = (c:Class{iri: "http://uri.neuinfo.org/nif/nifstd/nlx_154731"})
-[:apinatomy:annotates]->(soma:NamedIndividual) // soma lyph
-[:apinatomy:conveys]->(somaLink) // link connecting soma to axon and dendrite
-[:apinatomy:target|apinatomy:source]->(root) // axon or dendrite root
-[:apinatomy:internalIn]->(layer)
-[:apinatomy:cloneOf*0..1]->()
-[:apinatomy:supertype*0..1]->()
-[:apinatomy:layerIn]->(end_housing)
-[:apinatomy:ontologyTerms]->(end_housing_external:Class{iri: '${start-id}'})
WHERE soma.`https://apinatomy.org/uris/readable/generated` IS NULL
WITH path1, root
MATCH path2 = (root)
-[:apinatomy:rootOf]->(chain) // axon or dendrite tree
-[:apinatomy:housingLyphs]->(housing) // list of lyphs housing the trees
-[:apinatomy:ontologyTerms*0..1]->(external) // external ids for the housing lyphs
RETURN path1, path2
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()}
url = self._basePath + ('/dynamic/demos/apinat/housing-lyphs/{start_id}').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_modelList(self, output='application/json'):
""" Return the list of all ApiNATOMY models in the database. from: /dynamic/demos/apinat/modelList
Arguments:
Query:
MATCH ({iri: "https://apinatomy.org/uris/elements/Graph"})
<-[:type]-(g)-[:isDefinedBy]->(o:Ontology)
RETURN o
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
url = self._basePath + ('/dynamic/demos/apinat/modelList').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_modelPopulationsReferences_model_id(self, model_id, output='application/json'):
""" Given an ApiNATOMY model id return the identifiers for the neuronpopulations that are present in the model and the identifiers forreferences that provide supporting evidence. Publications andpopulations can be distingished by checking whether their meta typefield is NamedIndividual or Class. from: /dynamic/demos/apinat/modelPopulationsReferences/{model_id}
Arguments:
model_id: the identifier for an ApiNATOMY model
Query:
MATCH (start:Ontology {iri: $model_id})
<-[:isDefinedBy]-(external:Class)
-[:subClassOf*]->(:Class {iri: "http://uri.interlex.org/tgbugs/uris/readable/NeuronEBM"}) // FIXME
,
(external)
-[e:type]->()
RETURN e
UNION
OPTIONAL MATCH (start:Ontology {iri: $model_id})
<-[:isDefinedBy]-(graph:NamedIndividual)
-[:type]->({iri: "https://apinatomy.org/uris/elements/Graph"}) // elements don't have a superclass right now
,
(graph)
-[:apinatomy:references]->(pub)
-[e:type]->(:Class{iri: "https://apinatomy.org/uris/elements/Reference"})
RETURN e
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 = {'model_id': model_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
url = self._basePath + ('/dynamic/demos/apinat/modelPopulationsReferences/{model_id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'model_id'}
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_neru_1_neupop_id(self, neupop_id, output='application/json'):
""" Return the housing regions and publications for neurulated groups. from: /dynamic/demos/apinat/neru-1/{neupop-id}
Arguments:
neupop_id: neuron population identifier
Query:
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
// publications
WITH neugrp, a
OPTIONAL MATCH path = (neugrp)
-[:apinatomy:references]->(pub)
-[:type]->(:Class{iri: "https://apinatomy.org/uris/elements/Publication"}) // cannot be curied, dynamic endpoints will not expand it
WITH neugrp, a, path
MATCH (neugrp)
-[b:apinatomy:links]->(link)
-[c:apinatomy:fasciculatesIn|apinatomy:endsIn*0..1]->(lyph_or_layer) // real lyphs convey things, layers do not
-[d:apinatomy:layerIn*0..1]->(lyph)
-[:apinatomy:conveys*0..1]->() // make sure we are at a real lyph
WITH lyph, a, b, c, d, path
MATCH (lyph)
-[e:apinatomy:ontologyTerms]->(region)
RETURN a, b, c, d, e, path
UNION
// this part usually only returns the soma housing lyph
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
-[b:apinatomy:lyphs]->(lyph)
-[c:apinatomy:internalIn]->(e) // e is a hack to get columns to match
-[d:apinatomy:ontologyTerms*0..1]->(region)
// this variant shows the dead end lyphs that correspond to the fasciculatesIn links above
//-[c:apinatomy:internalIn*0..1]->(e)
//-[d:apinatomy:ontologyTerms*0..1]->(region)
return a, b, c, d, null AS e, null AS 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 = {'neupop_id': neupop_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
url = self._basePath + ('/dynamic/demos/apinat/neru-1/{neupop_id}').format(**kwargs)
requests_params = kwargs
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_neru_2_neupop_id(self, neupop_id, output='application/json'):
""" Return the housing regions and publications for neurulated groups. from: /dynamic/demos/apinat/neru-2/{neupop_id}
Arguments:
neupop_id: neuron population identifier
Query:
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
// publications
WITH neugrp, a
OPTIONAL MATCH path = (neugrp)
-[:apinatomy:references]->(pub)
-[:type]->(:Class{iri: "https://apinatomy.org/uris/elements/Publication"}) // cannot be curied, dynamic endpoints will not expand it
WITH neugrp, a, path
MATCH (neugrp)
-[b:apinatomy:links]->(link)
-[c:apinatomy:fasciculatesIn|apinatomy:endsIn*0..1]->(lyph_or_layer) // real lyphs convey things, layers do not
-[d:apinatomy:layerIn*0..1]->(lyph)
-[:apinatomy:conveys*0..1]->() // make sure we are at a real lyph
WITH neugrp, link, lyph, a, b, c, d, path
MATCH (lyph)
-[e:apinatomy:ontologyTerms]->(region)
// use apinatomy:next to extract ordering information
WITH neugrp, link, a, b, c, d, e, path
MATCH (link)
-[f:apinatomy:next*0..]->()
//-[f:apinatomy:next|apinatomy:nextChainStartLevels*0..]->()
// FIXME these should be collapsing into a single relationship
-[g:apinatomy:target*0..1]->()
-[h:apinatomy:rootOf*0..1]->()
-[i:apinatomy:levels*0..1]->()
<-[:apinatomy:links]-(neugrp)
RETURN a, b, c, d, e, f, g,h,i, path
UNION
// this part usually only returns the soma housing lyph
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
-[b:apinatomy:lyphs]->(lyph)
-[c:apinatomy:internalIn]->(e) // e is a hack to get columns to match
-[d:apinatomy:ontologyTerms*0..1]->(region)
// this variant shows the dead end lyphs that correspond to the fasciculatesIn links above
//-[c:apinatomy:internalIn*0..1]->(e)
//-[d:apinatomy:ontologyTerms*0..1]->(region)
RETURN a, b, c, d, null AS e, null AS f, null AS g, null AS h, null AS i, null AS 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 = {'neupop_id': neupop_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
url = self._basePath + ('/dynamic/demos/apinat/neru-2/{neupop_id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'neupop_id'}
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_neru_3_neupop_id(self, neupop_id, output='application/json'):
""" Return the housing regions and publications for neurulated groups. from: /dynamic/demos/apinat/neru-3/{neupop_id}
Arguments:
neupop_id: neuron population identifier
Query:
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
// publications
WITH neugrp, a
OPTIONAL MATCH path = (neugrp)
-[:apinatomy:references]->(pub)
-[:type]->(:Class{iri: "https://apinatomy.org/uris/elements/Publication"}) // cannot be curied, dynamic endpoints will not expand it
WITH neugrp, a, path
MATCH (neugrp)
-[b:apinatomy:links]->(link)
-[c:apinatomy:fasciculatesIn|apinatomy:endsIn*0..1]->(lyph_or_layer) // real lyphs convey things, layers do not
-[d:apinatomy:layerIn*0..1]->(lyph)
-[:apinatomy:conveys*0..1]->() // make sure we are at a real lyph
WITH neugrp, link, lyph, a, b, c, d, path // MATCH vs , not all things that match as lyphs have externals
MATCH (lyph)
-[e:apinatomy:ontologyTerms]->(region)
// use apinatomy:next to extract ordering information
WITH neugrp, link, a, b, c, d, e, path
MATCH p2 = (link)
-[:apinatomy:conveyingLyph]->(cl)
-[:apinatomy:topology]->()
WITH neugrp, link, a, b, c, d, e, path, p2, cl
MATCH (cl)
-[x:apinatomy:inheritedOntologyTerms*0..1]->()
WITH neugrp, link, a, b, c, d, e, path, p2, x
MATCH (link)
-[f:apinatomy:next*0..]->()
//-[f:apinatomy:next|apinatomy:nextChainStartLevels*0..]->()
// FIXME these should be collapsing into a single relationship
-[g:apinatomy:target*0..1]->()
-[h:apinatomy:rootOf*0..1]->()
-[i:apinatomy:levels*0..1]->()
<-[:apinatomy:links]-(neugrp)
RETURN a, b, c, d, e, f, g,h,i, path, p2, x
UNION
// this part usually only returns the soma housing lyph
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
-[b:apinatomy:lyphs]->(lyph)
-[c:apinatomy:internalIn]->()
-[d:apinatomy:ontologyTerms*0..1]->(region)
// this variant shows the dead end lyphs that correspond to the fasciculatesIn links above
//-[c:apinatomy:internalIn*0..1]->()
//-[d:apinatomy:ontologyTerms*0..1]->(region)
RETURN a, b, c, d, null AS e, null AS f, null AS g, null AS h, null AS i, null AS path, null as p2, null as x
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 = {'neupop_id': neupop_id}
kwargs = {k:dumps(v) if builtins.type(v) is dict else v for k, v in kwargs.items()}
url = self._basePath + ('/dynamic/demos/apinat/neru-3/{neupop_id}').format(**kwargs)
requests_params = {k:v for k, v in kwargs.items() if k != 'neupop_id'}
output = self._get('GET', url, requests_params, output)
return output if output else None
def demos_apinat_neru_4_neupop_id(self, neupop_id, output='application/json'):
""" Return the housing regions and publications for neurulated groups. from: /dynamic/demos/apinat/neru-4/{neupop_id}
Arguments:
neupop_id: neuron population identifier
Query:
MATCH (neupop:Class{iri: $neupop_id})
-[a:apinatomy:annotates]->(neugrp:NamedIndividual{`https://apinatomy.org/uris/readable/description`: "dynamic"}) // FIXME HACK
, (neugrp)
-[:apinatomy:links]->(link)
-[c:apinatomy:fasciculatesIn|apinatomy:endsIn*0..1]->(lyph_or_layer) // real lyphs convey things, layers do not
-[d:apinatomy:layerIn*0..1]->(lyph)
-[:apinatomy:conveys*0..1]->() // make sure we are at a real lyph