INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Iterates over all possible edges peripheral to a given subgraph that could be added from the given graph. Edges could be added if they go to nodes that are involved in relationships that occur with more than the threshold ( default 2 ) number of nodes in the subgraph.
def expand_periphery(universe: BELGraph, graph: BELGraph, node_predicates: NodePredicates = None, edge_predicates: EdgePredicates = None, threshold: int = 2, ) -> None: """Iterates over all possible edges, perip...
Add all of the members of the complex abundances to the graph.
def enrich_complexes(graph: BELGraph) -> None: """Add all of the members of the complex abundances to the graph.""" nodes = list(get_nodes_by_function(graph, COMPLEX)) for u in nodes: for v in u.members: graph.add_has_component(u, v)
Adds all of the members of the composite abundances to the graph.
def enrich_composites(graph: BELGraph): """Adds all of the members of the composite abundances to the graph.""" nodes = list(get_nodes_by_function(graph, COMPOSITE)) for u in nodes: for v in u.members: graph.add_has_component(u, v)
Adds all of the reactants and products of reactions to the graph.
def enrich_reactions(graph: BELGraph): """Adds all of the reactants and products of reactions to the graph.""" nodes = list(get_nodes_by_function(graph, REACTION)) for u in nodes: for v in u.reactants: graph.add_has_reactant(u, v) for v in u.products: graph.add_has_p...
Add the reference nodes for all variants of the given function.
def enrich_variants(graph: BELGraph, func: Union[None, str, Iterable[str]] = None): """Add the reference nodes for all variants of the given function. :param graph: The target BEL graph to enrich :param func: The function by which the subject of each triple is filtered. Defaults to the set of protein, rna,...
Enrich the sub - graph with the unqualified edges from the graph.
def enrich_unqualified(graph: BELGraph): """Enrich the sub-graph with the unqualified edges from the graph. The reason you might want to do this is you induce a sub-graph from the original graph based on an annotation filter, but the unqualified edges that don't have annotations that most likely connect el...
Edges between entities in the sub - graph that pass the given filters.
def expand_internal(universe: BELGraph, graph: BELGraph, edge_predicates: EdgePredicates = None) -> None: """Edges between entities in the sub-graph that pass the given filters. :param universe: The full graph :param graph: A sub-graph to find the upstream information :param edge_predicates: Optional l...
Add causal edges between entities in the sub - graph.
def expand_internal_causal(universe: BELGraph, graph: BELGraph) -> None: """Add causal edges between entities in the sub-graph. Is an extremely thin wrapper around :func:`expand_internal`. :param universe: A BEL graph representing the universe of all knowledge :param graph: The target BEL graph to enr...
Return the set of all namespaces with incorrect names in the graph.
def get_namespaces_with_incorrect_names(graph: BELGraph) -> Set[str]: """Return the set of all namespaces with incorrect names in the graph.""" return { exc.namespace for _, exc, _ in graph.warnings if isinstance(exc, (MissingNamespaceNameWarning, MissingNamespaceRegexWarning)) }
Get all namespaces that are used in the BEL graph aren t actually defined.
def get_undefined_namespaces(graph: BELGraph) -> Set[str]: """Get all namespaces that are used in the BEL graph aren't actually defined.""" return { exc.namespace for _, exc, _ in graph.warnings if isinstance(exc, UndefinedNamespaceWarning) }
Return the set of all incorrect names from the given namespace in the graph.
def get_incorrect_names_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: """Return the set of all incorrect names from the given namespace in the graph. :return: The set of all incorrect names from the given namespace in the graph """ return { exc.name for _, exc, _ in graph.w...
Get the names from a namespace that wasn t actually defined.
def get_undefined_namespace_names(graph: BELGraph, namespace: str) -> Set[str]: """Get the names from a namespace that wasn't actually defined. :return: The set of all names from the undefined namespace """ return { exc.name for _, exc, _ in graph.warnings if isinstance(exc, Und...
Return the dict of the sets of all incorrect names from the given namespace in the graph.
def get_incorrect_names(graph: BELGraph) -> Mapping[str, Set[str]]: """Return the dict of the sets of all incorrect names from the given namespace in the graph. :return: The set of all incorrect names from the given namespace in the graph """ return { namespace: get_incorrect_names_by_namespace...
Get all annotations that aren t actually defined.: return: The set of all undefined annotations
def get_undefined_annotations(graph: BELGraph) -> Set[str]: """Get all annotations that aren't actually defined. :return: The set of all undefined annotations """ return { exc.annotation for _, exc, _ in graph.warnings if isinstance(exc, UndefinedAnnotationWarning) }
Group all of the incorrect identifiers in a dict of { namespace: list of erroneous names }.
def calculate_incorrect_name_dict(graph: BELGraph) -> Mapping[str, str]: """Group all of the incorrect identifiers in a dict of {namespace: list of erroneous names}. :return: A dictionary of {namespace: list of erroneous names} """ missing = defaultdict(list) for _, e, ctx in graph.warnings: ...
Group the errors together for analysis of the most frequent error.
def group_errors(graph: BELGraph) -> Mapping[str, List[int]]: """Group the errors together for analysis of the most frequent error. :return: A dictionary of {error string: list of line numbers} """ warning_summary = defaultdict(list) for _, exc, _ in graph.warnings: warning_summary[str(exc...
Get the ( n ) most common errors in a graph.
def get_most_common_errors(graph: BELGraph, n: Optional[int] = 20): """Get the (n) most common errors in a graph.""" return count_dict_values(group_errors(graph)).most_common(n)
Takes the names from the graph in a given namespace (: func: pybel. struct. summary. get_names_by_namespace ) and the erroneous names from the same namespace (: func: get_incorrect_names_by_namespace ) and returns them together as a unioned set
def get_names_including_errors_by_namespace(graph: BELGraph, namespace: str) -> Set[str]: """Takes the names from the graph in a given namespace (:func:`pybel.struct.summary.get_names_by_namespace`) and the erroneous names from the same namespace (:func:`get_incorrect_names_by_namespace`) and returns them toget...
Takes the names from the graph in a given namespace and the erroneous names from the same namespace and returns them together as a unioned set
def get_names_including_errors(graph: BELGraph) -> Mapping[str, Set[str]]: """Takes the names from the graph in a given namespace and the erroneous names from the same namespace and returns them together as a unioned set :return: The dict of the sets of all correct and incorrect names from the given namesp...
Iterate over pairs in list s - > ( s0 s1 ) ( s1 s2 ) ( s2 s3 )...
def pairwise(iterable: Iterable[X]) -> Iterable[Tuple[X, X]]: """Iterate over pairs in list s -> (s0,s1), (s1,s2), (s2, s3), ...""" a, b = itt.tee(iterable) next(b, None) return zip(a, b)
Count the number of elements in each value of the dictionary.
def count_defaultdict(dict_of_lists: Mapping[X, List[Y]]) -> Mapping[X, typing.Counter[Y]]: """Count the number of elements in each value of the dictionary.""" return { k: Counter(v) for k, v in dict_of_lists.items() }
Count the number of elements in each value ( can be list Counter etc ).
def count_dict_values(dict_of_counters: Mapping[X, Sized]) -> typing.Counter[X]: """Count the number of elements in each value (can be list, Counter, etc). :param dict_of_counters: A dictionary of things whose lengths can be measured (lists, Counters, dicts) :return: A Counter with the same keys as the inp...
What percentage of x is contained within y?
def set_percentage(x: Iterable[X], y: Iterable[X]) -> float: """What percentage of x is contained within y? :param set x: A set :param set y: Another set :return: The percentage of x contained within y """ a, b = set(x), set(y) if not a: return 0.0 return len(a & b) / len(a)
Calculate the tanimoto set similarity.
def tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float: """Calculate the tanimoto set similarity.""" a, b = set(x), set(y) union = a | b if not union: return 0.0 return len(a & b) / len(union)
Calculate the tanimoto set similarity using the minimum size.
def min_tanimoto_set_similarity(x: Iterable[X], y: Iterable[X]) -> float: """Calculate the tanimoto set similarity using the minimum size. :param set x: A set :param set y: Another set :return: The similarity between """ a, b = set(x), set(y) if not a or not b: return 0.0 ...
Return a dictionary of distances keyed by the keys in the given dict.
def calculate_single_tanimoto_set_distances(target: Iterable[X], dict_of_sets: Mapping[Y, Set[X]]) -> Mapping[Y, float]: """Return a dictionary of distances keyed by the keys in the given dict. Distances are calculated based on pairwise tanimoto similarity of the sets contained :param set target: A set ...
Return a distance matrix keyed by the keys in the given dict.
def calculate_tanimoto_set_distances(dict_of_sets: Mapping[X, Set]) -> Mapping[X, Mapping[X, float]]: """Return a distance matrix keyed by the keys in the given dict. Distances are calculated based on pairwise tanimoto similarity of the sets contained. :param dict_of_sets: A dict of {x: set of y} :ret...
r Calculate an alternative distance matrix based on the following equation.
def calculate_global_tanimoto_set_distances(dict_of_sets: Mapping[X, Set]) -> Mapping[X, Mapping[X, float]]: r"""Calculate an alternative distance matrix based on the following equation. .. math:: distance(A, B)=1- \|A \cup B\| / \| \cup_{s \in S} s\| :param dict_of_sets: A dict of {x: set of y} :retu...
A convenience function for plotting a horizontal bar plot from a Counter
def barh(d, plt, title=None): """A convenience function for plotting a horizontal bar plot from a Counter""" labels = sorted(d, key=d.get) index = range(len(labels)) plt.yticks(index, labels) plt.barh(index, [d[v] for v in labels]) if title is not None: plt.title(title)
A convenience function for plotting a vertical bar plot from a Counter
def barv(d, plt, title=None, rotation='vertical'): """A convenience function for plotting a vertical bar plot from a Counter""" labels = sorted(d, key=d.get, reverse=True) index = range(len(labels)) plt.xticks(index, labels, rotation=rotation) plt.bar(index, [d[v] for v in labels]) if title is ...
Adds an edge while preserving negative keys and paying no respect to positive ones
def safe_add_edge(graph, u, v, key, attr_dict, **attr): """Adds an edge while preserving negative keys, and paying no respect to positive ones :param pybel.BELGraph graph: A BEL Graph :param tuple u: The source BEL node :param tuple v: The target BEL node :param int key: The edge key. If less than ...
Prepares C3 JSON for making a bar chart from a Counter
def prepare_c3(data: Union[List[Tuple[str, int]], Mapping[str, int]], y_axis_label: str = 'y', x_axis_label: str = 'x', ) -> str: """Prepares C3 JSON for making a bar chart from a Counter :param data: A dictionary of {str: int} to display as bar chart :param y_a...
Prepare C3 JSON string dump for a time series.
def prepare_c3_time_series(data: List[Tuple[int, int]], y_axis_label: str = 'y', x_axis_label: str = 'x') -> str: """Prepare C3 JSON string dump for a time series. :param data: A list of tuples [(year, count)] :param y_axis_label: The Y axis label :param x_axis_label: X axis internal label. Should be l...
Calculate the betweenness centrality over nodes in the graph.
def calculate_betweenness_centality(graph: BELGraph, number_samples: int = CENTRALITY_SAMPLES) -> Counter: """Calculate the betweenness centrality over nodes in the graph. Tries to do it with a certain number of samples, but then tries a complete approach if it fails. """ try: res = nx.betweenn...
Iterate over all possible circulations of an ordered collection ( tuple or list ).
def get_circulations(elements: T) -> Iterable[T]: """Iterate over all possible circulations of an ordered collection (tuple or list). Example: >>> list(get_circulations([1, 2, 3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] """ for i in range(len(elements)): yield elements[i:] + elements[:i]
Get get a canonical representation of the ordered collection by finding its minimum circulation with the given sort key
def canonical_circulation(elements: T, key: Optional[Callable[[T], bool]] = None) -> T: """Get get a canonical representation of the ordered collection by finding its minimum circulation with the given sort key """ return min(get_circulations(elements), key=key)
Check if a pair of nodes has any contradictions in their causal relationships.
def pair_has_contradiction(graph: BELGraph, u: BaseEntity, v: BaseEntity) -> bool: """Check if a pair of nodes has any contradictions in their causal relationships. Assumes both nodes are in the graph. """ relations = {data[RELATION] for data in graph[u][v].values()} return relation_set_has_contrad...
Return if the set of BEL relations contains a contradiction.
def relation_set_has_contradictions(relations: Set[str]) -> bool: """Return if the set of BEL relations contains a contradiction.""" has_increases = any(relation in CAUSAL_INCREASE_RELATIONS for relation in relations) has_decreases = any(relation in CAUSAL_DECREASE_RELATIONS for relation in relations) h...
Prepare the ( internal ) percolation graph from a given graph
def percolation_graph(graph, spanning_cluster=True): """ Prepare the (internal) percolation graph from a given graph Helper function to prepare the given graph for spanning cluster detection (if required). Basically it strips off the auxiliary nodes and edges again. It also returns fundamental ...
Generate successive sample states of the percolation model
def sample_states( graph, spanning_cluster=True, model='bond', copy_result=True ): ''' Generate successive sample states of the percolation model This is a :ref:`generator function <python:tut-generators>` to successively add one edge at a time from the graph to the percolation model. At each i...
r Generate statistics for a single run
def single_run_arrays(spanning_cluster=True, **kwargs): r''' Generate statistics for a single run This is a stand-alone helper function to evolve a single sample state (realization) and return the cluster statistics. Parameters ---------- spanning_cluster : bool, optional Whether t...
r Compute the average number of runs that have a spanning cluster
def _microcanonical_average_spanning_cluster(has_spanning_cluster, alpha): r''' Compute the average number of runs that have a spanning cluster Helper function for :func:`microcanonical_averages` Parameters ---------- has_spanning_cluster : 1-D :py:class:`numpy.ndarray` of bool Each e...
Compute the average size of the largest cluster
def _microcanonical_average_max_cluster_size(max_cluster_size, alpha): """ Compute the average size of the largest cluster Helper function for :func:`microcanonical_averages` Parameters ---------- max_cluster_size : 1-D :py:class:`numpy.ndarray` of int Each entry is the ``max_cluster_...
Compute the average moments of the cluster size distributions
def _microcanonical_average_moments(moments, alpha): """ Compute the average moments of the cluster size distributions Helper function for :func:`microcanonical_averages` Parameters ---------- moments : 2-D :py:class:`numpy.ndarray` of int ``moments.shape[1] == 5`. Each array ...
r Generate successive microcanonical percolation ensemble averages
def microcanonical_averages( graph, runs=40, spanning_cluster=True, model='bond', alpha=alpha_1sigma, copy_result=True ): r''' Generate successive microcanonical percolation ensemble averages This is a :ref:`generator function <python:tut-generators>` to successively add one edge at a time from...
Generate a linear chain with auxiliary nodes for spanning cluster detection
def spanning_1d_chain(length): """ Generate a linear chain with auxiliary nodes for spanning cluster detection Parameters ---------- length : int Number of nodes in the chain, excluding the auxiliary nodes. Returns ------- networkx.Graph A linear chain graph with auxili...
Generate a square lattice with auxiliary nodes for spanning detection
def spanning_2d_grid(length): """ Generate a square lattice with auxiliary nodes for spanning detection Parameters ---------- length : int Number of nodes in one dimension, excluding the auxiliary nodes. Returns ------- networkx.Graph A square lattice graph with auxilia...
Compile microcanonical averages over all iteration steps into single arrays
def microcanonical_averages_arrays(microcanonical_averages): """ Compile microcanonical averages over all iteration steps into single arrays Helper function to aggregate the microcanonical averages over all iteration steps into single arrays for further processing Parameters ---------- mi...
Compute the binomial PMF according to Newman and Ziff
def _binomial_pmf(n, p): """ Compute the binomial PMF according to Newman and Ziff Helper function for :func:`canonical_averages` See Also -------- canonical_averages Notes ----- See Newman & Ziff, Equation (10) [10]_ References ---------- .. [10] Newman, M. E. J. ...
Compute the canonical cluster statistics from microcanonical statistics
def canonical_averages(ps, microcanonical_averages_arrays): """ Compute the canonical cluster statistics from microcanonical statistics This is according to Newman and Ziff, Equation (2). Note that we also simply average the bounds of the confidence intervals according to this formula. Paramet...
Helper function to compute percolation statistics
def statistics( graph, ps, spanning_cluster=True, model='bond', alpha=alpha_1sigma, runs=40 ): """ Helper function to compute percolation statistics See Also -------- canonical_averages microcanonical_averages sample_states """ my_microcanonical_averages = microcanonical_av...
Render the graph as an HTML string.
def to_html(graph: BELGraph) -> str: """Render the graph as an HTML string. Common usage may involve writing to a file like: >>> from pybel.examples import sialic_acid_graph >>> with open('html_output.html', 'w') as file: ... print(to_html(sialic_acid_graph), file=file) """ context = g...
Create a summary dictionary.
def get_network_summary_dict(graph: BELGraph) -> Mapping: """Create a summary dictionary.""" return dict( # Counters function_count=count_functions(graph), modifications_count=get_modifications_count(graph), relation_count=count_relations(graph), authors_count=count_autho...
Get the pair as a tuple of BEL/ hashes.
def get_pair_tuple(a: BaseEntity, b: BaseEntity) -> Tuple[str, str, str, str]: """Get the pair as a tuple of BEL/hashes.""" return a.as_bel(), a.sha512, b.as_bel(), b.sha512
Get the triple as a tuple of BEL/ hashes.
def get_triplet_tuple(a: BaseEntity, b: BaseEntity, c: BaseEntity) -> Tuple[str, str, str, str, str, str]: """Get the triple as a tuple of BEL/hashes.""" return a.as_bel(), a.sha512, b.as_bel(), b.sha512, c.as_bel(), c.sha512
Test the regulator hypothesis of the given node on the input data using the algorithm.
def rank_causalr_hypothesis(graph, node_to_regulation, regulator_node): """Test the regulator hypothesis of the given node on the input data using the algorithm. Note: this method returns both +/- signed hypotheses evaluated Algorithm: 1. Calculate the shortest path between the regulator node and eac...
Returns the effect from the root to the target nodes represented as { - 1 1 }
def run_cna(graph, root, targets, relationship_dict=None): """ Returns the effect from the root to the target nodes represented as {-1,1} :param pybel.BELGraph graph: A BEL graph :param BaseEntity root: The root node :param iter targets: The targets nodes :param dict relationship_dict: dictionary w...
Calculate the final effect of the root node to the sink node in the path.
def get_path_effect(graph, path, relationship_dict): """Calculate the final effect of the root node to the sink node in the path. :param pybel.BELGraph graph: A BEL graph :param list path: Path from root to sink node :param dict relationship_dict: dictionary with relationship effects :rtype: Effect...
Return the highest ranked edge from a multiedge.
def rank_edges(edges, edge_ranking=None): """Return the highest ranked edge from a multiedge. :param dict edges: dictionary with all edges between two nodes :param dict edge_ranking: A dictionary of {relationship: score} :return: Highest ranked edge :rtype: tuple: (edge id, relation, score given ra...
Group the nodes occurring in edges by the given annotation.
def group_nodes_by_annotation(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Set[BaseEntity]]: """Group the nodes occurring in edges by the given annotation.""" result = defaultdict(set) for u, v, d in graph.edges(data=True): if not edge_has_annotation(d, annotation): co...
Groups graph into subgraphs and assigns each subgraph a score based on the average of all nodes values for the given node key
def average_node_annotation(graph: BELGraph, key: str, annotation: str = 'Subgraph', aggregator: Optional[Callable[[Iterable[X]], X]] = None, ) -> Mapping[str, X]: """Groups graph into subgraphs and assig...
Group the nodes occurring in edges by the given annotation with a node filter applied.
def group_nodes_by_annotation_filtered(graph: BELGraph, node_predicates: NodePredicates = None, annotation: str = 'Subgraph', ) -> Mapping[str, Set[BaseEntity]]: """Group the nodes occurring in edges...
Return a dict with keys: nodes that match the namespace and in names and values other nodes ( complexes variants orthologous... ) or this node.: param graph: A BEL graph: param namespace: The namespace to search: param names: List or set of values from which we want to map nodes from: return: Main node to variants/ gro...
def get_mapped_nodes(graph: BELGraph, namespace: str, names: Iterable[str]) -> Mapping[BaseEntity, Set[BaseEntity]]: """Return a dict with keys: nodes that match the namespace and in names and values other nodes (complexes, variants, orthologous...) or this node. :param graph: A BEL graph :param namesp...
Make an expand function that s bound to the manager.
def build_expand_node_neighborhood_by_hash(manager: Manager) -> Callable[[BELGraph, BELGraph, str], None]: """Make an expand function that's bound to the manager.""" @uni_in_place_transformation def expand_node_neighborhood_by_hash(universe: BELGraph, graph: BELGraph, node_hash: str) -> None: """Ex...
Make a delete function that s bound to the manager.
def build_delete_node_by_hash(manager: Manager) -> Callable[[BELGraph, str], None]: """Make a delete function that's bound to the manager.""" @in_place_transformation def delete_node_by_hash(graph: BELGraph, node_hash: str) -> None: """Remove a node by identifier.""" node = manager.get_dsl_...
Create an excel sheet ready to be used in SPIA software.
def bel_to_spia_matrices(graph: BELGraph) -> Mapping[str, pd.DataFrame]: """Create an excel sheet ready to be used in SPIA software. :param graph: BELGraph :return: dictionary with matrices """ index_nodes = get_matrix_index(graph) spia_matrices = build_spia_matrices(index_nodes) for u, v,...
Return set of HGNC names from Proteins/ Rnas/ Genes/ miRNA nodes that can be used by SPIA.
def get_matrix_index(graph: BELGraph) -> Set[str]: """Return set of HGNC names from Proteins/Rnas/Genes/miRNA, nodes that can be used by SPIA.""" # TODO: Using HGNC Symbols for now return { node.name for node in graph if isinstance(node, CentralDogma) and node.namespace.upper() == 'H...
Build an adjacency matrix for each KEGG relationship and return in a dictionary.
def build_spia_matrices(nodes: Set[str]) -> Dict[str, pd.DataFrame]: """Build an adjacency matrix for each KEGG relationship and return in a dictionary. :param nodes: A set of HGNC gene symbols :return: Dictionary of adjacency matrix for each relationship """ nodes = list(sorted(nodes)) # Crea...
Populate the adjacency matrix.
def update_spia_matrices(spia_matrices: Dict[str, pd.DataFrame], u: CentralDogma, v: CentralDogma, edge_data: EdgeData, ) -> None: """Populate the adjacency matrix.""" if u.namespace.upper() != 'HGNC' or v.namesp...
Export a SPIA data dictionary into an Excel sheet at the given path.
def spia_matrices_to_excel(spia_matrices: Mapping[str, pd.DataFrame], path: str) -> None: """Export a SPIA data dictionary into an Excel sheet at the given path. .. note:: # The R import should add the values: # ["nodes"] from the columns # ["title"] from the name of the file #...
Export a SPIA data dictionary into a directory as several TSV documents.
def spia_matrices_to_tsvs(spia_matrices: Mapping[str, pd.DataFrame], directory: str) -> None: """Export a SPIA data dictionary into a directory as several TSV documents.""" os.makedirs(directory, exist_ok=True) for relation, df in spia_matrices.items(): df.to_csv(os.path.join(directory, f'{relation}...
Export the graph to a SPIA Excel sheet.
def main(graph: BELGraph, xlsx: str, tsvs: str): """Export the graph to a SPIA Excel sheet.""" if not xlsx and not tsvs: click.secho('Specify at least one option --xlsx or --tsvs', fg='red') sys.exit(1) spia_matrices = bel_to_spia_matrices(graph) if xlsx: spia_matrices_to_excel...
Overlays tabular data on the network
def overlay_data(graph: BELGraph, data: Mapping[BaseEntity, Any], label: Optional[str] = None, overwrite: bool = False, ) -> None: """Overlays tabular data on the network :param graph: A BEL Graph :param data: A dictionary of {tuple node: ...
Overlay tabular data on the network for data that comes from an data set with identifiers that lack namespaces.
def overlay_type_data(graph: BELGraph, data: Mapping[str, float], func: str, namespace: str, label: Optional[str] = None, overwrite: bool = False, impute: Optional[float] = None, ...
Load and pre - process a differential gene expression data.
def load_differential_gene_expression(path: str, gene_symbol_column: str = 'Gene.symbol', logfc_column: str = 'logFC', aggregator: Optional[Callable[[List[float]], float]] = None, ...
Loads many namespaces and combines their names.
def get_merged_namespace_names(locations, check_keywords=True): """Loads many namespaces and combines their names. :param iter[str] locations: An iterable of URLs or file paths pointing to BEL namespaces. :param bool check_keywords: Should all the keywords be the same? Defaults to ``True`` :return: A d...
Merges namespaces from multiple locations to one.
def merge_namespaces(input_locations, output_path, namespace_name, namespace_keyword, namespace_domain, author_name, citation_name, namespace_description=None, namespace_species=None, namespace_version=None, namespace_query_url=None, namespace_created=None, author_contact=None,...
Run the reverse causal reasoning algorithm on a graph.
def run_rcr(graph, tag='dgxp'): """Run the reverse causal reasoning algorithm on a graph. Steps: 1. Get all downstream controlled things into map (that have at least 4 downstream things) 2. calculate population of all things that are downstream controlled .. note:: Assumes all nodes have been pre...
Exports all names and missing names from the given namespace to its own BEL Namespace files in the given directory.
def export_namespace(graph, namespace, directory=None, cacheable=False): """Exports all names and missing names from the given namespace to its own BEL Namespace files in the given directory. Could be useful during quick and dirty curation, where planned namespace building is not a priority. :param py...
Thinly wraps: func: export_namespace for an iterable of namespaces.
def export_namespaces(graph, namespaces, directory=None, cacheable=False): """Thinly wraps :func:`export_namespace` for an iterable of namespaces. :param pybel.BELGraph graph: A BEL graph :param iter[str] namespaces: An iterable of strings for the namespaces to process :param str directory: The path to...
Helps remove extraneous whitespace from the lines of a file
def lint_file(in_file, out_file=None): """Helps remove extraneous whitespace from the lines of a file :param file in_file: A readable file or file-like :param file out_file: A writable file or file-like """ for line in in_file: print(line.strip(), file=out_file)
Adds a linted version of each document in the source directory to the target directory
def lint_directory(source, target): """Adds a linted version of each document in the source directory to the target directory :param str source: Path to directory to lint :param str target: Path to directory to output """ for path in os.listdir(source): if not path.endswith('.bel'): ...
Build a skeleton for the citations statements.: param pmids: A list of PubMed identifiers: return: An iterator over the lines of the citation section
def make_pubmed_abstract_group(pmids: Iterable[Union[str, int]]) -> Iterable[str]: """Build a skeleton for the citations' statements. :param pmids: A list of PubMed identifiers :return: An iterator over the lines of the citation section """ for pmid in set(pmids): yield '' res ...
Get gene info from Entrez.
def get_entrez_gene_data(entrez_ids: Iterable[Union[str, int]]): """Get gene info from Entrez.""" url = PUBMED_GENE_QUERY_URL.format(','.join(str(x).strip() for x in entrez_ids)) response = requests.get(url) tree = ElementTree.fromstring(response.content) return { element.attrib['uid']: { ...
Builds a skeleton for gene summaries
def make_pubmed_gene_group(entrez_ids: Iterable[Union[str, int]]) -> Iterable[str]: """Builds a skeleton for gene summaries :param entrez_ids: A list of Entrez Gene identifiers to query the PubMed service :return: An iterator over statement lines for NCBI Entrez Gene summaries """ url = PUBMED_GENE...
Write a boilerplate BEL document with standard document metadata definitions.
def write_boilerplate(name: str, version: Optional[str] = None, description: Optional[str] = None, authors: Optional[str] = None, contact: Optional[str] = None, copyright: Optional[str] = None, ...
Induce a sub - graph on the nodes that pass the given predicate ( s ).
def get_subgraph_by_node_filter(graph: BELGraph, node_predicates: NodePredicates) -> BELGraph: """Induce a sub-graph on the nodes that pass the given predicate(s).""" return get_subgraph_by_induction(graph, filter_nodes(graph, node_predicates))
Get a sub - graph induced over all nodes matching the query string.
def get_subgraph_by_node_search(graph: BELGraph, query: Strings) -> BELGraph: """Get a sub-graph induced over all nodes matching the query string. :param graph: A BEL Graph :param query: A query string or iterable of query strings for node names Thinly wraps :func:`search_node_names` and :func:`get_su...
Get the giant component of a graph.
def get_largest_component(graph: BELGraph) -> BELGraph: """Get the giant component of a graph.""" biggest_component_nodes = max(nx.weakly_connected_components(graph), key=len) return subgraph(graph, biggest_component_nodes)
Get a random graph by inducing over a percentage of the original nodes.
def random_by_nodes(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph: """Get a random graph by inducing over a percentage of the original nodes. :param graph: A BEL graph :param percentage: The percentage of edges to keep """ percentage = percentage or 0.9 assert 0 < percentage...
Get a random graph by keeping a certain percentage of original edges.
def random_by_edges(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph: """Get a random graph by keeping a certain percentage of original edges. :param graph: A BEL graph :param percentage: What percentage of eges to take """ percentage = percentage or 0.9 assert 0 < percentage <=...
Shuffle the node s data.
def shuffle_node_data(graph: BELGraph, key: str, percentage: Optional[float] = None) -> BELGraph: """Shuffle the node's data. Useful for permutation testing. :param graph: A BEL graph :param key: The node data dictionary key :param percentage: What percentage of possible swaps to make """ ...
Shuffle the relations.
def shuffle_relations(graph: BELGraph, percentage: Optional[str] = None) -> BELGraph: """Shuffle the relations. Useful for permutation testing. :param graph: A BEL graph :param percentage: What percentage of possible swaps to make """ percentage = percentage or 0.3 assert 0 < percentage <=...
Check if all edges between two nodes have the same relation.
def is_edge_consistent(graph, u, v): """Check if all edges between two nodes have the same relation. :param pybel.BELGraph graph: A BEL Graph :param tuple u: The source BEL node :param tuple v: The target BEL node :return: If all edges from the source to target node have the same relation :rtyp...
Return if all edges are consistent in a graph. Wraps: func: pybel_tools. utils. is_edge_consistent.
def all_edges_consistent(graph): """Return if all edges are consistent in a graph. Wraps :func:`pybel_tools.utils.is_edge_consistent`. :param pybel.BELGraph graph: A BEL graph :return: Are all edges consistent :rtype: bool """ return all( is_edge_consistent(graph, u, v) for u, v...
Rewire a graph s edges target nodes.
def rewire_targets(graph, rewiring_probability): """Rewire a graph's edges' target nodes. - For BEL graphs, assumes edge consistency (all edges between two given nodes are have the same relation) - Doesn't make self-edges :param pybel.BELGraph graph: A BEL graph :param float rewiring_probability: ...
Check if the source and target nodes are the same.
def self_edge_filter(_: BELGraph, source: BaseEntity, target: BaseEntity, __: str) -> bool: """Check if the source and target nodes are the same.""" return source == target
Check if pmod of source causes activity of target.
def has_protein_modification_increases_activity(graph: BELGraph, source: BaseEntity, target: BaseEntity, key: str, ) -> bool: ...
Check if the degradation of source causes activity of target.
def has_degradation_increases_activity(data: Dict) -> bool: """Check if the degradation of source causes activity of target.""" return part_has_modifier(data, SUBJECT, DEGRADATION) and part_has_modifier(data, OBJECT, ACTIVITY)
Check if the translocation of source causes activity of target.
def has_translocation_increases_activity(data: Dict) -> bool: """Check if the translocation of source causes activity of target.""" return part_has_modifier(data, SUBJECT, TRANSLOCATION) and part_has_modifier(data, OBJECT, ACTIVITY)