def ground( graph: BELGraph, remove_ungrounded: bool = True, skip_namespaces: Optional[Collection[str]] = None, ) -> BELGraph: """Ground all entities in a BEL graph.""" j = to_nodelink(graph) ground_nodelink(j, skip_namespaces=skip_namespaces) graph = from_nodelink(j) remove_unused_annotation_metadata(graph) if remove_ungrounded: ungrounded_nodes = { node for node in get_ungrounded_nodes(graph) if not isinstance(node, BaseConcept) or node.namespace not in NO_NAMES } graph.remove_nodes_from(ungrounded_nodes) graph.namespace_url.clear() graph.namespace_pattern.clear() graph.namespace_pattern.update( {namespace: '.*' for namespace in get_namespaces(graph)}) graph.annotation_url.clear() graph.annotation_pattern.clear() graph.annotation_list.clear() graph.annotation_pattern.update( {annotation: '.*' for annotation in get_annotations(graph)}) return graph
def remove_unused_annotation_metadata(graph) -> None: used_annotations = get_annotations(graph) unused_patterns = set(graph.annotation_pattern) - used_annotations for annotation in unused_patterns: logger.warning('deleting unused annotation pattern: %s', annotation) del graph.annotation_pattern[annotation] unused_urls = set(graph.annotation_pattern) - used_annotations for annotation in unused_urls: logger.warning('deleting unused annotation URL: %s', annotation) del graph.annotation_url[annotation] unused_lists = set(graph.annotation_list) - used_annotations for annotation in unused_lists: logger.warning('deleting unused annotation list: %s', annotation) del graph.annotation_list[annotation]