### Install NicheNetPy Source: https://saeyslab.github.io/nichenetpy Use pip to install the NicheNetPy package. ```bash pip install nichenetpy ``` -------------------------------- ### Get Ligands Method Source: https://saeyslab.github.io/nichenetpy/nichenetpy/network.html Retrieves all ligands present in the network as a set. ```python 296 def get_ligands(self) -> set[gene_t]: 297 ''' 298 Get all the ligands present in the network. 299 300 Returns 301 ------- 302 set 303 set of ligands present in the network 304 ''' 305 return set(self.key_iter()) ``` -------------------------------- ### Construct Ligand-Target Matrix Source: https://saeyslab.github.io/nichenetpy/nichenetpy/model_construction.html Constructs the ligand-target matrix starting from source weights, handling hub correction and optional matrix returns. ```python if ( type(source_weights) is dict and sum(source_weights.values()) == 0 ) or ( type(source_weights) is pd.DataFrame and sum(source_weights["weight"]) == 0 ): return ( { "weighted networks": None, "grn matrix": None, "ltf matrix": None, "ligand-target matrix": None }, ) if ligands is None: ligands = set(lr_network["from"]) weighted_networks = construct_weighted_networks( lr_network, sig_network, gr_network, source_weights ) if weighted_networks["lr_sig"].shape[0] > 0: weighted_networks["lr_sig"] = apply_hub_correction(weighted_networks["lr_sig"], hub=lr_sig_hub) weighted_networks["gr"] = apply_hub_correction(weighted_networks["gr"], hub=gr_hub) res = construct_ligand_target_matrix( weighted_networks, lr_network, ligands, damping_factor=damping_factor, ltf_cutoff=ltf_cutoff, return_all_matrices=return_all_matrices ) if return_all_matrices: ligand2target, grn_matrix, ltf_matrix = res else: ligand2target = res grn_matrix = None ltf_matrix = None else: # lr_sig is empty -> lt_matrix is grn_matrix grn_matrix = construct_tf_target_matrix( weighted_networks, standalone_output=True ) grn_matrix = (grn_matrix[0].toarray(order="F"), grn_matrix[1], grn_matrix[2]) ligand2target = grn_matrix ltf_matrix = None output = { "weighted networks": weighted_networks, "grn matrix": grn_matrix, "ltf matrix": ltf_matrix, "ligand-target matrix": ( ligand2target if ligand2target[0].flags.f_contiguous else (ligand2target[0].copy(order="F"), ligand2target[1], ligand2target[2]) ) } if not return_all_matrices: output.pop("grn matrix") output.pop("ltf matrix") if not return_weighted_networks: output.pop("weighted networks") return output ``` -------------------------------- ### Get ligands from ligand-target matrix Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prediction.html Retrieves all ligands present in the ligand-target matrix as a set. ```python 147 def get_ligands(self) -> set[gene_t]: 148 ''' 149 Get the ligands from the ligand-target matrix. 150 151 Returns 152 ------- 153 set 154 all ligands in the ligand-target matrix 155 ''' 156 return set(self._ligand2index.keys()) ``` -------------------------------- ### construct_model_from_source_weights Source: https://saeyslab.github.io/nichenetpy/nichenetpy/model_construction.html Constructs the ligand-target matrix starting from provided source weights and interaction networks. ```APIDOC ## construct_model_from_source_weights(source_weights, lr_sig_hub, gr_hub, ltf_cutoff, damping_factor, lr_network, gr_network, sig_network, ligands=None, return_all_matrices=True, return_weighted_networks=True) ### Description Construct the ligand-target matrix starting from the source weights. Sources with higher weights contribute more to the final model performance. ### Parameters - **source_weights** (pandas.DataFrame or dict) - Required - Dataframe or dictionary containing weights for each data source. - **lr_sig_hub** (float) - Required - Correction factor for hubiness (0 to 1) for ligand-receptor/signaling. - **gr_hub** (float) - Required - Correction factor for hubiness (0 to 1) for gene regulation. - **ltf_cutoff** (float) - Required - Quantile cutoff for ligand-tf scores. - **damping_factor** (float) - Required - Damping factor for the PPR algorithm. - **lr_network** (pandas.DataFrame) - Required - Dataframe containing ligand-receptor interactions. - **gr_network** (pandas.DataFrame) - Required - Dataframe containing gene regulatory interactions. - **sig_network** (pandas.DataFrame) - Required - Dataframe containing signaling interactions. - **ligands** (Iterable[gene_t] or None) - Optional - Ligands to include in the model. - **return_all_matrices** (bool) - Optional - Whether to return ligand-tf and tf-target matrices. - **return_weighted_networks** (bool) - Optional - Whether to return the weighted networks. ### Returns - **dict** - A dictionary with keys 'weighted networks', 'grn matrix', 'ltf matrix' and 'ligand-target matrix'. ``` -------------------------------- ### Get genes from ligand-target matrix Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prediction.html Retrieves all genes present in the ligand-target matrix as a set. ```python 158 def get_genes(self) -> set[gene_t]: 159 ''' 160 Get the genes from the ligand-target matrix. 161 162 Returns 163 ------- 164 set 165 all genes in the ligand-target matrix 166 ''' 167 return set(self._gene2index.keys()) ``` -------------------------------- ### infer_supporting_datasources Source: https://saeyslab.github.io/nichenetpy/nichenetpy/wrappers.html Get the data sources that support the specific interactions in the extracted ligand-target signaling subnetwork. ```APIDOC ## infer_supporting_datasources(tf_signaling, tf_regulatory, lr_network, sig_network, gr_network) ### Description Get the data sources that support the specific interactions in the extracted ligand-target signaling subnetwork. ### Parameters - **tf_signaling** (pd.DataFrame) - Dataframe which contains weighted ligand-receptor and signaling interactions (from, to, weight) - **tf_regulatory** (pd.DataFrame) - Dataframe containing regulatory interactions - **lr_network** (pd.DataFrame) - Ligand-receptor network dataframe - **sig_network** (pd.DataFrame) - Signaling network dataframe - **gr_network** (pd.DataFrame) - Gene regulatory network dataframe ``` -------------------------------- ### Retrieve Indices and Sets Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prediction.html Methods to retrieve indices for specific ligands or genes, and to get the full sets of ligands and genes present in the matrix. ```python def ligand2index(self, ligand:gene_t): ''' Get the index of the ligand in the ligand-target matrix Returns ------- int the index Raises ------ ValueError if the ligand is not present in the ligand-target matrix ''' if ligand not in self._ligand2index: raise ValueError(f"{ligand} not in ligand_target_matrix") return self._ligand2index[ligand] def gene2index(self, gene:gene_t): ''' Get the index of the gene in the ligand-target matrix Returns ------- int the index Raises ------ ValueError if the gene is not present in the ligand-target matrix ''' if gene not in self._gene2index: raise ValueError(f"{gene} not in ligand_target_matrix") return self._gene2index[gene] def get_ligands(self) -> set[gene_t]: ''' Get the ligands from the ligand-target matrix. Returns ------- set all ligands in the ligand-target matrix ''' return set(self._ligand2index.keys()) def get_genes(self) -> set[gene_t]: ''' Get the genes from the ligand-target matrix. Returns ------- set all genes in the ligand-target matrix ''' return set(self._gene2index.keys()) ``` -------------------------------- ### Initialize Network Class Source: https://saeyslab.github.io/nichenetpy/nichenetpy/network.html The constructor accepts a mapping (list or pandas DataFrame) or a filename to build the network index. ```python class Network: ''' A network with links. This is in essence a one to many mapping. Parameters ---------- mapping : list or pandas.DataFrame or None sorted list of tuples (from, to) or pandas dataframe with keys ("from", "to") filename : str or None name of the file to read the network from Raises ------ TypeError if the arguments have the wrong type ValueError if neither mapping nor filename is provided Attributes ---------- mapping : list sorted list of tuples (from, to) _index : dict index for the mapping Notes ----- You must pass a list SORTED by "from" as mapping, a pandas dataframe with keys ("from", "to") or the name of a file to read from. ''' def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str|None=None): if mapping is not None: if type(mapping) is pd.DataFrame: mapping = sorted( zip(mapping["from"].tolist(), mapping["to"].tolist()), key=lambda x : x[0] ) elif type(mapping) is not list: raise TypeError(f"mapping should have type list or pandas.DataFrame, was {type(mapping)}") self._mapping = mapping elif filename is not None: if type(filename) is not str: raise TypeError(f"filename should have type str, was {type(filename)}") self._mapping = sorted( read_network(filename), key=lambda x : x[0] ) else: raise ValueError("either mapping or filename must be provided as arguments") self._index = dict() self._build_index() ``` -------------------------------- ### Network.__init__ Source: https://saeyslab.github.io/nichenetpy/nichenetpy/network.html Initializes a new Network instance from a mapping (list or DataFrame) or a file. ```APIDOC ## Network(mapping=None, filename=None) ### Description Initializes the network object. You must provide either a mapping (list of tuples or pandas DataFrame) or a filename to load the network from. ### Parameters - **mapping** (list|pd.DataFrame|None) - Optional - A sorted list of (from, to) tuples or a pandas DataFrame with 'from' and 'to' columns. - **filename** (str|None) - Optional - The path to a file containing network data. ``` -------------------------------- ### EvaluationData.__init__ Source: https://saeyslab.github.io/nichenetpy/nichenetpy/evaluation.html Initializes a new EvaluationData instance with optional initial data and custom key mappings. ```APIDOC ## EvaluationData.__init__(obj=None, key_name='name', ligand_name='from', de_genes_name='response') ### Description Initializes the EvaluationData object. It can ingest data from a dictionary, pandas DataFrame, ItemsView, or an iterable of dictionaries. ### Parameters - **obj** (dict | Iterable | ItemsView | pandas.DataFrame) - Optional - The initial data to populate the object. - **key_name** (str) - Optional - The key name for the data element identifier (default: 'name'). - **ligand_name** (str) - Optional - The key name for the ligand (default: 'from'). - **de_genes_name** (str) - Optional - The key name for the target genes (default: 'response'). ``` -------------------------------- ### GeneAliasInfo.__init__(arg) Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the GeneAliasInfo object by loading mappings from a file path or a dictionary. ```APIDOC ## GeneAliasInfo.__init__(arg) ### Description Initializes the GeneAliasInfo instance. If a string is provided, it reads a CSV file to build the mapping. If a dictionary is provided, it uses it directly as the mapping. ### Parameters - **arg** (str | dict[str, tuple[str, int | None]]) - Required - A file path to a CSV containing mappings or a dictionary of mappings. ### Raises - **TypeError** - If the argument is not a string or a dictionary. ``` -------------------------------- ### Initialize and Validate Ligand-Target Matrix Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prediction.html Handles the initialization of the ligand-target matrix, enforcing column-major format for performance and validating input types for row and column names. ```python 67 ligand_target_matrix:nichenet_matrix, 68 row_names:list[gene_t]|tuple[gene_t], 69 col_names:list[gene_t]|tuple[gene_t] 70 ) -> None: 71 self.ligand_target_matrix = ligand_target_matrix 72 if type(ligand_target_matrix) is csr_matrix: 73 warnings.warn("a scipy.csr_matrix was passed, this will result in extremely slow column indexing and is therefore not supported, the matrix is automatically converted to column-major format") 74 if self.matrix_density() > 0.5: 75 self.ligand_target_matrix = self.ligand_target_matrix.toarray(order="F") 76 else: 77 self.ligand_target_matrix = csc_matrix(self.ligand_target_matrix) 78 elif type(ligand_target_matrix) is csc_matrix: 79 density = self.matrix_density() 80 if density > 0.5: 81 warnings.warn(f"a scipy.csc_matrix was passed with a density of {density}, the reduction in memory consumption may not be worth the increased time to index columns, consider using a column-major numpy.ndarray in stead") 82 elif type(ligand_target_matrix) is np.ndarray: 83 if ligand_target_matrix.flags.c_contiguous: 84 warnings.warn("a row-major numpy.ndarray was passed, consider converting to a column-major numpy.ndarray for faster column indexing") 85 else: 86 raise TypeError(f"ligand_target_matrix should have type numpy.ndarray, scipy.csr_matrix or scipy.csc_matrix, was {type(ligand_target_matrix)}") 87 if type(row_names) is not list and type(row_names) is not tuple: 88 raise TypeError(f"row_names should have type list[gene_t] or tuple[gene_t], was {type(row_names)}") 89 if type(col_names) is not list and type(col_names) is not tuple: 90 raise TypeError(f"col_names should have type list[gene_t] or tuple[gene_t], was {type(col_names)}") 91 self.row_names = row_names 92 self.col_names = col_names 93 self._ligand2index = dict(zip(self.col_names, range(len(self.col_names)))) 94 self._gene2index = dict(zip(self.row_names, range(len(self.row_names)))) ``` -------------------------------- ### Get Gene Index Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prediction.html Retrieves the index of a specific gene, raising a ValueError if the gene is not found. ```python 129 def gene2index(self, gene:gene_t): 130 ''' 131 Get the index of the gene in the ligand-target matrix 132 133 Returns 134 ------- 135 int 136 the index 137 138 Raises 139 ------ 140 ValueError 141 if the gene is not present in the ligand-target matrix 142 ''' 143 if gene not in self._gene2index: 144 raise ValueError(f"{gene} not in ligand_target_matrix") 145 return self._gene2index[gene] ``` -------------------------------- ### Get Ligand Index Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prediction.html Retrieves the index of a specific ligand, raising a ValueError if the ligand is not found. ```python 111 def ligand2index(self, ligand:gene_t): 112 ''' 113 Get the index of the ligand in the ligand-target matrix 114 115 Returns 116 ------- 117 int 118 the index 119 120 Raises 121 ------ 122 ValueError 123 if the ligand is not present in the ligand-target matrix 124 ''' 125 if ligand not in self._ligand2index: 126 raise ValueError(f"{ligand} not in ligand_target_matrix") 127 return self._ligand2index[ligand] ``` -------------------------------- ### construct_and_evaluate(source_weights, lr_sig_hub, gr_hub, ltf_cutoff, damping_factor, lr_network, gr_network, sig_network, evaluation_data, return_all_matrices, return_weighted_networks) Source: https://saeyslab.github.io/nichenetpy/nichenetpy/parameter_optimization.html Constructs and evaluates the ligand-target matrix, returning the matrices and prediction scores. ```APIDOC ## construct_and_evaluate ### Description Construct and evaluate the ligand-target matrix. Returns the matrices and the prediction scores. ### Parameters - **source_weights** (dict[str, float]|dict[int, float]|pd.DataFrame) - Required - Dataframe or dictionary which contains the weights associated to each individual data source. Sources with higher weights will contribute more to the final model performance. - **lr_sig_hub** (float) - Required - Parameter for hub gene handling. - **gr_hub** (float) - Required - Parameter for gene regulatory hub handling. - **ltf_cutoff** (float) - Required - Cutoff for ligand-target-factor matrix. - **damping_factor** (float) - Required - Damping factor for network propagation. - **lr_network** (pd.DataFrame) - Required - Ligand-receptor network. - **gr_network** (pd.DataFrame) - Required - Gene regulatory network. - **sig_network** (pd.DataFrame) - Required - Signaling network. - **evaluation_data** (EvaluationData) - Required - Data used for evaluation. - **return_all_matrices** (bool) - Optional - Whether to return all matrices. - **return_weighted_networks** (bool) - Optional - Whether to return weighted networks. ``` -------------------------------- ### linked_iter(start, nxt, stp) Source: https://saeyslab.github.io/nichenetpy/nichenetpy/utils.html An iterator that yields values based on a next-step function and a stopping condition. ```APIDOC ## linked_iter(start, nxt, stp) ### Description Yields all values reached by calling the 'nxt' function on the current value until the 'stp' function returns True. ### Parameters - **start** (Any) - Required - The starting value. - **nxt** (Callable) - Required - Function that returns the next value. - **stp** (Callable) - Required - Function that takes the current and next element as input and decides when to stop. ### Yields - **Any** - All encountered values. ``` -------------------------------- ### construct_and_evaluate(source_weights, lr_sig_hub, gr_hub, ltf_cutoff, damping_factor, lr_network, gr_network, sig_network, evaluation_data, return_all_matrices=True, return_weighted_networks=True) Source: https://saeyslab.github.io/nichenetpy/nichenetpy/parameter_optimization.html Constructs and evaluates the ligand-target matrix, returning the resulting matrices and prediction scores. ```APIDOC ## construct_and_evaluate ### Description Constructs and evaluates the ligand-target matrix. Returns the matrices and the prediction scores. ### Parameters - **source_weights** (dict[str, float] | dict[int, float] | pandas.DataFrame) - Required - Dataframe or dictionary containing weights for each data source. - **lr_sig_hub** (float) - Required - Correction factor for hubiness (0 to 1). - **gr_hub** (float) - Required - Correction factor for hubiness (0 to 1). - **ltf_cutoff** (float) - Required - Quantile cutoff for ligand-tf scores. - **damping_factor** (float) - Required - Damping factor for the PPR algorithm. - **lr_network** (pandas.DataFrame) - Required - Ligand-receptor interactions. - **gr_network** (pandas.DataFrame) - Required - Gene regulatory interactions. - **sig_network** (pandas.DataFrame) - Required - Signaling interactions. - **evaluation_data** (EvaluationData) - Required - The evaluation data object. - **return_all_matrices** (bool) - Optional - Whether to return ligand-tf and tf-target matrices. Default: True. - **return_weighted_networks** (bool) - Optional - Whether to return weighted networks. Default: True. ### Returns - **dict** - A dictionary with keys 'weighted networks', 'grn matrix', 'ltf matrix' and 'ligand-target matrix'. - **float** - target prediction AUROC. - **float** - target prediction AUPR. - **float** - ligand prediction AUROC. - **float** - ligand prediction AUPR. ### Raises - **TypeError** - If the arguments have the wrong type. ``` -------------------------------- ### Get Average Expression Source: https://saeyslab.github.io/nichenetpy/nichenetpy/prioritization.html Calculates the average gene expression per cell type, with optional filtering by condition. ```python def get_avg_exp( ann:AnnData, celltype_col:str, condition_oi:str|None=None, condition_col:str|None=None, layer:str="counts", features:Iterable[gene_t]|None=None ) -> pd.DataFrame: ''' Calculate the average gene expression per cell type. If condition_oi is provided, only consider cells from that condition. Parameters ---------- ann : AnnData the AnnData object celltype_col : str the column in ann.obs which contains the celltypes condition_oi : str or None ``` -------------------------------- ### Create Ligand Activity Heatmap Source: https://saeyslab.github.io/nichenetpy/nichenetpy/wrappers.html Visualizes ligand activity metrics using a 1D heatmap. ```python def create_ligand_activity_heatmap( ligand_activities_sorted:Iterable[tuple], title:str="ligand activity", cbar_label:str="AUPR", cmap:str="YlOrRd", figsize:tuple[float, float]=(6, 6) ): ''' Creates a ligand activity heatmap. Parameters ---------- ligand_activities_sorted : Iterable of tuple the computed metrics for each ligand title : str the title of the plot cbar_label : str the label of the color bar cmap : str the color map figsize : tuple of float the size of the figure Returns ------- Figure the figure Axes the axes ''' ligands, metrics = zip(*ligand_activities_sorted) fig, ax = heatmap_1d( [e["aupr_corrected"] for e in metrics], labels=ligands, title=title, cbar_label=cbar_label, cmap=cmap, figsize=figsize ) ax.invert_yaxis() return (fig, ax) ``` -------------------------------- ### Get applicable evaluation datasets Source: https://saeyslab.github.io/nichenetpy/nichenetpy/evaluation.html Filters evaluation data to return only datasets where the ligand is present in the predictor's ligand-target matrix. ```python def get_applicable_evaluation_datasets( self, predictor:LigandActivityPredictor, combination:bool=True ): ''' get the subset of applicable evaluation data (evaluation data where the ligand is present in the ligand-target matrix and there is at least one true sample for a gene that is present in the ligand-target matrix) Parameters ---------- predictor : LigandActivityPredictor the ligand activity predictor combination : bool whether or not to allow combinations of ligands Yields ------- str the key of the dataset dict the applicable dataset ''' if not isinstance(predictor, LigandActivityPredictor): ``` -------------------------------- ### Initialize GeneAliasInfo Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the GeneAliasInfo class with either a file path or a dictionary of alias mappings. ```python class GeneAliasInfo: ''' This class facilitates gene alias conversion. Parameters ---------- arg : str or dict name of the file to read gene alias information from or a dict which contains the alias mappings: alias -> (symbol, entrez) Raises ------ TypeError if arg is not of the correct type ''' def __init__(self, arg:str|dict[str, tuple[str, int|None]]) -> None: if type(arg) is str: with open(arg) as file: lines = file.readlines() symbol, entrez, alias = zip(*([word.strip("\"\'") for word in line.rstrip().split(",")] for line in lines[1:])) self._mapping = dict(zip(alias, zip(symbol, (None if e == "" else int(e) for e in entrez)))) elif type(arg) is dict: self._mapping = arg else: raise TypeError(f"arg should have type str or dict, was {type(arg)}") ``` -------------------------------- ### GeneAliasInfo.__init__ Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the GeneAliasInfo object with alias mappings from a file or a dictionary. ```APIDOC ## __init__(arg: str | dict[str, tuple[str, int | None]]) ### Description Initializes the gene alias converter. The input can be a path to a CSV file or a dictionary mapping aliases to (symbol, entrez) tuples. ### Parameters - **arg** (str | dict) - Required - The name of the file to read gene alias information from or a dictionary containing the alias mappings. ``` -------------------------------- ### Get weighted ligand-receptor links Source: https://saeyslab.github.io/nichenetpy/nichenetpy/extraction.html Retrieves weighted interactions between specified ligands and receptors using a provided network and weighted signature. ```python 100def get_weighted_ligand_receptor_links( 101 best_upstream_ligands:Iterable[gene_t], 102 expressed_receptors:Iterable[gene_t], 103 lr_network:LigandReceptorNetwork, 104 lr_sig:WeightedNetwork 105) -> WeightedNetwork: 106 ''' 107 Get the weighted ligand-receptor links between a possible ligand and its receptors. 108 109 Parameters 110 ---------- 111 best_upstream_ligands : Iterable of gene_t 112 the ligands of interest 113 expressed_receptors : Iterable of gene_t 114 the receptors expressed in the cell type of interest 115 lr_network : LigandReceptorNetwork 116 the ligand-receptor network containing the ligand-receptor interactions 117 lr_sig : WeightedNetwork 118 a weighted network containing the ligand-receptor interactions and their weights 119 120 Returns 121 ------- 122 WeightedNetwork 123 the weighted ligand-receptor links 124 125 Raises 126 ------ 127 TypeError 128 if the arguments have the wrong type 129 ''' 130 if not isinstance(best_upstream_ligands, Iterable): 131 raise TypeError(f"best_upstream_ligands should be an Iterable of strings, was {type(best_upstream_ligands)}") 132 elif type(best_upstream_ligands) is not set: 133 best_upstream_ligands = set(best_upstream_ligands) 134 if not isinstance(expressed_receptors, Iterable): 135 raise TypeError(f"expressed_receptors should be an Iterable of strings, was {type(expressed_receptors)}") 136 elif type(expressed_receptors) is not set: 137 expressed_receptors = set(expressed_receptors) 138 if type(lr_network) is not LigandReceptorNetwork: 139 raise TypeError(f"lr_network should have type LigandReceptorNetwork, was {type(lr_network)}") 140 if type(lr_sig) is not WeightedNetwork: 141 raise TypeError(f"lr_sig should have type WeightedNetwork, was {type(lr_sig)}") 142 lr_sig = lr_sig.subset(set(lr_network)) 143 best_upstream_receptors = set(to for fr, to in lr_network if fr in best_upstream_ligands and to in expressed_receptors) 144 # from best upstream ligand to best upstream receptor 145 return lr_sig.subset_sep(best_upstream_ligands.intersection(set(e[0] for e in lr_network)), best_upstream_receptors) ``` -------------------------------- ### Initialize GeneAliasInfo Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the class with a file path to a mapping CSV or a dictionary of mappings. ```python 22 def __init__(self, arg:str|dict[str, tuple[str, int|None]]) -> None: 23 if type(arg) is str: 24 with open(arg) as file: 25 lines = file.readlines() 26 symbol, entrez, alias = zip(*([word.strip("\"\'") for word in line.rstrip().split(",")] for line in lines[1:])) 27 self._mapping = dict(zip(alias, zip(symbol, (None if e == "" else int(e) for e in entrez)))) 28 elif type(arg) is dict: 29 self._mapping = arg 30 else: 31 raise TypeError(f"arg should have type str or dict, was {type(arg)}") ``` -------------------------------- ### WeightedNetwork.__init__ Source: https://saeyslab.github.io/nichenetpy/nichenetpy/network.html Initializes a new WeightedNetwork instance from a list of tuples or a pandas DataFrame, or by reading from a file. ```APIDOC ## WeightedNetwork(mapping=None, filename=None) ### Description Initializes a ligand-receptor network with weighted links. The network can be constructed from a provided mapping (list of tuples or pandas DataFrame) or loaded from a file. ### Parameters - **mapping** (list | pandas.DataFrame | None) - Optional - A sorted list of tuples (from, to, weight) or a pandas DataFrame with columns 'from', 'to', and 'weight'. - **filename** (str | None) - Optional - The path to a file containing the network data. ### Raises - **TypeError** - Raised if the provided arguments do not match the expected types. ``` -------------------------------- ### Get reachable nodes in a graph Source: https://saeyslab.github.io/nichenetpy/nichenetpy/graph.html Identifies all nodes reachable from a specified source node using a breadth-first search approach on a CSR matrix. ```python def get_reachable_nodes( graph:csr_matrix, src:int ) -> set[int]: ''' Returns all nodes in the graph which are reachable from the specified source node. Parameters ---------- graph : csr_matrix the graph (as adjacency matrix) src : int the source node Returns ------- set of int the set of reachable nodes Raises ------ TypeError if the arguments are not of the correct type ''' if type(graph) is not csr_matrix: raise TypeError(f"graph should have type csr_matrix, was {type(graph)}") if type(src) is not int: raise TypeError(f"src should have type int, was {type(src)}") output = {src} q = [src] while len(q) > 0: cur = q.pop() nxts = graph.indices[graph.indptr[cur]:graph.indptr[cur+1]] for nxt in nxts: if nxt not in output: # if nxt is in output it's neighbours have already been visited or nxt is already queued q.append(nxt) output.add(nxt) return output ``` -------------------------------- ### linked_iter(start: any, nxt: Callable, stp: Callable) Source: https://saeyslab.github.io/nichenetpy/nichenetpy/utils.html Yields all values reached by calling nxt on the current value until stp returns True. ```APIDOC ## linked_iter(start: any, nxt: Callable, stp: Callable) ### Description Yields all values reached by calling nxt on the current value until stp returns True. ### Parameters - **start** (Any) - Required - The starting value. - **nxt** (Callable) - Required - Function that returns the next value. - **stp** (Callable) - Required - Function that takes the current and next element as input and decides when to stop. ### Yields - **Any** - All encountered values. ``` -------------------------------- ### Initialize GeneInfo class Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the GeneInfo object using either a file path or an iterable of gene symbol tuples. ```python 123 def __init__(self, arg:str|Iterable[tuple[str, str]]): 124 if type(arg) is str: 125 with open(arg) as file: 126 lines = file.readlines() 127 symbol, _, _, symbol_mouse = zip(*([word.strip("\"\'") for word in line.rstrip().split(",")] for line in lines[1:])) 128 self.__init__(list(zip(symbol, symbol_mouse))) 129 elif isinstance(arg, Iterable): 130 # one to many 131 self._human2mouse = Network( 132 sorted( 133 ((sh, sm) for sh, sm in arg if sh != "NA" and sm != "NA"), 134 key=lambda x : x[0] 135 ) 136 ) 137 # one to one 138 self._mouse2human = dict(((sm, sh) for sh, sm in arg)) 139 else: 140 raise TypeError(f"arg should have type str or dict, was {type(arg)}") ``` -------------------------------- ### Return empty solution Source: https://saeyslab.github.io/nichenetpy/nichenetpy/parameter_optimization.html Returns a default structure representing an empty model solution. ```python def _empty_solution(): return ( { "weighted networks": None, "grn matrix": None, "ltf matrix": None, "ligand-target matrix": None }, 0, 0, 0, 0 ) ``` -------------------------------- ### Get geneset of interest from AnnData Source: https://saeyslab.github.io/nichenetpy/nichenetpy/wrappers.html Extracts a set of genes from an AnnData object that are likely influenced by ligands, supporting both custom metrics and Scanpy-based differential expression. ```python def get_geneset_oi( ann:AnnData, receiver:str, condition_col:str, condition_oi:str, layer:str="data", max_pval_adj:float=0.05, min_abs_lfc:float=0.25, min_pct:float=0.05, use_scanpy:bool=False, scanpy_corr_method:str="benjamini-hochberg", scanpy_tie_correct:bool=False, celltype_col:str="celltype", lfc_denormalize:Callable[[nichenet_matrix], nichenet_matrix]|None=np.expm1 ) -> set[str]: ''' Gets the geneset of interest from an AnnData object. The gene set of interest are genes within the receiver cell type that are likely to be influenced by ligands from the CCC event. Parameters ---------- ann : AnnData the AnnData object to extract expressed genes from receiver : str the receiver cell type condition_col : str the name of the column in obs which contains the conditions condition_oi : str the condition of interest layer : str the name of the layer which contains the data matrix max_pval_adj : float the upper bound for pval_adj min_lfc : float the lower bound for lfc, min_pct : float the lower bound for the pct use_scanpy : bool if true, use scanpy.tl.rank_genes_groups to compute the metrics scanpy_corr_method : str corr_method argument passed to scanpy.tl.rank_genes_groups scanpy_tie_correct : bool tie_correct argument passed to scanpy.tl.rank_genes_groups celltype_col : str the column in the anndata object which contains the celltype lfc_denormalize : Callable or None a denormalization function to apply prior to the calculation of the log fold changes only used with use_scanpy=False Returns ------- list the geneset of interest Notes ----- With `use_scanpy`=True, `scanpy_corr_method`="bonferroni" and `scanpy_tie_correct`=True only the log fold changes will be different compared to `use_scanpy`=False ''' ann_receiver = subset_ann( ann, val=receiver, layers=[layer], val_col=celltype_col ) if use_scanpy: # lfc will be different sc.tl.rank_genes_groups( ann_receiver, groupby=condition_col, layer=layer, pts=True, method="wilcoxon", corr_method=scanpy_corr_method, tie_correct=scanpy_tie_correct ) DE_table = rank_genes_groups_to_dataframe(ann_receiver, condition_col) DE_table = DE_table[ (DE_table["pval_adj"] <= max_pval_adj) & (abs(DE_table["lfc"]) >= min_abs_lfc) & (DE_table["pct"] >= min_pct) ] else: group_metrics( ann_receiver, groupby=condition_col, layer=layer, min_pct=min_pct, min_abs_lfc=min_abs_lfc, lfc_denormalize=lfc_denormalize ) DE_table = ann_receiver.uns["group_metrics"] return set( DE_table[ ``` -------------------------------- ### Get ties from an Iterable Source: https://saeyslab.github.io/nichenetpy/nichenetpy/utils.html Groups indices of tied elements within an iterable based on a provided key function. Returns a dictionary mapping values to lists of indices. ```python 621def get_ties( 622 it:Iterable, 623 key:Callable 624): 625 ''' 626 Group the indices of the tied elements of an Iterable. 627 628 Parameters 629 ---------- 630 it : Iterable 631 the values to get the ties from 632 key : Callable 633 function to call on elements of it which returns the values of interest 634 635 Returns 636 ------- 637 dict 638 a dictionary which maps tied values to groups of indices whose corresponging values equal the key 639 640 Raises 641 ------ 642 TypeError 643 if the arguments have the wrong type 644 ''' 645 if not isinstance(it, Iterable): 646 raise TypeError(f"it should have type Iterable, was {type(it)}") 647 if not isinstance(key, Callable): 648 raise TypeError(f"key should have type Callable, was {type(key)}") 649 output = dict() 650 for i, v in enumerate(it): 651 v = key(v) 652 if v in output: 653 output[v].append(i) 654 else: 655 output[v] = [i] 656 return output ``` -------------------------------- ### Construct and evaluate model Source: https://saeyslab.github.io/nichenetpy/nichenetpy/parameter_optimization.html Constructs and evaluates a ligand-target matrix using provided network weights and parameters. ```python def construct_and_evaluate( source_weights:dict[str, float]|dict[int, float]|pd.DataFrame, lr_sig_hub:float, gr_hub:float, ltf_cutoff:float, damping_factor:float, lr_network:pd.DataFrame, gr_network:pd.DataFrame, sig_network:pd.DataFrame, evaluation_data:EvaluationData, return_all_matrices:bool=True, return_weighted_networks:bool=True ): ''' Construct and evaluate the ligand-target matrix. Returns the matrices and the prediction scores Parameters ---------- source_weights : pandas.DataFrame or dictionary Dataframe or dictionary which contains the weights associated to each individual data source. Sources with higher weights will contribute more to the final model performance. ``` -------------------------------- ### GeneInfo.__init__(arg) Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the GeneInfo object with gene alias information. ```APIDOC ## GeneInfo.__init__(arg) ### Description Initializes the GeneInfo class to facilitate gene conversion between mouse and human symbols. ### Parameters - **arg** (str or Iterable) - Required - The name of the file to read gene alias information from, or an Iterable of (human_symbol, mouse_symbol) tuples. ### Raises - **TypeError** - If arg is not of the correct type. ``` -------------------------------- ### WeightedNetwork Initialization and Access Source: https://saeyslab.github.io/nichenetpy/nichenetpy/network.html Initializes a weighted network from a file or DataFrame and provides item access. ```python def __init__(self, mapping:list|pd.DataFrame|None=None, filename:str=None): if filename is not None: if type(filename) is not str: raise TypeError(f"filename should have type str, was {type(filename)}") mapping = sorted( read_weighted_network(filename), key=lambda x : x[0] ) elif type(mapping) is pd.DataFrame: mapping = sorted( zip(mapping["from"], mapping["to"], mapping["weight"]), key=lambda x : x[0] ) super().__init__(mapping=mapping) def __getitem__(self, key:gene_t) -> dict[gene_t, float]: start, count = self._index[key] return dict(item[1:3] for item in self._mapping[start:start+count]) ``` -------------------------------- ### Initialize and use GeneAliasInfo Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html The class can be initialized with a file path or a dictionary mapping aliases to symbols and Entrez IDs. It provides methods for alias conversion and managing mappings. ```python 8class GeneAliasInfo: 9 ''' 10 This class facilitates gene alias conversion. 11 12 Parameters 13 ---------- 14 arg : str or dict 15 name of the file to read gene alias information from or a dict which contains the alias mappings: alias -> (symbol, entrez) 16 17 Raises 18 ------ 19 TypeError 20 if arg is not of the correct type 21 ''' 22 def __init__(self, arg:str|dict[str, tuple[str, int|None]]) -> None: 23 if type(arg) is str: 24 with open(arg) as file: 25 lines = file.readlines() 26 symbol, entrez, alias = zip(*([word.strip("\"\'") for word in line.rstrip().split(",")] for line in lines[1:])) 27 self._mapping = dict(zip(alias, zip(symbol, (None if e == "" else int(e) for e in entrez)))) 28 elif type(arg) is dict: 29 self._mapping = arg 30 else: 31 raise TypeError(f"arg should have type str or dict, was {type(arg)}") 32 33 def __str__(self) -> str: 34 return self._mapping.__str__() 35 36 def __getitem__(self, key:str) -> tuple[str, int|None]: 37 try: 38 return self._mapping[key] 39 except KeyError: 40 raise KeyError(f"{key} is not a recognized gene") 41 42 def __iter__(self): 43 return self._mapping.__iter__() 44 45 def __contains__(self, item): 46 return item in self._mapping 47 48 def add(self, items:Iterable[tuple[str, tuple[str, int|None]]]): 49 ''' 50 Adds new mappings but will not overwrite existing mappings. 51 52 Parameters 53 ---------- 54 items : Iterable 55 the new mappings 56 ''' 57 for k, v in items: 58 if k not in self: 59 self._mapping[k] = v 60 61 def alias_to_symbol(self, obj:Iterable[str]|AnnData) -> list[str]|None: 62 ''' 63 Converts gene aliases to gene symbols. 64 65 Parameters 66 ---------- 67 obj : Iterable or AnnData or None 68 an object that contains gene symbols 69 70 Returns 71 ------- 72 list of str or None 73 a list of gene names post gene alias conversion 74 75 Raises 76 ------ 77 TypeError 78 if obj is not of the correct type 79 80 Notes 81 ----- 82 if obj is of type Iterable[str], this function returns a list of gene symbols 83 if obj is of type AnnData, this function returns None 84 ''' 85 if type(obj) is list or type(obj) is tuple: 86 output = [] 87 mapped_genes = dict() 88 for gene in obj: 89 ngene = self[gene][0] if gene in self else gene 90 output.append(ngene) 91 if ngene in mapped_genes: 92 mapped_genes[ngene].add(gene) 93 else: 94 mapped_genes[ngene] = {gene} 95 # revert duplicate symbols back to the original symbols 96 doubles = [i for i, ngene in enumerate(output) if len(mapped_genes[ngene]) > 1] 97 for i in doubles: 98 output[i] = obj[i] 99 return output 100 elif type(obj) is AnnData: 101 obj.var_names = self.alias_to_symbol(obj.var_names) 102 if "gene" in obj.var: 103 obj.var["gene"] = self.alias_to_symbol(obj.var["gene"]) 104 elif isinstance(obj, Iterable): 105 return self.alias_to_symbol(list(obj)) 106 else: 107 raise TypeError(f"expected type of obj argument to be Iterable[str] or AnnData, got {type(obj)}") ``` -------------------------------- ### LigandReceptorNetwork Methods Source: https://saeyslab.github.io/nichenetpy/nichenetpy/network.html Methods to retrieve ligands and receptors from a LigandReceptorNetwork instance. ```python def get_ligands(self) -> set[gene_t]: ''' Get all the ligands present in the network. Returns ------- set set of ligands present in the network ''' return set(self.key_iter()) def get_receptors(self) -> set[gene_t]: ''' Get all the receptors present in the network. Returns ------- set set of receptors present in the network ''' return set(receptor for _, receptor in self._mapping) ``` -------------------------------- ### GeneInfo.__init__ Source: https://saeyslab.github.io/nichenetpy/nichenetpy/gene_symbol.html Initializes the GeneInfo object with either a path to a CSV file or an iterable of human-mouse gene symbol pairs. ```APIDOC ## GeneInfo(arg: str | Iterable[tuple[str, str]]) ### Description Initializes the GeneInfo instance. If a string is provided, it reads from a file; if an iterable is provided, it uses the pairs to build mapping dictionaries. ### Parameters - **arg** (str | Iterable[tuple[str, str]]) - Required - A file path to a CSV or an iterable of (human_symbol, mouse_symbol) tuples. ### Raises - **TypeError** - Raised if the provided argument is not a string or an iterable. ```