### Install Latest Code from GitHub Source Source: https://drug2ways.readthedocs.io/en/latest/installation.html Install the most recent code directly from the GitHub repository using pip. ```bash python3 -m pip install git+https://github.com/drug2ways/drug2ways.git ``` -------------------------------- ### Install for Developers (Editable Mode) Source: https://drug2ways.readthedocs.io/en/latest/installation.html Clone the repository and install in editable mode for development. This allows changes in the source code to be reflected immediately without reinstallation. ```bash git clone https://github.com/drug2ways/drug2ways.git cd drug2ways python3 -m pip install -e . ``` -------------------------------- ### Install Latest Stable Version from PyPI Source: https://drug2ways.readthedocs.io/en/latest/installation.html Use this command to install the most recent stable release of drug2ways from the Python Package Index. ```bash python3 -m pip install drug2ways ``` -------------------------------- ### Get Paths to Target Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Retrieves all paths from a source to a single target, avoiding specified nodes. Returns path counts and node traversal statistics. ```python def get_paths_to_target(graph, source, target, visited_nodes, history, lmax): """Return all paths from source to target avoiding nodes in visitied_nodes. Paths are returned as a tuple with (1) a pair of integers with the total number of paths source to target (2) a dictionary of all nodes and how many nodes cross through them """ if lmax == 0: if graph[source][target]['polarity'] == 1: return [1, 0], {} else: return [0, 1], {} # pre conditions: # 1. len(history[source]) is at least lmax # 2. target in history[source][lmax] ``` -------------------------------- ### Get Paths to Target Function Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Calculates paths and node counts from a source to a target node, considering graph edges, history, and visited nodes. Used when a direct path or a path through intermediate nodes is needed. ```python def get_paths_to_target(graph, source, target, visited_nodes, history, lmax): valid_neighbors = [] for node in history[source][lmax][target][1]: if graph.has_edge(source, node): valid_neighbors.append(node) paths = [0, 0] node_count = {} for neighbor in valid_neighbors: # 1. len(history[neighbor]) is at least lmax-1 if len(history[neighbor]) < lmax - 1: continue # 2. target in history[neighbor][lmax - 1] if target not in history[neighbor][lmax - 1]: continue # if neighbor is in list of visited_nodes, we're not interested in its paths. if neighbor in visited_nodes: continue # if neighbor has paths involving any of the visited_nodes, # recursive call will return w/o them. nodes_in_subpath = [node for node in history[neighbor][lmax - 1][target][1].keys()] if any(node in visited_nodes + [source] for node in nodes_in_subpath): neighbor_paths, neighbor_node_count = get_paths_to_target( graph, neighbor, target, visited_nodes + [source], history, lmax - 1) else: neighbor_paths = history[neighbor][lmax - 1][target][0] neighbor_node_count = history[neighbor][lmax - 1][target][1] relation_polarity = graph[source][neighbor]['polarity'] activation_index = 0 if relation_polarity == 1 else 1 inhibition_index = 1 if relation_polarity == 1 else 0 for node, count in neighbor_node_count.items(): if node not in node_count: node_count[node] = [0, 0] node_count[node][0] += count[activation_index] node_count[node][1] += count[inhibition_index] if sum(neighbor_paths): if neighbor not in node_count: node_count[neighbor] = [0, 0] node_count[neighbor][0] += neighbor_paths[activation_index] node_count[neighbor][1] += neighbor_paths[inhibition_index] paths[0] += neighbor_paths[activation_index] paths[1] += neighbor_paths[inhibition_index] return paths, node_count ``` -------------------------------- ### Get Paths Through Function Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Finds all paths between a source and target that specifically pass through a given crossnode. It handles cases where the source is the crossnode by calling get_paths_to_target. ```python def get_paths_through(graph, source, target, crossnode, visited_nodes, history, lmax): """Return all paths crossing crossnode. Paths are returned as a tuple with (1) a pair of integers with the total number of paths source to target. (2) a dictionary of all nodes and how many nodes cross through them If source == crossnode, call get_paths_to_target to get all paths from here. Otherwise, select neighbors that include crossnode in their history of length lmax - 1 """ # if source == crossnode, we need to get all paths but source won't be involved anymore, # therefore, we have to switch to get_paths_to_target function if source == crossnode: paths, node_count = get_paths_to_target( graph, source, target, visited_nodes + [source], history, lmax - 1 ) return paths, node_count valid_neighbors = [] for node in history[source][lmax][target][1]: if graph.has_edge(source, node): valid_neighbors.append(node) paths = [0, 0] node_count = {} for neighbor in valid_neighbors: # 1. len(history[neighbor]) is at least lmax-1 if len(history[neighbor]) < lmax - 1: continue # 2. target in history[neighbor][lmax - 1] if target not in history[neighbor][lmax - 1]: continue # 3. neighbor not in visited_nodes if neighbor in visited_nodes: continue elif neighbor == crossnode: neighbor_paths, neighbor_node_count = get_paths_to_target( graph, neighbor, target, visited_nodes + [source], history, lmax - 1) # crossnode must be in intermediate paths for neighbor to be considered elif crossnode not in history[neighbor][lmax - 1][target][1]: continue else: neighbor_paths, neighbor_node_count = get_paths_through( graph, neighbor, target, crossnode, visited_nodes + [source], history, lmax - 1) relation_polarity = graph[source][neighbor]['polarity'] activation_index = 0 if relation_polarity == 1 else 1 inhibition_index = 1 if relation_polarity == 1 else 0 for node, count in neighbor_node_count.items(): if node not in node_count: node_count[node] = [0, 0] node_count[node][0] += count[activation_index] node_count[node][1] += count[inhibition_index] if sum(neighbor_paths): if neighbor not in node_count: node_count[neighbor] = [0, 0] node_count[neighbor][0] += neighbor_paths[activation_index] node_count[neighbor][1] += neighbor_paths[inhibition_index] paths[0] += neighbor_paths[activation_index] paths[1] += neighbor_paths[inhibition_index] return paths, node_count ``` -------------------------------- ### Define Output Directories Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Defines the paths for the resources and results directories within the project's root directory. ```python RESOURCES_DIR = os.path.join(ROOT_DIR, 'graphs') RESULTS_DIR = os.path.join(ROOT_DIR, 'results') ``` -------------------------------- ### Optimize Command Source: https://drug2ways.readthedocs.io/en/latest/cli.html Utilize the 'optimize' command to find sources that optimize given targets within a network. This command requires specifying the network graph and other relevant parameters. ```bash drug2ways optimize [OPTIONS] ``` -------------------------------- ### Explore Graph with Drug2ways API Source: https://drug2ways.readthedocs.io/en/latest/api.html Use the wrapper_explore function to find paths in a directed graph. Specify source and target nodes, maximum path length, and whether to allow cycles. ```python from drug2ways.cli_helper import wrapper_explore from networkx import DiGraph # Initialize a directed graph directed_graph = nx.DiGraph() directed_graph.add_edges_from([(1, 2), (1, 3)]) results, time_cache = wrapper_explore( graph=directed_graph, # directed graph source_nodes=[1], # list of source nodes target_nodes=[3], # list of target nodes lmax=2, # max length of the path simple_paths=True, # with or without cycles (True=no cycles are allowed) ) ``` -------------------------------- ### Ensure Output Directories Exist Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Creates the default drug2ways directory if it does not already exist. This ensures that the library has a place to store its data. ```python def ensure_output_dirs(): """Ensure that the output directories exists.""" os.makedirs(DEFAULT_DRUG2WAYS_DIR, exist_ok=True) ``` -------------------------------- ### Compute All Simple Paths with Multi-Target and History Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Recursively computes all simple paths from a source to multiple targets within a maximum length, while tracking path history for each visited node. Handles cycles by detecting and accounting for paths that loop back. ```python def _compute_all_simple_paths_multitarget_dict(graph, source, targets, lmax, history, cycle_history={}): """Compute all simple paths and store history for each visited node containing number of paths already found. :param graph: graph :param source: source node :param targets: target nodes :param lmax: maximum number of edges to find a path :param history: maximum number of edges to find a path :param cycle_history: :return: """ if lmax == 0: return _history_source = [{} for _ in range(lmax)] neighbor_nodes = [neighbor for neighbor in graph.neighbors(source)] for neighbor in neighbor_nodes: if graph.nodes[neighbor]['isTarget']: if neighbor in targets or not targets: _history_source[0][neighbor] = [[0, 0], {}] if graph[source][neighbor]['polarity'] == 1: _history_source[0][neighbor][0][0] = 1 else: _history_source[0][neighbor][0][1] = 1 continue if neighbor not in history or (neighbor in history and len(history[neighbor]) < lmax - 1): _compute_all_simple_paths_multitarget_dict( graph=graph, source=neighbor, targets=targets, lmax=lmax - 1, history=history, cycle_history=cycle_history, ) if neighbor in history: for length in range(len(history[neighbor][:lmax - 1])): relation_polarity = graph[source][neighbor]['polarity'] for target in history[neighbor][length].keys(): if target not in _history_source[length + 1]: _history_source[length + 1][target] = [[0, 0], {}] activation_index = 0 if relation_polarity == 1 else 1 inhibition_index = 1 if relation_polarity == 1 else 0 # Get paths to target paths_to_target = [history[neighbor][length][target][0][0], history[neighbor][length][target][0][1]] # If there're no cycles, intermediate_nodes will not be modified # and there's no need for a costly deepcopy operation intermediate_nodes = history[neighbor][length][target][1] # Get paths starting from neighbor that have source as intermediate node paths_in_cycle = intermediate_nodes.get(source, [0, 0]) if paths_in_cycle[0] or paths_in_cycle[1]: # Cycle detected. # Find all paths / nodes involved in cycle so they can be removed # from neighbor's list before being added to source's. nodes_in_cycles = {} number_of_paths_in_cycles = [] if ( source in cycle_history[0] and neighbor in cycle_history[0][source] and target in cycle_history[0][source][neighbor] and length in cycle_history[0][source][neighbor][target] ): number_of_paths_in_cycles, nodes_in_cycles = cycle_history[0][source][neighbor][target][length] else: number_of_paths_in_cycles, nodes_in_cycles = get_paths_through( graph, neighbor, target, source, [], history, length, ) if source not in cycle_history[0]: cycle_history[0][source] = {} if neighbor not in cycle_history[0][source]: cycle_history[0][source][neighbor] = {} if target not in cycle_history[0][source][neighbor]: cycle_history[0][source][neighbor][target] = {} if length not in cycle_history[0][source][neighbor][target]: cycle_history[0][source][neighbor][target][length] = [number_of_paths_in_cycles, nodes_in_cycles] if target not in cycle_history[1]: cycle_history[1][target] = 0 cycle_history[1][target] += 1 # Manually copy intermediate_nodes to avoid calling deepcopy intermediate_nodes = { node: [paths[0], paths[1]] for node, paths in history[neighbor][length][target][1].items() } ``` -------------------------------- ### Count Paths and Ratios - Python Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html This function aggregates path counts and calculates the ratio of positive and negative paths. It handles division by zero by returning 0 if no paths exist. ```python source_to_target = previous_history[source][length][target_id] if simple_paths: source_to_target = source_to_target[0] count[t][0] += source_to_target[0] count[t][1] += source_to_target[1] count[t][2] += source_to_target[0] + source_to_target[1] total_number_of_paths = _count_paths(count, t, total_number_of_paths) return total_number_of_paths, count def _count_paths(count, t, total_number_of_paths): """Count ratio and number of paths.""" total_number_of_paths += count[t][2] # Calculate ratio of positive and negative paths count[t][0] = 0 if not count[t][2] else round(count[t][0] / count[t][2], 2) count[t][1] = 0 if not count[t][2] else round(count[t][1] / count[t][2], 2) return total_number_of_paths ``` -------------------------------- ### Explore Command Source: https://drug2ways.readthedocs.io/en/latest/cli.html The 'explore' command is used to run drug2ways on a given network. It allows for various options to customize the exploration process. ```bash drug2ways explore [OPTIONS] ``` -------------------------------- ### Compute All Paths (List Target) Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Recursively computes all paths from a source to a list of targets in a graph, storing path counts and history. Used for detailed path analysis. ```python # -*- coding: utf-8 -*- """Graph traversal methods.""" from typing import Any, Dict, Iterable, Tuple, List, Union from networkx import DiGraph __all__ = [ 'compute_all_paths_multitarget', 'compute_all_paths_multitarget_dict', ] def _compute_all_paths_multitarget(graph, source, targets, history, lmax): """Compute all paths and store history for each visited node containing number of paths already found. :param graph: graph :param source: source node :param targets: target nodes :param history: :param lmax: :return: """ if lmax == 0: return paths = [[[0, 0] for _ in targets] for _ in range(lmax)] for neighbor in graph.neighbors(source): if neighbor in targets or (not targets and graph.nodes[neighbor]['isTarget']): target_id = targets.index(neighbor) if graph[source][neighbor]['polarity'] == 1: paths[0][target_id][0] += 1 else: paths[0][target_id][1] += 1 continue if neighbor not in history or neighbor in history and len(history[neighbor]) < lmax - 1: _compute_all_paths_multitarget(graph, neighbor, targets, history, lmax - 1) # After a node has been visited, # history[neighbor] is a dictionary with # all paths found for lenghts < lmax. # Different keys in dict groups paths # by their size (in number of nodes). if neighbor in history: for length in range(len(history[neighbor][:lmax - 1])): if graph[source][neighbor]['polarity'] == 1: for target_id in range(len(targets)): paths[length + 1][target_id][0] += history[neighbor][length][target_id][0] paths[length + 1][target_id][1] += history[neighbor][length][target_id][1] else: for target_id in range(len(targets)): paths[length + 1][target_id][0] += history[neighbor][length][target_id][1] paths[length + 1][target_id][1] += history[neighbor][length][target_id][0] history[source] = paths ``` -------------------------------- ### Compute All Paths (Dict Target) Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Recursively computes all paths from a source to targets using a dictionary for history storage. Suitable for graphs where target identification is dynamic. ```python def _compute_all_paths_multitarget_dict(graph, source, targets, history, lmax): """Compute all paths and store history for each visited node containing number of paths already found. :param graph: graph :param source: source node :param targets: target nodes :param lmax: lmax :param history: """ if lmax == 0: return paths = [{} for _ in range(lmax)] for neighbor in graph.neighbors(source): if graph.nodes[neighbor]['isTarget']: if neighbor in targets or not targets: paths[0][neighbor] = [0, 0] if graph[source][neighbor]['polarity'] == 1: paths[0][neighbor][0] += 1 else: paths[0][neighbor][1] += 1 continue if neighbor not in history or neighbor in history and len(history[neighbor]) < lmax - 1: _compute_all_paths_multitarget_dict(graph, neighbor, targets, history, lmax - 1) # After a node has been visited, # history[neighbor] is a dictionary with # all paths found for lenghts < lmax. # Different keys in dict groups paths # by their size (in number of nodes). if neighbor in history: for length in range(len(history[neighbor][:lmax - 1])): relation_polarity = graph[source][neighbor]['polarity'] for target in history[neighbor][length].keys(): if target not in paths[length + 1]: paths[length + 1][target] = [0, 0] if relation_polarity == 1: paths[length + 1][target][0] += history[neighbor][length][target][0] paths[length + 1][target][1] += history[neighbor][length][target][1] else: paths[length + 1][target][0] += history[neighbor][length][target][1] paths[length + 1][target][1] += history[neighbor][length][target][0] history[source] = paths ``` -------------------------------- ### Pathway Analysis Command Source: https://drug2ways.readthedocs.io/en/latest/cli.html Run pathway enrichment analysis on paths using the 'pathway-analysis' command. This requires specifying the network graph and path-related options. ```bash drug2ways pathway-analysis [OPTIONS] ``` -------------------------------- ### List Available Network Formats Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Provides a list of all network formats that drug2ways can handle, excluding BEL-specific formats. ```python FORMATS = [ CSV, TSV, GRAPHML, BEL, NODE_LINK_JSON, ] ``` -------------------------------- ### Compute All Paths Multi-Target Dict Function Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Computes all paths to multiple targets using a dictionary for target path counts. Supports an option for computing only simple paths. ```python def compute_all_paths_multitarget_dict( graph: DiGraph, source, targets, lmax: int, previous_history: Dict, cycle_history: Union[Dict, Dict], simple_paths: bool = False, ) -> Tuple[int, List[List[Union[float, int]]]]: """Compute all paths to all the targets, separately. Uses dict to store target path count instead of array. :param graph: graph :param source: source node :param targets: target nodes :param lmax: lmax :param previous_history: history of visited nodes :param cycle_history: history of cycles :param simple_paths: simple paths mode """ if simple_paths: _compute_all_simple_paths_multitarget_dict( graph=graph, source=source, targets=targets, history=previous_history, lmax=lmax, cycle_history=cycle_history, ) else: _compute_all_paths_multitarget_dict( graph=graph, source=source, targets=targets, history=previous_history, lmax=lmax, ) # Initialize [relative_activations, relative_inhibitions, number_of_paths_to_target] count = [[0.0, 0.0, 0] for _ in targets] total_number_of_paths = 0 # Loop up in the history the results in each of the paths for t in range(len(targets)): target_id = targets[t] for length in range(lmax): if target_id not in previous_history[source][length]: continue ``` -------------------------------- ### Combine Command Source: https://drug2ways.readthedocs.io/en/latest/cli.html Use the 'combine' command to find drug combinations that optimize given targets within a network. Specify the network graph and combination length. ```bash drug2ways combine [OPTIONS] ``` -------------------------------- ### compute_all_paths_multitarget_dict Source: https://drug2ways.readthedocs.io/en/latest/algorithm.html Computes all paths to all targets, similar to `compute_all_paths_multitarget`, but uses a dictionary to store target path counts and supports an option for simple paths. ```APIDOC ## compute_all_paths_multitarget_dict ### Description Computes all paths to all the targets, separately. Uses dict to store target path count instead of array. ### Method (Not specified, likely a Python function call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Parameters - **graph** (DiGraph) - The input graph. - **source** (Any) - The starting node for path computation. - **targets** (Iterable[Any]) - The target nodes to reach. - **lmax** (int) - The maximum length of paths to compute. - **previous_history** (Dict) - A dictionary tracking the history of visited nodes. - **cycle_history** (Dict) - A dictionary tracking the history of cycles. - **simple_paths** (bool) - If True, only simple paths are computed. Defaults to False. ### Returns - **Tuple[int, List[List[Union[float, int]]]]** - A tuple containing the count of paths and a list of paths, where each path is a list of nodes (float or int). ``` -------------------------------- ### Define Gene Set File Paths Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Defines the local file paths for KEGG, Reactome, and WikiPathways gene sets, which are stored in the default drug2ways directory. ```python KEGG_GENESETS = os.path.join(DEFAULT_DRUG2WAYS_DIR, 'kegg.tsv') REACTOME_GENESETS = os.path.join(DEFAULT_DRUG2WAYS_DIR, 'reactome.tsv') WIKIPATHWAYS_GENESETS = os.path.join(DEFAULT_DRUG2WAYS_DIR, 'wp.tsv') ``` -------------------------------- ### Download Data from URL Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Downloads data from a given URL and saves it to a specified export path. This function is used for fetching gene set files. ```python def download_pathway(url: str, export_path: str) -> None: """Make a function that downloads the data for you, or uses a cached version at the given path. :param url: The URL of some data :param export_path: folder where decompressed file will be exported """ urlretrieve(url, export_path) # noqa: S310 ``` -------------------------------- ### Drug2Ways CLI Usage Source: https://drug2ways.readthedocs.io/en/latest/cli.html The base command for interacting with the Drug2Ways CLI. Use this to access specific commands and their arguments. ```bash drug2ways [OPTIONS] COMMAND [ARGS]... ``` -------------------------------- ### Ensure Gene Sets Downloaded Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Checks if gene set files exist locally and downloads them from their respective URLs if they are missing. This function ensures that the necessary gene set data is available for pathway predictions. ```python def ensure_genesets(): """Download gene sets.""" logger.info('Downloading genesets for pathway predictions...') if not os.path.exists(KEGG_GENESETS): download_pathway(KEGG_GENESETS_URL, KEGG_GENESETS) if not os.path.exists(REACTOME_GENESETS): download_pathway(REACTOME_GENESETS_URL, REACTOME_GENESETS) if not os.path.exists(WIKIPATHWAYS_GENESETS): download_pathway(WIKIPATHWAYS_GENESETS_URL, WIKIPATHWAYS_GENESETS) ``` -------------------------------- ### Define Gene Set URLs Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Specifies the URLs for downloading KEGG, Reactome, and WikiPathways gene set files from GitHub. ```python KEGG_GENESETS_URL = 'https://raw.githubusercontent.com/pathwayforte/pathway-forte/master/data/gmt_files/kegg.gmt' REACTOME_GENESETS_URL = 'https://raw.githubusercontent.com/pathwayforte/pathway-forte/master/data/gmt_files/reactome.gmt' WIKIPATHWAYS_GENESETS_URL = 'https://raw.githubusercontent.com/pathwayforte/pathway-forte/master/data/gmt_files/wikipathways.gmt' ``` -------------------------------- ### enumerate_paths Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/alternative_graph_traversal.html Enumerates all paths from a source node to a list of target nodes within a given maximum length. This function is intended for graph traversal and pathfinding but is marked as deprecated. ```APIDOC ## enumerate_paths ### Description Enumerates paths from a source node to target nodes up to a maximum length. This function is deprecated and not used in the package. ### Parameters * **graph** (DiGraph) - The input graph. * **source** (int) - The starting node for the paths. * **targets** (List[int]) - A list of target nodes. * **lmax** (int) - The maximum length of the paths to enumerate. * **cycle_free** (bool, optional) - If True, only cycle-free paths are returned. Defaults to False. ### Returns List[List[int]] - A list of all enumerated paths, where each path is a list of nodes. ``` -------------------------------- ### Compute All Paths Multi-Target Function Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Computes all paths to multiple targets, aggregating results separately for each target. It utilizes a history dictionary to store traversal information. ```python def compute_all_paths_multitarget( graph: DiGraph, source: Iterable[Any], targets, lmax: int, previous_history: Dict, ) -> Tuple[int, List[List[Union[float, int]]]]: """Compute all paths to all the targets, separately. :param graph: graph :param source: source nodes :param targets: target nodes :param lmax: lmax :param previous_history: previous history of visited nodes :return: """ _compute_all_paths_multitarget( graph=graph, source=source, targets=targets, history=previous_history, lmax=lmax, ) # Initialize [relative_activations, relative_inhibitions, number_of_paths_to_target] count = [[0.0, 0.0, 0] for _ in targets] total_number_of_paths = 0 # Loop up in the history the results in each of the paths for t in range(len(targets)): for length in range(lmax): source_to_target = previous_history[source][length][t] count[t][0] += source_to_target[0] count[t][1] += source_to_target[1] count[t][2] += source_to_target[0] + source_to_target[1] total_number_of_paths = _count_paths(count, t, total_number_of_paths) return total_number_of_paths, count ``` -------------------------------- ### Enumerate Paths in a Graph Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/alternative_graph_traversal.html Use this function to find all paths from a source node to target nodes within a specified maximum length. It handles cycle-free path enumeration if required. The function populates a history dictionary to store found paths. ```python # -*- coding: utf-8 -*- """Alternative methods for path calculations in graphs (depricated and not used in the package).""" from typing import List from networkx import DiGraph [docs] def enumerate_paths(graph, source, targets, lmax, cycle_free=False): """Enumerate paths. :param graph: graph :param source: source node :param targets: target nodes :param lmax: lmax :param cycle_free: :return: """ history = {} _enumerate_paths( graph=graph, source=source, targets=targets, history=history, lmax=lmax, cycle_free=cycle_free, ) paths = [] for length in range(lmax): for path in history[source][length]: paths.append(path) return paths def _enumerate_paths( graph: DiGraph, source: int, targets: List[int], lmax: int, history, cycle_free: bool, ): """Enumerate all paths. :param graph: graph :param source: source node :param targets: target nodes :param lmax: maximum number of edges to find a path :param history: :param cycle_free: :return: """ # dfs to traverse graph and store history # for each visited node # containing number of paths already found if lmax == 0: return if graph.nodes[source]['isTarget']: history[source] = history.get(source, [[] for _ in range(lmax)]) if source in targets or not targets: history[source][0] = [[source]] return else: return paths = [[] for _ in range(lmax)] for neighbor in graph.neighbors(source): # if not graph.nodes[neighbor]['isTarget'] and lmax == 1: # continue if neighbor not in history or neighbor in history and len(history[neighbor]) < lmax - 1: _enumerate_paths( graph=graph, source=neighbor, targets=targets, lmax=lmax - 1, history=history, cycle_free=cycle_free, ) # After a node has been visited, # history[neighbor] is a dictionary with # all paths found for lenghts < lmax. # Different keys in dict groups paths # by their size (in number of nodes). # If there are no paths of length k, k < lmax # entry will be None. if neighbor in history: for length in range(len(history[neighbor][:lmax - 1])): for hist_path in history[neighbor][length]: if cycle_free and source in hist_path: continue paths[length + 1].append([source] + hist_path) history[source] = paths ``` -------------------------------- ### Define Default Drug2Ways Directory Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Sets the default directory for drug2ways data using PyStow. This is used for storing gene sets and other resources. ```python import pystow DEFAULT_DRUG2WAYS_DIR = pystow.join('drug2ways') ``` -------------------------------- ### enumerate_paths Source: https://drug2ways.readthedocs.io/en/latest/algorithm.html Enumerates paths between a source and targets in a graph, with an option to find only cycle-free paths. ```APIDOC ## enumerate_paths ### Description Enumerate paths. ### Method (Not specified, likely a Python function call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Parameters - **graph** (Any) - The input graph. - **source** (Any) - The source node. - **targets** (Any) - The target nodes. - **lmax** (Any) - The maximum length. - **cycle_free** (bool) - If True, only cycle-free paths are returned. Defaults to False. ### Returns (Return type not specified in the source.) ``` -------------------------------- ### List BEL Network Formats Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Specifies the network formats that are specific to the BEL (Biological Expression Language) standard. ```python BEL_FORMATS = [ BEL, BEL_PICKLE, ] ``` -------------------------------- ### Validate with Data Command Source: https://drug2ways.readthedocs.io/en/latest/cli.html The 'validate-with-data' command performs validation using RCR against a network and experimental data. Specify the network graph and target drugs. ```bash drug2ways validate-with-data [OPTIONS] ``` -------------------------------- ### compute_all_paths_multitarget_dict Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/graph_traversal.html Computes all paths to multiple target nodes using a dictionary to store target path counts. This function supports an option to compute only simple paths and utilizes cycle history for more complex path analysis. ```APIDOC ## compute_all_paths_multitarget_dict ### Description Compute all paths to all the targets, separately. Uses dict to store target path count instead of array. ### Method compute_all_paths_multitarget_dict ### Parameters #### Path Parameters - **graph** (DiGraph) - The input graph. - **source** (source) - The starting node for path computation. - **targets** (targets) - The target node(s). - **lmax** (int) - The maximum path length to consider. - **previous_history** (Dict) - History of visited nodes. - **cycle_history** (Union[Dict, Dict]) - History of cycles. - **simple_paths** (bool) - If True, computes only simple paths. Defaults to False. ### Returns - **Tuple[int, List[List[Union[float, int]]]]** - A tuple containing the total number of paths and a list of path counts for each target. ``` -------------------------------- ### compute_all_paths_multitarget Source: https://drug2ways.readthedocs.io/en/latest/algorithm.html Computes all paths to all specified targets from a given source node in a graph. It considers a maximum path length and tracks previous node history. ```APIDOC ## compute_all_paths_multitarget ### Description Computes all paths to all the targets, separately. ### Method (Not specified, likely a Python function call) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (None specified) ### Parameters - **graph** (DiGraph) - The input graph. - **source** (Iterable[Any]) - The starting nodes for path computation. - **targets** (Iterable[Any]) - The target nodes to reach. - **lmax** (int) - The maximum length of paths to compute. - **previous_history** (Dict) - A dictionary tracking the history of visited nodes. ### Returns - **Tuple[int, List[List[Union[float, int]]]]** - A tuple containing the count of paths and a list of paths, where each path is a list of nodes (float or int). ``` -------------------------------- ### Define Graph Column Names Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Defines the standard column names used for representing graph data: 'source', 'target', and 'polarity' for the relation. ```python SOURCE = 'source' TARGET = 'target' RELATION = 'polarity' ``` -------------------------------- ### Define Network Formats Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Defines constants for various network file formats supported by drug2ways, including CSV, TSV, GraphML, BEL, and JSON. ```python CSV = 'csv' TSV = 'tsv' GRAPHML = 'graphml' BEL = 'bel' NODE_LINK_JSON = 'json' BEL_PICKLE = 'pickle' GML = 'gml' EDGE_LIST = '.lst' ``` -------------------------------- ### Define Format Separator Mapping Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Maps CSV and TSV formats to their respective delimiter characters (comma and tab). ```python FORMAT_SEPARATOR_MAPPING = { CSV: ',', TSV: ' ' } ``` -------------------------------- ### Drug2Ways Emoji Source: https://drug2ways.readthedocs.io/en/latest/_modules/drug2ways/constants.html Defines the emoji used to represent drug2ways in the documentation or interface. ```python EMOJI = "💊🔬" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.