### Install netZooPy using pip Source: https://netzoopy.readthedocs.io/en/stable/_sources/install/index.md.txt Clone the repository, navigate to the directory, and install netZooPy in editable mode using pip. ```bash git clone https://github.com/netZoo/netZooPy.git cd netZooPy pip3 install -e . ``` -------------------------------- ### Panda Command Example with Specific Files Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html A concrete example of the 'netzoopy panda' command with paths to test data files for expression, motif, and PPI, and specifying the output file. ```bash netzoopy panda -e tests/puma/ToyData/ToyExpressionData.txt -m tests/puma/ToyData/ToyMotifData.txt -p tests/puma/ToyData/ToyPPIData.txt -o test_panda.txt ``` -------------------------------- ### Run NetZoopy Panda from Command Line Source: https://netzoopy.readthedocs.io/en/stable/index.html This command-line interface example shows how to run the 'panda' command with specified input and output files. Ensure all required input files (expression, motif, ppi) are correctly formatted. ```bash netzoopy panda --e expression.txt --m motif.txt --p ppi.txt --o output_panda.txt ``` -------------------------------- ### Initialize Panda Object and Run Algorithm Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/panda/panda.html Initializes the Panda object with expression, motif, and PPI data. This example demonstrates running the PANDA algorithm using toy data and saving the results. It omits motif and PPI data to use a Pearson correlation network. ```python from netZooPy.panda.panda import Panda panda_obj = Panda('../../tests/ToyData/ToyExpressionData.txt', '../../tests/ToyData/ToyMotifData.txt', '../../tests/ToyData/ToyPPIData.txt', remove_missing=False) panda_obj.save_panda_results('Toy_Panda.pairs.txt') ``` -------------------------------- ### Install netZooPy using Conda Source: https://netzoopy.readthedocs.io/en/stable/_sources/install/index.md.txt Install netZooPy from anaconda.org using the conda package manager, specifying the netzoo and conda-forge channels. ```bash conda install -c netzoo -c conda-forge netzoopy ``` -------------------------------- ### Run SAMBAR with ToyData Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/sambar/sambar.html Example of running the SAMBAR method using toy data for UCEC mutation data. This will generate pathway mutation scores, processed gene mutation scores, a distance matrix, and cluster assignments. ```python import pysambar as sm pathways, groups = sm.sambar("/ToyData/mut.ucec.csv","ToyData/esizef.csv",'ToyData/genes.txt','ToyData/h.all.v6.1.symbols.gmt') ``` -------------------------------- ### Lioness with GPU Computing and Optimized Precision Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Example for utilizing GPU computing for Lioness. It optimizes precision and uses gene intersection with PANDA priors, saving individual Lioness networks as they are computed. ```bash netzoopy lioness -e -m -p -op output_panda.txt -ol output_lioness_folder/ --computing gpu --precision single --mode_process intersection --save_single_lioness --ignore_final ``` -------------------------------- ### Initialize LIONESS Parameters and Sample Selection Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/lioness/lioness.html Sets up LIONESS parameters, including sample selection based on provided indices or names, and determines the number of samples for computation. It also configures output directories and save formats. ```python # Get sample range to iterate # the number of conditions is the N parameter used for the number of samples in the whole background self.n_conditions = self.expression_matrix.shape[1] self.n_lio_samples = self.n_conditions if (subset_numbers!=None or subset_names!=None): if (subset_numbers!=None and subset_names!=None): sys.exit('Pass only one between subset_numbers and subset_names') elif (subset_numbers!=None and subset_names==None): # select using indexes assert isinstance(subset_numbers, list) assert isinstance(subset_numbers[0], int) self.indexes = [int(i) for i in subset_numbers] else: #select using sample names assert isinstance(subset_names, list) assert isinstance(subset_names[0], int) self.indexes = [self.expression_samples.index(int(i)) for i in subset_names] #self.expression_samples = self.expression_samples[self.indexes] # number of lioness networks to be computed self.n_lio_samples = len(self.indexes) else: # if no subset is selected, we just use the start and end numbers to decide # which samples need to be analyses. The background is always what is used for PANDA # and stays the same self.indexes = range(self.n_conditions)[ start - 1 : end ] # sample indexes to include #self.expression_samples = self.expression_samples[start-1:end] self.n_lio_samples = len(self.indexes) print("Number of total samples:", self.n_conditions) print("Number of computed samples:", len(self.indexes)) print("Number of parallel cores:", self.n_cores) # Create the output folder if not exists self.save_dir = save_dir self.save_fmt = save_fmt # if true, no final large matrix is saved self.ignore_final=ignore_final # Here we make sure that at least one between the complete lioness (edgex x samples) # dataframe or each single network is saved if ((self.save_single==False) and (self.ignore_final==True)): sys.exit("ERROR: you are passing save_single=False, and ignore_final=True. This way no output is saved, change one of the two to have either the single networks or the final large table") # We create the folder if not os.path.exists(save_dir): os.makedirs(save_dir) ``` -------------------------------- ### Run LIONESS Algorithm via CLI Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Execute the LIONESS algorithm from the command line. Requires expression, motif, and PPI matrices, along with output directory and format. Supports CPU/GPU and core count specification. ```bash python3 run_lioness.py -e ../../tests/ToyData/ToyExpressionData.txt -m ../../tests/ToyData/ToyMotifData.txt -p ../../tests/ToyData/ToyPPIData.txt -g cpu -r single -c 2 -o /tmp -f npy 1 2 ``` -------------------------------- ### netZooPy.lioness.run_lioness.main Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Run the LIONESS algorithm from the command line to estimate sample-specific regulatory networks. ```APIDOC ## netZooPy.lioness.run_lioness.main ### Description Run LIONESS algorithm from the command line. ### Method CLI command ### Parameters #### Command-line Arguments - **-h, --help**: help - **-e, --expression**: expression_matrix - Path to expression matrix (.npy). - **-m, --motif**: motif_matrix - Path to motif matrix, normalized (.npy). - **-p, --ppi**: ppi_matrix - Path to ppi matrix, normalized (.npy). - **-g, --comp**: Specifies whether to use CPU or GPU (default: cpu). - **-r, --pre**: number_of_digits - Number of digits to calculate. - **-c, --ncores**: number_of_cores - Number of cores to use. - **-n, --npy**: panda_network - Path to PANDA network (.npy). - **-o, --out**: output_folder - Path to the output folder. - **-f, --format**: output_format - Output format (txt, npy, or mat). - **start**: Optional - To start from the nth sample. - **end**: Optional - To end at the nth sample (must be used with start). ### Request Example ```bash python3 run_lioness.py -e ../../tests/ToyData/ToyExpressionData.txt -m ../../tests/ToyData/ToyMotifData.txt -p ../../tests/ToyData/ToyPPIData.txt -g cpu -r single -c 2 -o /tmp -f npy 1 2 ``` ### Reference Kuijjer, Marieke Lydia, et al. “Estimating sample-specific regulatory networks.” Iscience 14 (2019): 226-240. ``` -------------------------------- ### Run Lioness for Single-Sample Networks Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Basic command to run Lioness for extracting single-sample networks. Requires expression, motif, and PPI data files. ```bash netzoopy lioness -e tests/puma/ToyData/ToyExpressionData.txt -m tests/puma/ToyData/ToyMotifData.txt -p tests/puma/ToyData/ToyPPIData.txt -op test_panda.txt -ol lioness/ ``` -------------------------------- ### Run LIONESS from Command Line Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/lioness/run_lioness.html Execute the LIONESS algorithm via the command line. Requires expression, motif, and PPI matrices, along with output specifications. Supports specifying computation mode (CPU/GPU), precision, number of cores, and sample range. ```python #!/usr/bin/env python import sys import getopt from netZooPy.lioness.lioness import Lioness from netZooPy.panda.panda import Panda [docs] def main(argv): """ Description: Run LIONESS algorithm from the command line. Usage: -h, --help: help -e, --expression: expression matrix (.npy) -m, --motif: motif matrix, normalized (.npy) -p, --ppi: ppi matrix, normalized (.npy) -g, --comp: use cpu (default) or gpu -r, --pre: number of digits to calcluate -c, --ncores: number cores -n, --npy: PANDA network (.npy) -o, --out: output folder -f, --format: output format (txt, npy, or mat) start: to start from nth sample (optional) end: to end at nth sample (optional, must with start) Example: python3 run_lioness.py -e ../../tests/ToyData/ToyExpressionData.txt -m ../../tests/ToyData/ToyMotifData.txt -p ../../tests/ToyData/ToyPPIData.txt -g cpu -r single -c 2 -o /tmp -f npy 1 2 Reference: Kuijjer, Marieke Lydia, et al. "Estimating sample-specific regulatory networks." Iscience 14 (2019): 226-240. """ #Create variables expression_data = None motif = None ppi = None comp = None pre = None ncores = None save_dir = None save_fmt = None try: opts, args = getopt.getopt(argv, 'he:m:p:g:r:c:n:o:f:', ['help', 'expression=', 'motif=','ppi=','comp=','pre=','ncores=', 'out=', 'format=']) except getopt.GetoptError as err: print(str(err)) # will print something like "option -a not recognized" print(__doc__) return 2 for opt, arg in opts: if opt in ('-h', '--help'): print(__doc__) return 0 elif opt in ('-e', '--expression'): expression_data = arg elif opt in ('-m', '--motif'): motif = arg elif opt in ('-p', '--ppi'): ppi = arg elif opt in ('-g', '--comp'): comp = arg elif opt in ('-r', '--pre'): pre = arg elif opt in ('-c', '--ncores'): ncores = arg elif opt in ('-n'): panda_net = arg elif opt in ('-o', '--out'): save_dir = arg elif opt in ('-f', '--format'): save_fmt = arg else: print('Unknown option', opt) return 1 start, end = 1, None if len(args) == 2: start, end = map(int, args) #Check if required options are given if expression_data is None or motif is None or ppi is None \ or save_dir is None or save_fmt is None: print('Missing argument!') print(__doc__) return 1 else: print('Input data:') print('Expression: ', expression_data) print('Motif matrix: ', motif) print('PPI matrix: ', ppi) print('compute core: ', comp) print('precision: ', pre) print('n cores: ', ncores) print('Output folder:', save_dir) print('Output format:', save_fmt) print('Sample range: ', start, '-', end) # Run panda print('Start LIONESS run ...') obj = Panda(expression_data, motif, ppi, keep_expression_matrix=True,save_memory=False) L = Lioness(obj, computing=comp, precision=pre,ncores=ncores,start=start, end=end, save_dir=save_dir, save_fmt=save_fmt) print('All done!') if __name__ == '__main__': sys.exit(main(sys.argv[1:])) ``` -------------------------------- ### Initialize and Compute LIONESS Network (GPU) Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/lioness/lioness.html Initializes the total LIONESS network for GPU computation using the first sample's results. Converts transposed data to a string format for efficient storage. ```python self.total_lioness_network = np.fromstring( np.transpose(lioness_network).tostring(), dtype=lioness_network.dtype )[:,np.newaxis] ``` -------------------------------- ### Initialize and Run BONOBO Source: https://netzoopy.readthedocs.io/en/stable/_sources/functions/api.rst.txt Initialize the Bonobo class with expression data and run the compute_bonobo function. This snippet demonstrates setting parameters for memory usage, output format, sparsification, and output folder. ```python bonobo_obj_sparse = Bonobo(expression_file) bonobo_obj_sparse.run_bonobo(keep_in_memory=True, output_fmt='.hdf', sparsify=True, output_folder='../data/processed/bonobo_sparse_pvals/', save_pvals=False) ``` -------------------------------- ### Initialize AnalyzeLioness Class Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/lioness/analyze_lioness.html Initializes the AnalyzeLioness class with LIONESS data. It loads results for export and analysis. ```python class AnalyzeLioness(Lioness): """ Plots LIONESS network. Parameters ------------ lioness_data: object lioness object. """ def __init__(self, lioness_data): """ Intialize instance of AnalyzeLioness class and load variables. """ self.export_panda_results = lioness_data.export_panda_results self.lioness_results = lioness_data.export_lioness_results return None ``` -------------------------------- ### Lioness on a Subset of Samples Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Demonstrates running Lioness on a restricted subset of samples using --panda_start and --panda_end. This is useful for testing data suitability or resource constraints. Alternatively, --subset_numbers and --subset_names can be used to specify samples. ```bash netzoopy lioness -e -m -p -op output_panda.txt -ol output_lioness_folder/ --computing --panda_start 1 --panda_end 5 --precision single --mode_process intersection --save_single_lioness --ignore_final ``` -------------------------------- ### Run Netzoopy Panda Method from CLI Source: https://netzoopy.readthedocs.io/en/stable/_sources/functions/cli.rst.txt Execute the 'panda' method using the Netzoopy CLI. Specify input files for expression, motif, and PPI data, and an output file for the results. ```bash netzoopy panda --e expression.txt --m motif.txt --p ppi.txt --o output_panda.txt ``` -------------------------------- ### Run PANDA Algorithm via CLI Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Execute the PANDA algorithm using command-line arguments. Specify input files for expression, motifs, and PPI, along with an output file. The -q flag enables Lioness output. ```bash python run_panda.py -e ../../tests/ToyData/ToyExpressionData.txt -m ../../tests/ToyData/ToyMotifData.txt -p ../../tests/ToyData/ToyPPIData.txt -o test_panda.txt -q output_panda.txt ``` -------------------------------- ### netZooPy.panda.run_panda.main Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Run the PANDA algorithm from the command line to infer gene regulatory networks. ```APIDOC ## netZooPy.panda.run_panda.main ### Description Run PANDA algorithm from the command line. ### Method CLI command ### Parameters #### Command-line Arguments - **-h, --help**: help - **-e, --expression**: expression_file - Path to file containing the gene expression data. By default, the expression file does not have a header, and the cells are separated by a tab. - **-m, --motif**: motif_file - Path to pair file containing the transcription factor DNA binding motif edges in the form of TF-gene-weight(0/1). If not provided, the gene coexpression matrix is returned as a result network. - **-p, --ppi**: ppi_file - Path to pair file containing the PPI edges. The PPI can be symmetrical, if not, it will be transformed into a symmetrical adjacency matrix. - **-o, --out**: output_file - Output file path. - **-r, --rm_missing**: Flag to remove missing values. - **-q, --lioness**: Flag to output for Lioness single sample networks. ### Request Example ```bash python run_panda.py -e ../../tests/ToyData/ToyExpressionData.txt -m ../../tests/ToyData/ToyMotifData.txt -p ../../tests/ToyData/ToyPPIData.txt -o test_panda.txt -q output_panda.txt ``` ### Reference Glass, Kimberly, et al. “Passing messages between biological networks to refine predicted interactions.” PloS one 8.5 (2013): e64832. ``` -------------------------------- ### Run PUMA Algorithm Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/puma/puma.html Initiates the core PUMA algorithm by calling the `puma_loop` method with the normalized correlation, motif, and PPI matrices, along with computing and alpha parameters. ```python print("Running PUMA algorithm ...") self.puma_network = self.puma_loop( self.correlation_matrix, self.motif_matrix, self.ppi_matrix, computing, alpha, ) ``` -------------------------------- ### Initialize Lioness Object Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/lioness/lioness.html Instantiates the Lioness class, which requires a pre-initialized Panda object with the expression matrix kept. This is the first step to running the LIONESS algorithm. ```python from netZooPy.lioness.lioness import Lioness from netZooPy.panda.panda import Panda panda_obj = Panda('../../tests/ToyData/ToyExpressionData.txt', '../../tests/ToyData/ToyMotifData.txt', '../../tests/ToyData/ToyPPIData.txt', remove_missing=False, keep_expression_matrix=True) lioness_obj = Lioness(panda_obj) ``` -------------------------------- ### Initialize condor_object with a network file Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/condor/condor.html Initializes the condor_object by reading a network edgelist from a specified file path. Ensure the file path, separator, index column, and header row are correctly provided. ```python import random import pandas as pd from igraph import * from netZooPy.condor.condor import condor_object # Example usage with a network file # Assuming 'network.csv' exists and is formatted correctly # c = condor_object(network_file='network.csv', sep=',', index_col=0, header=0) # To ensure reproducibility, set the random seed before initialization random.seed(1) c1 = condor_object(network_file='network.csv', sep=',', index_col=0, header=0) random.seed(1) c2 = condor_object(network_file='network.csv', sep=',', index_col=0, header=0) # If you want different results on each run, use a dynamic seed # random.seed(random.randint(1,10000000)) # c3 = condor_object(network_file='network.csv', sep=',', index_col=0, header=0) ``` -------------------------------- ### initial_community Source: https://netzoopy.readthedocs.io/en/stable/functions/api.html Computes the initial community structure based on unipartite methods. ```APIDOC ## initial_community ### Description Computes the initial community structure based on unipartite methods. ### Parameters #### Path Parameters - **method** (str) - The method to use for initial community detection. Defaults to 'LDN'. - **project** (bool) - Whether to project the network. Defaults to False. - **resolution** (float) - Resolution parameter for community detection. Defaults to 1. ``` -------------------------------- ### Run Condor Process Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/condor/condor.html Orchestrates the entire Condor process, including object creation and running the BRIM algorithm. Allows for customization of input parameters and output options. ```python def run_condor( network_file, sep=",", index_col=0, header=0, initial_method="LDN", initial_project=False, com_num="def", deltaQmin="def", resolution=1, return_output=False, tar_output="tar_memb.txt", reg_output="reg_memb.txt", silent = False ): """ Computation of the whole condor process. It creates a condor object and runs all the steps of BRIM on it. The function outputs ``` -------------------------------- ### PANDA Command-Line Execution Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/panda/run_panda.html This script provides a command-line interface to run the PANDA algorithm. It parses arguments for expression data, motif, PPI, output file, and Lioness options. Ensure all required input files are provided. ```python #!/usr/bin/env python import sys import getopt from netZooPy.panda.panda import Panda [docs] def main(argv): """ Description: Run PANDA algorithm from the command line. Inputs: -h, --help: help -e, --expression: expression_file : Path to file containing the gene expression data. By default, the expression file does not have a header, and the cells ares separated by a tab. -m, --motif: Path to pair file containing the transcription factor DNA binding motif edges in the form of TF-gene-weight(0/1). If not provided, the gene coexpression matrix is returned as a result network. -p, --ppi: Path to pair file containing the PPI edges. The PPI can be symmetrical, if not, it will be transformed into a symmetrical adjacency matrix. -o, --out: output file. -r, --rm_missing. -q, --lioness: output for Lioness single sample networks. Example: python run_panda.py -e ../../tests/ToyData/ToyExpressionData.txt -m ../../tests/ToyData/ToyMotifData.txt -p ../../tests/ToyData/ToyPPIData.txt -o test_panda.txt -q output_panda.txt Reference: Glass, Kimberly, et al. "Passing messages between biological networks to refine predicted interactions." PloS one 8.5 (2013): e64832. """ #Create variables expression_data = None motif = None ppi = None output_file = "output_panda.txt" rm_missing = False lioness_file = False # Get input options try: opts, args = getopt.getopt(argv, 'he:m:p:o:rq:', ['help', 'expression=', 'motif=', 'ppi=', 'out=', 'rm_missing', 'lioness']) except getopt.GetoptError: print(__doc__) sys.exit() for opt, arg in opts: if opt in ('-h', '--help'): print(__doc__) sys.exit() elif opt in ('-e', '--expression'): expression_data = arg elif opt in ('-m', '--motif'): motif = arg elif opt in ('-p', '--ppi'): ppi = arg elif opt in ('-o', '--out'): output_file = arg elif opt in ('-r', '--rm_missing'): rm_missing = arg elif opt in ('-q', '--lioness'): lioness_file = arg #Check if required options are given print('Input data:') print('Expression:', expression_data) print('Motif data:', motif) print('PPI data:', ppi) if expression_data is None and motif is None: print('Missing inputs!') print(__doc__) sys.exit() # Run PANDA print('Start Panda run ...') panda_obj = Panda(expression_data, motif, ppi, save_tmp=True, remove_missing=rm_missing, keep_expression_matrix=bool(lioness_file), save_memory=False) #panda_obj = pypanda.Panda(expression_data, motif, None, save_tmp=True, remove_missing=rm_missing) #panda_obj = pypanda.Panda(None, motif, ppi, save_tmp=True, remove_missing=rm_missing) #panda_obj = pypanda.Panda(None, motif, None, save_tmp=True, remove_missing=rm_missing) #panda_obj = pypanda.Panda(expression_data, None, ppi, save_tmp=True, remove_missing=rm_missing) panda_obj.save_panda_results(output_file) #panda_obj.top_network_plot(top=70, file='panda_topgenes.png') #indegree = panda_obj.return_panda_indegree() #outdegree = panda_obj.return_panda_outdegree() if lioness_file: from netZooPy.lioness.lioness import Lioness lioness_obj = Lioness(panda_obj) lioness_obj.save_lioness_results(lioness_file) print('All done!') if __name__ == '__main__': sys.exit(main(sys.argv[1:])) ``` -------------------------------- ### Create Motif and PPI Networks Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/panda/panda.html Initializes and populates the unnormalized motif matrix and the PPI matrix. Handles cases where PPI data is not provided by creating an identity matrix. Raises an exception if there's no intersection between expression matrix genes and motif prior genes. ```python with Timer("Creating motif network ..."): self.motif_matrix_unnormalized = np.zeros((self.num_tfs, self.num_genes)) idx_tfs = [tf2idx.get(x, np.nan) for x in self.motif_data[0]] idx_genes = [gene2idx.get(x, np.nan) for x in self.motif_data[1]] commind1 = ~np.isnan(idx_tfs) & ~np.isnan(idx_genes) idx_tfs = [i for (i, v) in zip(idx_tfs, commind1) if v] idx_genes = [i for (i, v) in zip(idx_genes, commind1) if v] if (len(idx_genes) == 0) or (len(idx_tfs) == 0): raise Exception('Error when creating the motif network!' ' Typically this exception is raised if your' ' expression matrix genes and motif priors' ' not have any intersection.') idx = np.ravel_multi_index( (idx_tfs, idx_genes), self.motif_matrix_unnormalized.shape ) self.motif_matrix_unnormalized.ravel()[idx] = self.motif_data[2][commind1] if self.ppi_data is None: self.ppi_matrix = np.identity(self.num_tfs, dtype=int) else: with Timer("Creating PPI network ..."): self.ppi_matrix = np.identity(self.num_tfs) idx_tf1 = [tf2idx.get(x, np.nan) for x in self.ppi_data[0]] idx_tf2 = [tf2idx.get(x, np.nan) for x in self.ppi_data[1]] commind2 = ~np.isnan(idx_tf1) & ~np.isnan(idx_tf2) idx_tf1 = [i for (i, v) in zip(idx_tf1, commind2) if v] idx_tf2 = [i for (i, v) in zip(idx_tf2, commind2) if v] idx = np.ravel_multi_index((idx_tf1, idx_tf2), self.ppi_matrix.shape) self.ppi_matrix.ravel()[idx] = self.ppi_data[2][commind2] idx = np.ravel_multi_index((idx_tf2, idx_tf1), self.ppi_matrix.shape) self.ppi_matrix.ravel()[idx] = self.ppi_data[2][commind2] ``` -------------------------------- ### AnalyzePanda Initialization Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/panda/analyze_panda.html Initializes the AnalyzePanda class with PANDA data. It requires a PANDA object that has the 'export_panda_results' attribute. This attribute is necessary for loading the network results. ```APIDOC ## Initialize AnalyzePanda ### Description Initializes the AnalyzePanda class with PANDA data. It requires a PANDA object that has the 'export_panda_results' attribute. This attribute is necessary for loading the network results. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **panda_data** (object) - Required - A PANDA object containing the 'export_panda_results' attribute. ``` -------------------------------- ### Lioness class methods Source: https://netzoopy.readthedocs.io/en/stable/functions/api.html Details the methods of the `Lioness` class, including internal computation functions, network normalization, and export/save functionalities. ```APIDOC ## Lioness class methods ### Description Methods available for the `Lioness` class. ### Methods - `Lioness.__compute_subset_panda()` - `Lioness.__lioness_loop()` - `Lioness.__lioness_to_disk()` - `Lioness.__par_lioness_loop` - `Lioness._normalize_network()` - `Lioness.export_lioness_table()` - `Lioness.panda_loop()` - `Lioness.processData()` - `Lioness.return_panda_indegree()` - `Lioness.return_panda_outdegree()` - `Lioness.save_lioness_results()` - `Lioness.save_panda_results()` - `Lioness.top_network_plot()` ``` -------------------------------- ### Run Bonobo Computation Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Computes BONOBOs from an expression file. Parameters like computing method (CPU only), number of cores (no parallelization yet), and online coexpression are not accessible via CLI. ```bash netzoopy bonobo [OPTIONS] ``` -------------------------------- ### Initial Community Structure (Projected) Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/condor/condor.html Computes the initial community structure for the bipartite network, either by projecting onto the target nodes or by disregarding the bipartite structure. Supports Leiden ('LDN') and Multilevel ('LCS') methods. ```python with Timer("Initial community structure with projection:",self.silent): # Obtains bipartite projection onto target subset. projected_graph = self.graph.bipartite_projection(which=1) if method == "LCS": vc = Graph.community_multilevel(projected_graph, weights=weights_id) if method == "LDN": vc = Graph.community_leiden( projected_graph, objective_function='modularity',resolution_parameter=resolution, weights=weights_id ) self.modularity = vc.modularity if not self.silent: print("Initial modularity: ", self.modularity) tar_index = [i.index for i in self.graph.vs.select(type_in=[1])] # By the ordering on the indices, the target nodes indices begin at len(co.reg_names) # in order not to mess with the indices in vc we substract that starting value. tar_memb = [vc.membership[i - len(self.reg_names)] for i in tar_index] T0 = pd.DataFrame(zip(tar_index, tar_memb)) T0.columns = ["index", "community"] self.tar_memb = T0 # Here we have only computed the community structure for the target nodes. We initialize a properly sized dataframe for the reg nodes. reg_index = [i.index for i in self.graph.vs.select(type_in=[0])] # By the ordering on the indices, the target nodes indices begin at len(co.reg_names) # in order not to mess with the indices in vc we substract that starting value. reg_memb = [0 for i in reg_index] R0 = pd.DataFrame(zip(reg_index, reg_memb)) R0.columns = ["index", "community"] self.reg_memb = R0 ``` -------------------------------- ### Netzoopy CLI Lioness Command Structure Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html The general structure of the netzoopy lioness command, outlining the base command and its available options. ```bash netzoopy lioness [OPTIONS] ``` -------------------------------- ### Run Condor Computation Source: https://netzoopy.readthedocs.io/en/stable/functions/cli.html Executes the full condor computation process, creating a condor object and running all BRIM steps. Outputs tar and reg final memberships to CSV files. Assumes the edgelist represents a bipartite network. ```bash netzoopy condor [OPTIONS] ``` -------------------------------- ### Initialize Puma Object Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/puma/puma.html Instantiate the Puma class to begin the gene regulatory network inference process. Provide paths to expression, motif, PPI, and miRNA data files. ```python from netZooPy.puma.puma import Puma puma_obj = Puma('../../tests/ToyData/ToyExpressionData.txt', '../../tests/ToyData/ToyMotifData.txt', '../../tests/ToyData/ToyPPIData.txt','../../tests/ToyData/ToyMiRList.txt') ``` -------------------------------- ### Panda Class Initialization Source: https://netzoopy.readthedocs.io/en/stable/functions/api.html Initializes the PANDA algorithm with various input files and processing parameters to infer a gene regulatory network. ```APIDOC ## Panda Class ### Description Initializes the PANDA algorithm to infer gene regulatory networks using expression data, motif priors, and TF PPI data. ### Parameters * **expression_file** (str or pandas.DataFrame) - Path to gene expression data or a pandas DataFrame. Defaults to tab-separated, no header. * **motif_file** (str or pandas.DataFrame) - Path to TF DNA binding motif data (TF-gene-weight) or a pandas DataFrame. If None, returns gene coexpression matrix. * **ppi_file** (str or pandas.DataFrame) - Path to TF PPI data or a pandas DataFrame. Assumed undirected. * **computing** (str) - 'cpu' or 'gpu' for computation. Defaults to 'cpu'. * **precision** (str) - 'double' (15 digits) or 'single' (7 digits) for network computation. Defaults to 'double'. * **save_memory** (bool) - If True, removes temporary results. If False, keeps temporary files. Defaults to True. * **save_tmp** (bool) - Save temporary variables. Defaults to False. * **remove_missing** (bool) - Removes genes/TFs not present in all priors (only for modeProcess='legacy'). Defaults to False. * **keep_expression_matrix** (bool) - Keep the input expression matrix in the result object. Defaults to False. * **modeProcess** (str) - Data processing mode: 'legacy', 'union' (default), or 'intersection'. * **alpha** (str) - Learning rate. Defaults to 0.1. * **start** (int) - First sample of the expression dataset. Defaults to 1. * **end** (int) - Last sample of the expression dataset. Defaults to None. * **cobra_design_matrix** (np.ndarray or pd.DataFrame) - COBRA design matrix. * **cobra_covariate_to_keep** (int) - Zero-indexed base of COBRA co-expression component to use. ### Examples ```python from netZooPy.panda.panda import Panda # Initialize Panda with toy data panda_obj = Panda( '../../tests/ToyData/ToyExpressionData.txt', '../../tests/ToyData/ToyMotifData.txt', '../../tests/ToyData/ToyPPIData.txt', remove_missing=False ) ``` ``` -------------------------------- ### brim Source: https://netzoopy.readthedocs.io/en/stable/functions/api.html Implements the BRIM algorithm to iteratively maximize bipartite modularity. ```APIDOC ## brim ### Description Implements the BRIM algorithm to iteratively maximize bipartite modularity. Note that `c` is the maximum number of communities. Dynamic choice of `c` is not yet implemented. ### Parameters #### Path Parameters - **deltaQmin** (str) - Difference modularity threshold for stopping the iterative process. Defaults to 'def'. - **c** (int) - Maximum number of communities. Defaults to 'def'. - **resolution** (float) - Resolution parameter for modularity calculation. Defaults to 1. ### Notes Updates the condor object with the following attributes: - **self.modularity**: Modularity score for the final assignment. - **self.tar_memb**: Final community assignment for target nodes. - **self.reg_memb**: Final community assignment for regulator nodes. **Note**: `c` must be larger than the number of communities given by the initial community assignment. Otherwise, the program will crash. The default option provides room for 20% more communities, which rarely fails. ``` -------------------------------- ### Run Condor Process Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/condor/condor.html Orchestrates the entire Condor process, including object creation, BRIM algorithm execution, and output generation. ```APIDOC ## run_condor( network_file, sep=",", index_col=0, header=0, initial_method="LDN", initial_project=False, com_num="def", deltaQmin="def", resolution=1, return_output=False, tar_output="tar_memb.txt", reg_output="reg_memb.txt", silent = False ) ### Description Computation of the whole condor process. It creates a condor object and runs all the steps of BRIM on it. The function outputs community assignments for target and regulator nodes. ``` -------------------------------- ### Run PANDA Algorithm Source: https://netzoopy.readthedocs.io/en/stable/functions/api.html Initializes and runs the PANDA algorithm. Use this to infer a gene regulatory network. Motif and PPI data can be omitted to rely solely on a Pearson correlation network. ```python from netZooPy.panda.panda import Panda panda_obj = Panda('../../tests/ToyData/ToyExpressionData.txt', '../../tests/ToyData/ToyMotifData.txt', '../../tests/ToyData/ToyPPIData.txt', remove_missing=False) ``` -------------------------------- ### Run PANDA Algorithm Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/panda/panda.html Executes the PANDA algorithm using provided correlation, motif, and PPI matrices. Supports both CPU and GPU computation. Prints the time taken for the PANDA loop execution. ```python panda_loop_time = time.time() # TODO:This should be using self.correlation. Keeping for retrocompatibility motif_matrix = calc.compute_panda( correlation_matrix, ppi_matrix, motif_matrix, computing=computing, alpha=alpha, ) print("Running panda took: %.2f seconds!" % (time.time() - panda_loop_time)) # Ale: reintroducing the export_panda_results array if Panda called with save_memory=False if hasattr(self, "unique_tfs"): tfs = np.tile(self.unique_tfs, (len(self.gene_names), 1)).flatten() genes = np.repeat(self.gene_names, self.num_tfs) motif = self.motif_matrix_unnormalized.flatten(order="F") force = motif_matrix.flatten(order="F") self.export_panda_results = pd.DataFrame( {"tf": tfs, "gene": genes, "motif": motif, "force": force} ) # self.export_panda_results = np.column_stack((tfs,genes,motif,force)) return motif_matrix ``` -------------------------------- ### Accumulate LIONESS Network Results (GPU) Source: https://netzoopy.readthedocs.io/en/stable/_modules/netZooPy/lioness/lioness.html Accumulates LIONESS network results for subsequent samples when using GPU computation. Stacks the new sample's network results as a column to the existing total network. ```python self.total_lioness_network = np.column_stack( ( self.total_lioness_network, np.fromstring( np.transpose(lioness_network).tostring(), dtype=lioness_network.dtype, ), ) ) ``` -------------------------------- ### Lioness Class Initialization Source: https://netzoopy.readthedocs.io/en/stable/functions/api.html Initializes the Lioness object to infer single-sample gene regulatory networks. It takes a PANDA object as input and allows configuration of computation resources, precision, sample subsets, and output settings. ```APIDOC ## class netZooPy.lioness.lioness.Lioness ### Description Using LIONESS to infer single-sample gene regulatory networks. This involves reading PANDA network and preprocessed middle data, computing and normalizing the coexpression network, running the PANDA algorithm, and finally writing out the LIONESS networks. ### Parameters * **obj** (_object_) – PANDA object, generated with keep_expression_matrix=True. * **computing** (_str_) – ‘cpu’ uses Central Processing Unit (CPU) to run PANDA ‘gpu’ use the Graphical Processing Unit (GPU) to run PANDA * **precision** (_str_) – ‘double’ computes the regulatory network in double precision (15 decimal digits). ‘single’ computes the regulatory network in single precision (7 decimal digits) which is faster, requires half the memory but less accurate. * **subset_numbers** (_list_) – List of sample index onto which lioness should be run. ([1,10,20]) * **subset_names** (_list_) – List of sample names onto which lioness should be run. ([‘s1’,’s2’,’s3’]) * **start** (_int_) – Index of first sample to compute the network. If subset_numbers or subset_names is passed, this is ignored * **end** (_int_) – Index of last sample to compute the network. If subset_numbers or subset_names is passed, this is ignored * **all_background** (_bool_) – Pass the flag if you want to keep the whole samples as background * **save_dir** (_str_) – Directory to save the networks. * **save_fmt** (_str_) – Save format. - ‘.npy’: (Default) Numpy file of the network. - ‘.txt’: Text file, only values are saved, no tf or gene names. Will be deprecated. - ‘.csv’: text file with index (tf) and column (gene) names - ‘.h5’: hdf file, fastest way to save the lioness dataframe with index/column names - ‘.mat’: MATLAB file. * **output** (_str_) – * ‘network’ returns all networks in a single edge-by-sample matrix (lioness_obj.total_lioness_network is the unlabeled variable and lioness_obj.export_lioness_results is the row-labeled variable). For large sample sizes, this variable requires large RAM memory. * ’gene_targeting’ returns gene targeting scores for all networks in a single gene-by-sample matrix (lioness_obj.total_lioness_network). * ’tf_targeting’ returns tf targeting scores for all networks in a single gene-by-sample matrix (lioness_obj.total_lioness_network). * **alpha** (_float_) – learning rate, set to 0.1 by default but has to be changed manually to match the learning rate of the PANDA object. * **save_single** (_bool_) – when set to True it will save each lioness network with its sample name inside the lioness output folder * **export_filename** (_str_) – if passed, the final lioness table will be saved with all tf-gene edges as dataframe index and samples as column name * **ignore_final** (_bool_) – if True, no lioness network is kept in memory. This requires saving single networks at each step * **online_coexpression** (_bool_) – if True, each LIONESS correlation is computed using the online coexpression method. ### Returns **export_lioness_results** – Depending on the output argument, this can be either all the lioness networks or their gene/tf targeting scores. ### Example ```python from netZooPy.lioness.lioness import Lioness # To run the Lioness algorithm for single sample networks, first run PANDA using the keep_expression_matrix flag, then use Lioness as follows: panda_obj = Panda("../../tests/ToyData/ToyExpressionData.txt", "../../tests/ToyData/ToyMotifData.txt", "../../tests/ToyData/ToyPPIData.txt", remove_missing=False, keep_expression_matrix=True) lioness_obj = Lioness(panda_obj) ``` ```