-
Notifications
You must be signed in to change notification settings - Fork 30
/
ontol.py
1240 lines (1054 loc) · 36.3 KB
/
ontol.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
"""
A module for representing simple graph-oriented views of an ontology
See also:
- ontol_factory.py
"""
import networkx as nx
import logging
import re
logger = logging.getLogger(__name__)
class Ontology():
"""An object that represents a basic graph-oriented view over an ontology.
The ontology may be represented in memory, or it may be located
remotely. See subclasses for details.
The default implementation is an in-memory wrapper onto the python networkx library
"""
def __init__(self,
handle=None,
id=None,
graph=None,
xref_graph=None,
meta=None,
payload=None,
graphdoc=None):
"""
initializes based on an ontology name.
**Note**: do not call this directly, use OntologyFactory instead
"""
self.handle = handle
self.meta = meta
if id is None:
if payload is not None:
id = payload.get('id')
if id is None:
id = handle
self.id = id
# networkx object
self.graph = graph
if self.graph is None:
self.graph = nx.MultiDiGraph()
logger.debug('Graph initialized, nodes={}'.format(self.graph.nodes()))
self.xref_graph = xref_graph
# obograph
self.graphdoc = graphdoc
self.all_logical_definitions = []
self.all_property_chain_axioms = []
# alternatively accept a payload object
if payload is not None:
self.meta = payload.get('meta')
self.graph = payload.get('graph')
self.xref_graph = payload.get('xref_graph')
self.graphdoc = payload.get('graphdoc')
self.all_logical_definitions = payload.get('logical_definitions')
self.all_property_chain_axioms = payload.get('property_chain_axioms')
def __str__(self):
return '{} handle: {} meta: {}'.format(self.id, self.handle, self.meta)
def __repr__(self):
return self.__str__()
def get_graph(self):
"""
Return a networkx graph for the whole ontology.
Note: Only implemented for *eager* implementations
Return
------
nx.MultiDiGraph
A networkx MultiDiGraph object representing the complete ontology
"""
return self.graph
# consider caching
def get_filtered_graph(self, relations=None, prefix=None):
"""
Returns a networkx graph for the whole ontology, for a subset of relations
Only implemented for eager methods.
Implementation notes: currently this is not cached
Arguments
---------
- relations : list
list of object property IDs, e.g. subClassOf, BFO:0000050. If empty, uses all.
- prefix : String
if specified, create a subgraph using only classes with this prefix, e.g. ENVO, PATO, GO
Return
------
nx.MultiDiGraph
A networkx MultiDiGraph object representing the filtered ontology
"""
# trigger synonym cache
self.all_synonyms()
self.all_obsoletes()
# default method - wrap get_graph
srcg = self.get_graph()
if prefix is not None:
srcg = srcg.subgraph([n for n in srcg.nodes() if n.startswith(prefix+":")])
if relations is None:
logger.info("No filtering on "+str(self))
return srcg
logger.info("Filtering {} for {}".format(self, relations))
g = nx.MultiDiGraph()
# TODO: copy full metadata
logger.info("copying nodes")
for (n,d) in srcg.nodes(data=True):
g.add_node(n, **d)
logger.info("copying edges")
num_edges = 0
for (x,y,d) in srcg.edges(data=True):
if d['pred'] in relations:
num_edges += 1
g.add_edge(x,y,**d)
logger.info("Filtered edges: {}".format(num_edges))
return g
def merge(self, ontologies):
"""
Merges specified ontology into current ontology
"""
if self.xref_graph is None:
self.xref_graph = nx.MultiGraph()
logger.info("Merging source: {} xrefs: {}".format(self, len(self.xref_graph.edges())))
for ont in ontologies:
logger.info("Merging {} into {}".format(ont, self))
g = self.get_graph()
srcg = ont.get_graph()
for n in srcg.nodes():
g.add_node(n, **srcg.nodes[n])
for (o,s,m) in srcg.edges(data=True):
g.add_edge(o,s,**m)
if ont.xref_graph is not None:
for (o,s,m) in ont.xref_graph.edges(data=True):
self.xref_graph.add_edge(o,s,**m)
if ont.all_logical_definitions is not None:
for ld in ont.all_logical_definitions:
self.add_logical_definition(ld)
if ont.all_property_chain_axioms is not None:
for pca in ont.all_property_chain_axioms:
self.add_property_chain_axiom(pca)
def subgraph(self, nodes=None):
"""
Return an induced subgraph
By default this wraps networkx subgraph,
but this may be overridden in specific implementations
"""
if nodes is None:
nodes = []
return self.get_graph().subgraph(nodes)
def subontology(self, nodes=None, minimal=False, relations=None):
"""
Return a new ontology that is an extract of this one
Arguments
---------
- nodes: list
list of node IDs to include in subontology. If None, all are used
- relations: list
list of relation IDs to include in subontology. If None, all are used
"""
g = None
if nodes is not None:
g = self.subgraph(nodes)
else:
g = self.get_graph()
if minimal:
from ontobio.slimmer import get_minimal_subgraph
g = get_minimal_subgraph(g, nodes)
ont = Ontology(graph=g, xref_graph=self.xref_graph) # TODO - add metadata
if relations is not None:
g = ont.get_filtered_graph(relations)
ont = Ontology(graph=g, xref_graph=self.xref_graph)
return ont
def create_slim_mapping(self, subset=None, subset_nodes=None, relations=None, disable_checks=False):
"""
Create a dictionary that maps between all nodes in an ontology to a subset
Arguments
---------
ont : `Ontology`
Complete ontology to be mapped. Assumed pre-filtered for relationship types
subset : str
Name of subset to map to, e.g. goslim_generic
nodes : list
If no named subset provided, subset is passed in as list of node ids
relations : list
List of relations to filter on
disable_checks: bool
Unless this is set, this will prevent a mapping being generated with non-standard relations.
The motivation here is that the ontology graph may include relations that it is inappropriate to
propagate gene products over, e.g. transports, has-part
Return
------
dict
maps all nodes in ont to one or more non-redundant nodes in subset
Raises
------
ValueError
if the subset is empty
"""
if subset is not None:
subset_nodes = self.extract_subset(subset)
logger.info("Extracting subset: {} -> {}".format(subset, subset_nodes))
if subset_nodes is None or len(subset_nodes) == 0:
raise ValueError("subset nodes is blank")
subset_nodes = set(subset_nodes)
logger.debug("SUBSET: {}".format(subset_nodes))
# Use a sub-ontology for mapping
subont = self
if relations is not None:
subont = self.subontology(relations=relations)
if not disable_checks:
for r in subont.relations_used():
if r != 'subClassOf' and r != 'BFO:0000050' and r != 'subPropertyOf':
raise ValueError("Not safe to propagate over a graph with edge type: {}".format(r))
m = {}
for n in subont.nodes():
ancs = subont.ancestors(n, reflexive=True)
ancs_in_subset = subset_nodes.intersection(ancs)
m[n] = list(subont.filter_redundant(ancs_in_subset))
return m
def filter_redundant(self, ids):
"""
Return all non-redundant ids from a list
"""
sids = set(ids)
for id in ids:
sids = sids.difference(self.ancestors(id, reflexive=False))
return sids
def extract_subset(self, subset, contract=True):
"""
Return all nodes in a subset.
We assume the oboInOwl encoding of subsets, and subset IDs are IRIs, or IR fragments
"""
return [n for n in self.nodes() if subset in self.subsets(n, contract=contract)]
def subsets(self, nid, contract=True):
"""
Retrieves subset ids for a class or ontology object
"""
n = self.node(nid)
subsets = []
meta = self._meta(nid)
if 'subsets' in meta:
subsets = meta['subsets']
else:
subsets = []
if contract:
subsets = [self._contract_subset(s) for s in subsets]
return subsets
def _contract_subset(self, s):
if s.find("#") > -1:
return s.split('#')[-1]
else:
return s
def _meta(self, nid):
n = self.node(nid)
return n.get("meta", {})
def prefixes(self):
"""
list all prefixes used
"""
pset = set()
for n in self.nodes():
pfx = self.prefix(n)
if pfx is not None:
pset.add(pfx)
return list(pset)
def prefix_fragment(self, nid):
"""
Return prefix and fragment/localid for a node
"""
sep=':'
if nid.startswith('http'):
if '#' in nid:
sep='#'
else:
sep='/'
parts = nid.split(sep)
frag = parts.pop()
prefix = sep.join(parts)
return prefix, frag
def prefix(self, nid):
"""
Return prefix for a node
"""
pfx,_ = self.prefix_fragment(nid)
return pfx
def nodes(self):
"""
Return all nodes in ontology
Wraps networkx by default
"""
return self.get_graph().nodes()
def node(self, id):
"""
Return a node with a given ID. If the node with the ID exists the
Node object is returned, otherwise None is returned.
Wraps networkx by default
"""
return self.get_graph().nodes.get(id, None)
def has_node(self, id):
"""
True if id identifies a node in the ontology graph
"""
return id in self.get_graph().nodes()
def sorted_nodes(self):
"""
Returns all nodes in ontology, after topological sort
"""
return nx.topological_sort(self.get_graph())
def node_type(self, id):
"""
If stated, either CLASS, PROPERTY or INDIVIDUAL
"""
return self.node(id).get('type', None)
def relations_used(self):
"""
Return list of all relations used to connect edges
"""
g = self.get_graph()
types = set()
for (x,y,d) in g.edges(data=True):
types.add(d['pred'])
return list(types)
def neighbors(self, node, relations=None):
return self.parents(node, relations=relations) + self.children(node, relations=relations)
def child_parent_relations(self, subj, obj, graph=None):
"""
Get all relationship type ids between a subject and a parent.
Typically only one relation ID returned, but in some cases there may be more than one
Arguments
---------
subj: string
Child (subject) id
obj: string
Parent (object) id
Returns
-------
list
"""
if graph is None:
graph = self.get_graph()
preds = set()
for _,ea in graph[obj][subj].items():
preds.add(ea['pred'])
logger.debug('{}->{} = {}'.format(subj,obj,preds))
return preds
def parents(self, node, relations=None):
"""
Return all direct 'parents' of specified node.
Note that in the context of ontobio, 'parent' means any node that
is traversed in a single hop along an edge from a subject to object.
For example, if the ontology has an edge "finger part-of some hand", then
"hand" is the parent of finger.
This can sometimes be counter-intutitive, for example, if the ontology
contains has-part axioms. If the ontology has an edge
"X receptor activity has-part some X binding", then "X binding" is the 'parent'
of "X receptor activity" over a has-part edge.
Wraps networkx by default.
Arguments
---------
node: string
identifier for node in ontology
relations: list of strings
list of relation (object property) IDs used to filter
"""
g = self.get_graph()
if node in g:
parents = list(g.predecessors(node))
if relations is None:
return parents
else:
rset = set(relations)
return [p for p in parents if len(self.child_parent_relations(node, p, graph=g).intersection(rset)) > 0 ]
else:
return []
def children(self, node, relations=None):
"""
Return all direct children of specified node.
Wraps networkx by default.
Arguments
---------
node: string
identifier for node in ontology
relations: list of strings
list of relation (object property) IDs used to filter
"""
g = self.get_graph()
if node in g:
children = list(g.successors(node))
if relations is None:
return children
else:
rset = set(relations)
return [c for c in children if len(self.child_parent_relations(c, node, graph=g).intersection(rset)) > 0 ]
else:
return []
def ancestors(self, node, relations=None, reflexive=False):
"""Return all ancestors of specified node.
The default implementation is to use networkx, but some
implementations of the Ontology class may use a database or
service backed implementation, for large graphs.
Arguments
---------
node : str
identifier for node in ontology
reflexive : bool
if true, return query node in graph
relations : list
relation (object property) IDs used to filter
Returns
-------
list[str]
ancestor node IDs
"""
seen = set()
nextnodes = [node]
while len(nextnodes) > 0:
nn = nextnodes.pop()
if not nn in seen:
seen.add(nn)
nextnodes += self.parents(nn, relations=relations)
if not reflexive:
seen -= {node}
return list(seen)
def descendants(self, node, relations=None, reflexive=False):
"""
Returns all descendants of specified node.
The default implementation is to use networkx, but some
implementations of the Ontology class may use a database or
service backed implementation, for large graphs.
Arguments
---------
node : str
identifier for node in ontology
reflexive : bool
if true, return query node in graph
relations : list
relation (object property) IDs used to filter
Returns
-------
list[str]
descendant node IDs
"""
seen = set()
nextnodes = [node]
while len(nextnodes) > 0:
nn = nextnodes.pop()
if not nn in seen:
seen.add(nn)
nextnodes += self.children(nn, relations=relations)
if not reflexive:
seen -= {node}
return list(seen)
def equiv_graph(self):
"""
Returns
-------
graph
bidirectional networkx graph of all equivalency relations
"""
eg = nx.Graph()
for (u,v,d) in self.get_graph().edges(data=True):
if d['pred'] == 'equivalentTo':
eg.add_edge(u,v)
return eg
def traverse_nodes(self, qids, up=True, down=False, **args):
"""
Traverse (optionally) up and (optionally) down from an input set of nodes
Arguments
---------
qids : list[str]
list of seed node IDs to start from
up : bool
if True, include ancestors
down : bool
if True, include descendants
relations : list[str]
list of relations used to filter
Return
------
list[str]
nodes reachable from qids
"""
g = self.get_filtered_graph(**args)
nodes = set()
for id in qids:
# reflexive - always add self
nodes.add(id)
if down:
nodes.update(nx.descendants(g, id))
if up:
nodes.update(nx.ancestors(g, id))
return nodes
def get_roots(self, relations=None, prefix=None):
"""
Get all nodes that lack parents
Arguments
---------
relations : list[str]
list of relations used to filter
prefix : str
E.g. GO. Exclude nodes that lack this prefix when testing parentage
"""
g = self.get_filtered_graph(relations=relations, prefix=prefix)
# note: we also eliminate any singletons, which includes obsolete classes
roots = [n for n in g.nodes() if len(list(g.predecessors(n))) == 0 and len(list(g.successors(n))) > 0]
return roots
def get_level(self, level, relations=None, **args):
"""
Get all nodes at a particular level
Arguments
---------
relations : list[str]
list of relations used to filter
"""
g = self.get_filtered_graph(relations)
nodes = self.get_roots(relations=relations, **args)
for i in range(level):
logger.info(" ITERATING TO LEVEL: {} NODES: {}".format(i, nodes))
nodes = [c for n in nodes
for c in g.successors(n)]
logger.info(" FINAL: {}".format(nodes))
return nodes
def parent_index(self, relations=None):
"""
Returns a mapping of nodes to all direct parents
Arguments
---------
relations : list[str]
list of relations used to filter
Returns:
list
list of lists [[CLASS_1, PARENT_1,1, ..., PARENT_1,N], [CLASS_2, PARENT_2,1, PARENT_2,2, ... ] ... ]
"""
g = None
if relations is None:
g = self.get_graph()
else:
g = self.get_filtered_graph(relations)
l = []
for n in g:
l.append([n] + list(g.predecessors(n)))
return l
def text_definition(self, nid):
"""
Retrieves logical definitions for a class or relation id
Arguments
---------
nid : str
Node identifier for entity to be queried
Returns
-------
TextDefinition
"""
tdefs = []
meta = self._meta(nid)
if 'definition' in meta:
obj = meta['definition']
return TextDefinition(nid, **obj)
else:
return None
def logical_definitions(self, nid):
"""
Retrieves logical definitions for a class id
Arguments
---------
nid : str
Node identifier for entity to be queried
Returns
-------
LogicalDefinition
"""
ldefs = self.all_logical_definitions
if ldefs is not None:
#print("TESTING: {} AGAINST LD: {}".format(nid, str(ldefs)))
return [x for x in ldefs if x.class_id == nid]
else:
return []
def add_logical_definition(self, logical_def):
if self.all_logical_definitions is None:
self.all_logical_definitions = []
self.all_logical_definitions.append(logical_def)
def get_property_chain_axioms(self, nid):
"""
Retrieves property chain axioms for a class id
Arguments
---------
nid : str
Node identifier for relation to be queried
Returns
-------
PropertyChainAxiom
"""
pcas = self.all_property_chain_axioms
if pcas is not None:
return [x for x in pcas if x.predicate_id == nid]
else:
return []
def add_property_chain_axiom(self, pca):
if self.all_property_chain_axioms is None:
self.all_property_chain_axioms = []
self.all_property_chain_axioms.append(pca)
def get_node_type(self, nid):
n = self.node(nid)
if 'type' in n:
return n['type']
return None
def _get_meta_prop(self, nid, prop):
n = self.node(nid)
if 'meta' in n:
meta = n['meta']
if prop in meta:
return meta[prop]
return None
def _get_meta(self, nid):
n = self.node(nid)
if 'meta' in n:
return n['meta']
return None
def _get_basic_property_values(self, nid):
r = self._get_meta_prop(nid, 'basicPropertyValues')
if r is None:
return []
else:
return r
def _get_basic_property_value(self, nid, prop):
bpvs = self._get_basic_property_values(nid)
return [x['val'] for x in bpvs if x['pred'] == prop]
def is_obsolete(self, nid):
"""
True if node is obsolete
Arguments
---------
nid : str
Node identifier for entity to be queried
"""
dep = self._get_meta_prop(nid, 'deprecated')
return dep is not None and dep
def replaced_by(self, nid, strict=True):
"""
Returns value of 'replaced by' (IAO_0100001) property for obsolete nodes
Arguments
---------
nid : str
Node identifier for entity to be queried
strict: bool
If true, raise error if cardinality>1. If false, return list if cardinality>1
Return
------
None if no value set, otherwise returns node id (or list if multiple values, see strict setting)
"""
vs = self._get_basic_property_value(nid, 'IAO:0100001')
if len(vs) > 1:
msg = "replaced_by has multiple values: {}".format(vs)
if strict:
raise ValueError(msg)
else:
logger.error(msg)
return vs
def synonyms(self, nid, include_label=False):
"""
Retrieves synonym objects for a class
Arguments
---------
nid : str
Node identifier for entity to be queried
include_label : bool
If True, include label/names as Synonym objects
Returns
-------
list[Synonym]
:class:`Synonym` objects
"""
n = self.node(nid)
syns = []
if 'meta' in n:
meta = n['meta']
if 'synonyms' in meta:
for obj in meta['synonyms']:
syns.append(Synonym(nid, **obj))
if include_label:
syns.append(Synonym(nid, val=self.label(nid), pred='label'))
return syns
def obo_namespace(self, nid):
go_namespace = [predval for predval in
self.get_graph().nodes
.get(nid, {})
.get("meta", {})
.get("basicPropertyValues", []) if predval["pred"] == "OIO:hasOBONamespace"]
if len(go_namespace) >= 1:
return go_namespace[0]["val"]
else:
return None
def add_node(self, id, label=None, type='CLASS', meta=None):
"""
Add a new node to the ontology
"""
g = self.get_graph()
if meta is None:
meta={}
g.add_node(id, label=label, type=type, meta=meta)
def add_text_definition(self, textdef):
"""
Add a new text definition to the ontology
"""
self._add_meta_element(textdef.subject, 'definition', textdef.as_dict())
def set_obsolete(self, nid):
if nid not in self.get_graph():
self.add_node(nid)
self._add_meta_element(nid, 'deprecated', True)
def _add_meta_element(self, id, k, edict):
n = self.node(id)
if n is None:
raise ValueError('no such node {}'.format(id))
if 'meta' not in n:
n['meta'] = {}
n['meta'][k] = edict
def inline_xref_graph(self):
"""
Copy contents of xref_graph to inlined meta object for each node
"""
xg = self.xref_graph
for n in self.nodes():
if n in xg:
self._add_meta_element(n, 'xrefs', [{'val':x} for x in xg.neighbors(n)])
def add_parent(self, id, pid, relation='subClassOf'):
"""
Add a new edge to the ontology
"""
g = self.get_graph()
g.add_edge(pid, id, pred=relation)
def add_xref(self, id, xref):
"""
Adds an xref to the xref graph
"""
# note: does not update meta object
if self.xref_graph is None:
self.xref_graph = nx.MultiGraph()
self.xref_graph.add_edge(xref, id)
def add_synonym(self, syn):
"""
Adds a synonym for a node
"""
n = self.node(syn.class_id)
if 'meta' not in n:
n['meta'] = {}
meta = n['meta']
if 'synonyms' not in meta:
meta['synonyms'] = []
meta['synonyms'].append(syn.as_dict())
def add_to_subset(self, id, s):
"""
Adds a node to a subset
"""
n = self.node(id)
if 'meta' not in n:
n['meta'] = {}
meta = n['meta']
if 'subsets' not in meta:
meta['subsets'] = []
meta['subsets'].append(s)
def all_synonyms(self, include_label=False):
"""
Retrieves all synonyms
Arguments
---------
include_label : bool
If True, include label/names as Synonym objects
Returns
-------
list[Synonym]
:class:`Synonym` objects
"""
syns = []
for n in self.nodes():
syns = syns + self.synonyms(n, include_label=include_label)
return syns
def all_obsoletes(self):
"""
Returns all obsolete nodes
"""
return [n for n in self.nodes() if self.is_obsolete(n)]
def label(self, nid, id_if_null=False):
"""
Fetches label for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
id_if_null : bool
If True and node has no label return id as label
Return
------
str
"""
g = self.get_graph()
if nid in g:
n = g.nodes[nid]
if 'label' in n:
return n['label']
else:
if id_if_null:
return nid
else:
return None
else:
if id_if_null:
return nid
else:
return None
def xrefs(self, nid, bidirectional=False, prefix=None):
"""
Fetches xrefs for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
bidirection : bool
If True, include nodes xreffed to nid
Return
------
list[str]
"""
xrefs = []
if self.xref_graph is not None:
xg = self.xref_graph
if nid not in xg:
xrefs = []
else:
if bidirectional:
xrefs = list(xg.neighbors(nid))
else:
xrefs = [x for x in xg.neighbors(nid) if xg[nid][x][0]['source'] == nid]
if prefix is not None:
xrefs = [x for x in xrefs if self.prefix(x) == prefix]
return xrefs
def resolve_names(self, names, synonyms=False, **args):
"""
returns a list of identifiers based on an input list of labels and identifiers.
Arguments
---------
names: list
search terms. '%' treated as wildcard
synonyms: bool
if true, search on synonyms in addition to labels
is_regex : bool
if true, treats each name as a regular expression
is_partial_match : bool
if true, treats each name as a regular expression .*name.*
"""
g = self.get_graph()
r_ids = []
for n in names:
logger.debug("Searching for {} syns={}".format(n,synonyms))
if len(n.split(":")) == 2:
r_ids.append(n)