| 
4
 | 
     1 import argparse
 | 
| 
 | 
     2 import utils.general_utils as utils
 | 
| 
 | 
     3 from typing import Optional, List
 | 
| 
 | 
     4 import os
 | 
| 
 | 
     5 import numpy as np
 | 
| 
 | 
     6 import pandas as pd
 | 
| 
 | 
     7 import cobra
 | 
| 
 | 
     8 import utils.CBS_backend as CBS_backend
 | 
| 
 | 
     9 from joblib import Parallel, delayed, cpu_count
 | 
| 
 | 
    10 from cobra.sampling import OptGPSampler
 | 
| 
 | 
    11 import sys
 | 
| 
 | 
    12 
 | 
| 
 | 
    13 ################################# process args ###############################
 | 
| 
147
 | 
    14 def process_args(args :List[str] = None) -> argparse.Namespace:
 | 
| 
4
 | 
    15     """
 | 
| 
 | 
    16     Processes command-line arguments.
 | 
| 
 | 
    17 
 | 
| 
 | 
    18     Args:
 | 
| 
 | 
    19         args (list): List of command-line arguments.
 | 
| 
 | 
    20 
 | 
| 
 | 
    21     Returns:
 | 
| 
 | 
    22         Namespace: An object containing parsed arguments.
 | 
| 
 | 
    23     """
 | 
| 
 | 
    24     parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
 | 
| 
 | 
    25                                      description = 'process some value\'s')
 | 
| 
 | 
    26 
 | 
| 
 | 
    27     parser.add_argument('-ol', '--out_log', 
 | 
| 
 | 
    28                         help = "Output log")
 | 
| 
 | 
    29     
 | 
| 
 | 
    30     parser.add_argument('-td', '--tool_dir',
 | 
| 
 | 
    31                         type = str,
 | 
| 
 | 
    32                         required = True,
 | 
| 
 | 
    33                         help = 'your tool directory')
 | 
| 
 | 
    34     
 | 
| 
 | 
    35     parser.add_argument('-in', '--input',
 | 
| 
 | 
    36                         required = True,
 | 
| 
 | 
    37                         type=str,
 | 
| 
 | 
    38                         help = 'inputs bounds')
 | 
| 
 | 
    39     
 | 
| 
 | 
    40     parser.add_argument('-ni', '--names',
 | 
| 
 | 
    41                         required = True,
 | 
| 
 | 
    42                         type=str,
 | 
| 
 | 
    43                         help = 'cell names')
 | 
| 
 | 
    44  
 | 
| 
 | 
    45     parser.add_argument(
 | 
| 
 | 
    46         '-ms', '--model_selector', 
 | 
| 
 | 
    47         type = utils.Model, default = utils.Model.ENGRO2, choices = [utils.Model.ENGRO2, utils.Model.Custom],
 | 
| 
 | 
    48         help = 'chose which type of model you want use')
 | 
| 
 | 
    49     
 | 
| 
 | 
    50     parser.add_argument("-mo", "--model", type = str)
 | 
| 
 | 
    51     
 | 
| 
 | 
    52     parser.add_argument("-mn", "--model_name", type = str, help = "custom mode name")
 | 
| 
 | 
    53     
 | 
| 
 | 
    54     parser.add_argument('-a', '--algorithm',
 | 
| 
 | 
    55                         type = str,
 | 
| 
 | 
    56                         choices = ['OPTGP', 'CBS'],
 | 
| 
 | 
    57                         required = True,
 | 
| 
 | 
    58                         help = 'choose sampling algorithm')
 | 
| 
 | 
    59     
 | 
| 
 | 
    60     parser.add_argument('-th', '--thinning', 
 | 
| 
 | 
    61                         type = int,
 | 
| 
 | 
    62                         default= 100,
 | 
| 
 | 
    63                         required=False,
 | 
| 
 | 
    64                         help = 'choose thinning')
 | 
| 
 | 
    65     
 | 
| 
 | 
    66     parser.add_argument('-ns', '--n_samples', 
 | 
| 
 | 
    67                         type = int,
 | 
| 
 | 
    68                         required = True,
 | 
| 
 | 
    69                         help = 'choose how many samples')
 | 
| 
 | 
    70     
 | 
| 
 | 
    71     parser.add_argument('-sd', '--seed', 
 | 
| 
 | 
    72                         type = int,
 | 
| 
 | 
    73                         required = True,
 | 
| 
 | 
    74                         help = 'seed')
 | 
| 
 | 
    75     
 | 
| 
 | 
    76     parser.add_argument('-nb', '--n_batches', 
 | 
| 
 | 
    77                         type = int,
 | 
| 
 | 
    78                         required = True,
 | 
| 
 | 
    79                         help = 'choose how many batches')
 | 
| 
 | 
    80     
 | 
| 
 | 
    81     parser.add_argument('-ot', '--output_type', 
 | 
| 
 | 
    82                         type = str,
 | 
| 
 | 
    83                         required = True,
 | 
| 
 | 
    84                         help = 'output type')
 | 
| 
 | 
    85     
 | 
| 
 | 
    86     parser.add_argument('-ota', '--output_type_analysis', 
 | 
| 
 | 
    87                         type = str,
 | 
| 
 | 
    88                         required = False,
 | 
| 
 | 
    89                         help = 'output type analysis')
 | 
| 
 | 
    90     
 | 
| 
147
 | 
    91     parser.add_argument(
 | 
| 
 | 
    92         '-idop', '--output_path', 
 | 
| 
 | 
    93         type = str,
 | 
| 
 | 
    94         default='result',
 | 
| 
 | 
    95         help = 'output path for maps')
 | 
| 
 | 
    96     
 | 
| 
 | 
    97     ARGS = parser.parse_args(args)
 | 
| 
4
 | 
    98     return ARGS
 | 
| 
 | 
    99 
 | 
| 
 | 
   100 ########################### warning ###########################################
 | 
| 
 | 
   101 def warning(s :str) -> None:
 | 
| 
 | 
   102     """
 | 
| 
 | 
   103     Log a warning message to an output log file and print it to the console.
 | 
| 
 | 
   104 
 | 
| 
 | 
   105     Args:
 | 
| 
 | 
   106         s (str): The warning message to be logged and printed.
 | 
| 
 | 
   107     
 | 
| 
 | 
   108     Returns:
 | 
| 
 | 
   109       None
 | 
| 
 | 
   110     """
 | 
| 
 | 
   111     with open(ARGS.out_log, 'a') as log:
 | 
| 
 | 
   112         log.write(s + "\n\n")
 | 
| 
 | 
   113     print(s)
 | 
| 
 | 
   114 
 | 
| 
 | 
   115 
 | 
| 
 | 
   116 def write_to_file(dataset: pd.DataFrame, name: str, keep_index:bool=False)->None:
 | 
| 
 | 
   117     dataset.index.name = 'Reactions'
 | 
| 
147
 | 
   118     dataset.to_csv(ARGS.output_path + name + ".csv", sep = '\t', index = keep_index)
 | 
| 
4
 | 
   119 
 | 
| 
 | 
   120 ############################ dataset input ####################################
 | 
| 
 | 
   121 def read_dataset(data :str, name :str) -> pd.DataFrame:
 | 
| 
 | 
   122     """
 | 
| 
 | 
   123     Read a dataset from a CSV file and return it as a pandas DataFrame.
 | 
| 
 | 
   124 
 | 
| 
 | 
   125     Args:
 | 
| 
 | 
   126         data (str): Path to the CSV file containing the dataset.
 | 
| 
 | 
   127         name (str): Name of the dataset, used in error messages.
 | 
| 
 | 
   128 
 | 
| 
 | 
   129     Returns:
 | 
| 
 | 
   130         pandas.DataFrame: DataFrame containing the dataset.
 | 
| 
 | 
   131 
 | 
| 
 | 
   132     Raises:
 | 
| 
 | 
   133         pd.errors.EmptyDataError: If the CSV file is empty.
 | 
| 
 | 
   134         sys.exit: If the CSV file has the wrong format, the execution is aborted.
 | 
| 
 | 
   135     """
 | 
| 
 | 
   136     try:
 | 
| 
 | 
   137         dataset = pd.read_csv(data, sep = '\t', header = 0, index_col=0, engine='python')
 | 
| 
 | 
   138     except pd.errors.EmptyDataError:
 | 
| 
 | 
   139         sys.exit('Execution aborted: wrong format of ' + name + '\n')
 | 
| 
 | 
   140     if len(dataset.columns) < 2:
 | 
| 
 | 
   141         sys.exit('Execution aborted: wrong format of ' + name + '\n')
 | 
| 
 | 
   142     return dataset
 | 
| 
 | 
   143 
 | 
| 
 | 
   144 
 | 
| 
 | 
   145 
 | 
| 
 | 
   146 def OPTGP_sampler(model:cobra.Model, model_name:str, n_samples:int=1000, thinning:int=100, n_batches:int=1, seed:int=0)-> None:
 | 
| 
 | 
   147     """
 | 
| 
 | 
   148     Samples from the OPTGP (Optimal Global Perturbation) algorithm and saves the results to CSV files.
 | 
| 
 | 
   149 
 | 
| 
 | 
   150     Args:
 | 
| 
 | 
   151         model (cobra.Model): The COBRA model to sample from.
 | 
| 
 | 
   152         model_name (str): The name of the model, used in naming output files.
 | 
| 
 | 
   153         n_samples (int, optional): Number of samples per batch. Default is 1000.
 | 
| 
 | 
   154         thinning (int, optional): Thinning parameter for the sampler. Default is 100.
 | 
| 
 | 
   155         n_batches (int, optional): Number of batches to run. Default is 1.
 | 
| 
 | 
   156         seed (int, optional): Random seed for reproducibility. Default is 0.
 | 
| 
 | 
   157     
 | 
| 
 | 
   158     Returns:
 | 
| 
 | 
   159         None
 | 
| 
 | 
   160     """
 | 
| 
 | 
   161 
 | 
| 
 | 
   162     for i in range(0, n_batches):
 | 
| 
 | 
   163         optgp = OptGPSampler(model, thinning, seed)
 | 
| 
 | 
   164         samples = optgp.sample(n_samples)
 | 
| 
147
 | 
   165         samples.to_csv(ARGS.output_path +  model_name + '_'+ str(i)+'_OPTGP.csv', index=False)
 | 
| 
4
 | 
   166         seed+=1
 | 
| 
 | 
   167     samplesTotal = pd.DataFrame()
 | 
| 
 | 
   168     for i in range(0, n_batches):
 | 
| 
147
 | 
   169         samples_batch = pd.read_csv(ARGS.output_path  +  model_name + '_'+ str(i)+'_OPTGP.csv')
 | 
| 
4
 | 
   170         samplesTotal = pd.concat([samplesTotal, samples_batch], ignore_index = True)
 | 
| 
 | 
   171 
 | 
| 
 | 
   172     write_to_file(samplesTotal.T, model_name, True)
 | 
| 
 | 
   173 
 | 
| 
 | 
   174     for i in range(0, n_batches):
 | 
| 
147
 | 
   175         os.remove(ARGS.output_path +   model_name + '_'+ str(i)+'_OPTGP.csv')
 | 
| 
4
 | 
   176     pass
 | 
| 
 | 
   177 
 | 
| 
 | 
   178 
 | 
| 
 | 
   179 def CBS_sampler(model:cobra.Model, model_name:str, n_samples:int=1000, n_batches:int=1, seed:int=0)-> None:
 | 
| 
 | 
   180     """
 | 
| 
 | 
   181     Samples using the CBS (Constraint-based Sampling) algorithm and saves the results to CSV files.
 | 
| 
 | 
   182 
 | 
| 
 | 
   183     Args:
 | 
| 
 | 
   184         model (cobra.Model): The COBRA model to sample from.
 | 
| 
 | 
   185         model_name (str): The name of the model, used in naming output files.
 | 
| 
 | 
   186         n_samples (int, optional): Number of samples per batch. Default is 1000.
 | 
| 
 | 
   187         n_batches (int, optional): Number of batches to run. Default is 1.
 | 
| 
 | 
   188         seed (int, optional): Random seed for reproducibility. Default is 0.
 | 
| 
 | 
   189     
 | 
| 
 | 
   190     Returns:
 | 
| 
 | 
   191         None
 | 
| 
 | 
   192     """
 | 
| 
 | 
   193 
 | 
| 
 | 
   194     df_FVA = cobra.flux_analysis.flux_variability_analysis(model,fraction_of_optimum=0).round(6)
 | 
| 
 | 
   195     
 | 
| 
 | 
   196     df_coefficients = CBS_backend.randomObjectiveFunction(model, n_samples*n_batches, df_FVA, seed=seed)
 | 
| 
 | 
   197 
 | 
| 
 | 
   198     for i in range(0, n_batches):
 | 
| 
 | 
   199         samples = pd.DataFrame(columns =[reaction.id for reaction in model.reactions], index = range(n_samples))
 | 
| 
 | 
   200         try:
 | 
| 
 | 
   201             CBS_backend.randomObjectiveFunctionSampling(model, n_samples, df_coefficients.iloc[:,i*n_samples:(i+1)*n_samples], samples)
 | 
| 
 | 
   202         except Exception as e:
 | 
| 
 | 
   203             utils.logWarning(
 | 
| 
 | 
   204             "Warning: GLPK solver has failed for " + model_name + ". Trying with COBRA interface. Error:" + str(e),
 | 
| 
 | 
   205             ARGS.out_log)
 | 
| 
 | 
   206             CBS_backend.randomObjectiveFunctionSampling_cobrapy(model, n_samples, df_coefficients.iloc[:,i*n_samples:(i+1)*n_samples], 
 | 
| 
 | 
   207                                                     samples)
 | 
| 
147
 | 
   208         utils.logWarning(ARGS.output_path +  model_name + '_'+ str(i)+'_CBS.csv', ARGS.out_log)
 | 
| 
 | 
   209         samples.to_csv(ARGS.output_path +  model_name + '_'+ str(i)+'_CBS.csv', index=False)
 | 
| 
4
 | 
   210 
 | 
| 
 | 
   211     samplesTotal = pd.DataFrame()
 | 
| 
 | 
   212     for i in range(0, n_batches):
 | 
| 
147
 | 
   213         samples_batch = pd.read_csv(ARGS.output_path  +  model_name + '_'+ str(i)+'_CBS.csv')
 | 
| 
4
 | 
   214         samplesTotal = pd.concat([samplesTotal, samples_batch], ignore_index = True)
 | 
| 
 | 
   215 
 | 
| 
 | 
   216     write_to_file(samplesTotal.T, model_name, True)
 | 
| 
 | 
   217 
 | 
| 
 | 
   218     for i in range(0, n_batches):
 | 
| 
147
 | 
   219         os.remove(ARGS.output_path +   model_name + '_'+ str(i)+'_CBS.csv')
 | 
| 
4
 | 
   220     pass
 | 
| 
 | 
   221 
 | 
| 
 | 
   222 
 | 
| 
 | 
   223 def model_sampler(model_input_original:cobra.Model, bounds_path:str, cell_name:str)-> List[pd.DataFrame]:
 | 
| 
 | 
   224     """
 | 
| 
 | 
   225     Prepares the model with bounds from the dataset and performs sampling and analysis based on the selected algorithm.
 | 
| 
 | 
   226 
 | 
| 
 | 
   227     Args:
 | 
| 
 | 
   228         model_input_original (cobra.Model): The original COBRA model.
 | 
| 
 | 
   229         bounds_path (str): Path to the CSV file containing the bounds dataset.
 | 
| 
 | 
   230         cell_name (str): Name of the cell, used to generate filenames for output.
 | 
| 
 | 
   231 
 | 
| 
 | 
   232     Returns:
 | 
| 
 | 
   233         List[pd.DataFrame]: A list of DataFrames containing statistics and analysis results.
 | 
| 
 | 
   234     """
 | 
| 
 | 
   235 
 | 
| 
 | 
   236     model_input = model_input_original.copy()
 | 
| 
 | 
   237     bounds_df = read_dataset(bounds_path, "bounds dataset")
 | 
| 
 | 
   238     for rxn_index, row in bounds_df.iterrows():
 | 
| 
 | 
   239         model_input.reactions.get_by_id(rxn_index).lower_bound = row.lower_bound
 | 
| 
 | 
   240         model_input.reactions.get_by_id(rxn_index).upper_bound = row.upper_bound
 | 
| 
 | 
   241     
 | 
| 
142
 | 
   242     name = cell_name
 | 
| 
4
 | 
   243     
 | 
| 
 | 
   244     if ARGS.algorithm == 'OPTGP':
 | 
| 
 | 
   245         OPTGP_sampler(model_input, name, ARGS.n_samples, ARGS.thinning, ARGS.n_batches, ARGS.seed)
 | 
| 
 | 
   246 
 | 
| 
 | 
   247     elif ARGS.algorithm == 'CBS':
 | 
| 
 | 
   248         CBS_sampler(model_input,  name, ARGS.n_samples, ARGS.n_batches, ARGS.seed)
 | 
| 
 | 
   249 
 | 
| 
 | 
   250     df_mean, df_median, df_quantiles = fluxes_statistics(name, ARGS.output_types)
 | 
| 
 | 
   251 
 | 
| 
 | 
   252     if("fluxes" not in ARGS.output_types):
 | 
| 
147
 | 
   253         os.remove(ARGS.output_path  +  name + '.csv')
 | 
| 
4
 | 
   254 
 | 
| 
 | 
   255     returnList = []
 | 
| 
 | 
   256     returnList.append(df_mean)
 | 
| 
 | 
   257     returnList.append(df_median)
 | 
| 
 | 
   258     returnList.append(df_quantiles)
 | 
| 
 | 
   259 
 | 
| 
 | 
   260     df_pFBA, df_FVA, df_sensitivity = fluxes_analysis(model_input, name, ARGS.output_type_analysis)
 | 
| 
 | 
   261 
 | 
| 
 | 
   262     if("pFBA" in ARGS.output_type_analysis):
 | 
| 
 | 
   263         returnList.append(df_pFBA)
 | 
| 
 | 
   264     if("FVA" in ARGS.output_type_analysis):
 | 
| 
 | 
   265         returnList.append(df_FVA)
 | 
| 
 | 
   266     if("sensitivity" in ARGS.output_type_analysis):
 | 
| 
 | 
   267         returnList.append(df_sensitivity)
 | 
| 
 | 
   268 
 | 
| 
 | 
   269     return returnList
 | 
| 
 | 
   270 
 | 
| 
 | 
   271 def fluxes_statistics(model_name: str,  output_types:List)-> List[pd.DataFrame]:
 | 
| 
 | 
   272     """
 | 
| 
 | 
   273     Computes statistics (mean, median, quantiles) for the fluxes.
 | 
| 
 | 
   274 
 | 
| 
 | 
   275     Args:
 | 
| 
 | 
   276         model_name (str): Name of the model, used in filename for input.
 | 
| 
 | 
   277         output_types (List[str]): Types of statistics to compute (mean, median, quantiles).
 | 
| 
 | 
   278 
 | 
| 
 | 
   279     Returns:
 | 
| 
 | 
   280         List[pd.DataFrame]: List of DataFrames containing mean, median, and quantiles statistics.
 | 
| 
 | 
   281     """
 | 
| 
 | 
   282 
 | 
| 
 | 
   283     df_mean = pd.DataFrame()
 | 
| 
 | 
   284     df_median= pd.DataFrame()
 | 
| 
 | 
   285     df_quantiles= pd.DataFrame()
 | 
| 
 | 
   286 
 | 
| 
147
 | 
   287     df_samples = pd.read_csv(ARGS.output_path  +  model_name + '.csv', sep = '\t', index_col = 0).T
 | 
| 
4
 | 
   288     df_samples = df_samples.round(8)
 | 
| 
 | 
   289 
 | 
| 
 | 
   290     for output_type in output_types:
 | 
| 
 | 
   291         if(output_type == "mean"):
 | 
| 
 | 
   292             df_mean = df_samples.mean()
 | 
| 
 | 
   293             df_mean = df_mean.to_frame().T
 | 
| 
 | 
   294             df_mean = df_mean.reset_index(drop=True)
 | 
| 
 | 
   295             df_mean.index = [model_name]
 | 
| 
 | 
   296         elif(output_type == "median"):
 | 
| 
 | 
   297             df_median = df_samples.median()
 | 
| 
 | 
   298             df_median = df_median.to_frame().T
 | 
| 
 | 
   299             df_median = df_median.reset_index(drop=True)
 | 
| 
 | 
   300             df_median.index = [model_name]
 | 
| 
 | 
   301         elif(output_type == "quantiles"):
 | 
| 
 | 
   302             newRow = []
 | 
| 
 | 
   303             cols = []
 | 
| 
 | 
   304             for rxn in df_samples.columns:
 | 
| 
 | 
   305                 quantiles = df_samples[rxn].quantile([0.25, 0.50, 0.75])
 | 
| 
 | 
   306                 newRow.append(quantiles[0.25])
 | 
| 
 | 
   307                 cols.append(rxn + "_q1")
 | 
| 
 | 
   308                 newRow.append(quantiles[0.5])
 | 
| 
 | 
   309                 cols.append(rxn + "_q2")
 | 
| 
 | 
   310                 newRow.append(quantiles[0.75])
 | 
| 
 | 
   311                 cols.append(rxn + "_q3")
 | 
| 
 | 
   312             df_quantiles = pd.DataFrame(columns=cols)
 | 
| 
 | 
   313             df_quantiles.loc[0] = newRow
 | 
| 
 | 
   314             df_quantiles = df_quantiles.reset_index(drop=True)
 | 
| 
 | 
   315             df_quantiles.index = [model_name]
 | 
| 
 | 
   316     
 | 
| 
 | 
   317     return df_mean, df_median, df_quantiles
 | 
| 
 | 
   318 
 | 
| 
 | 
   319 def fluxes_analysis(model:cobra.Model,  model_name:str, output_types:List)-> List[pd.DataFrame]:
 | 
| 
 | 
   320     """
 | 
| 
 | 
   321     Performs flux analysis including pFBA, FVA, and sensitivity analysis.
 | 
| 
 | 
   322 
 | 
| 
 | 
   323     Args:
 | 
| 
 | 
   324         model (cobra.Model): The COBRA model to analyze.
 | 
| 
 | 
   325         model_name (str): Name of the model, used in filenames for output.
 | 
| 
 | 
   326         output_types (List[str]): Types of analysis to perform (pFBA, FVA, sensitivity).
 | 
| 
 | 
   327 
 | 
| 
 | 
   328     Returns:
 | 
| 
 | 
   329         List[pd.DataFrame]: List of DataFrames containing pFBA, FVA, and sensitivity analysis results.
 | 
| 
 | 
   330     """
 | 
| 
 | 
   331 
 | 
| 
 | 
   332     df_pFBA = pd.DataFrame()
 | 
| 
 | 
   333     df_FVA= pd.DataFrame()
 | 
| 
 | 
   334     df_sensitivity= pd.DataFrame()
 | 
| 
 | 
   335 
 | 
| 
 | 
   336     for output_type in output_types:
 | 
| 
 | 
   337         if(output_type == "pFBA"):
 | 
| 
 | 
   338             model.objective = "Biomass"
 | 
| 
 | 
   339             solution = cobra.flux_analysis.pfba(model)
 | 
| 
 | 
   340             fluxes = solution.fluxes
 | 
| 
 | 
   341             df_pFBA.loc[0,[rxn._id for rxn in model.reactions]] = fluxes.tolist()
 | 
| 
 | 
   342             df_pFBA = df_pFBA.reset_index(drop=True)
 | 
| 
 | 
   343             df_pFBA.index = [model_name]
 | 
| 
 | 
   344             df_pFBA = df_pFBA.astype(float).round(6)
 | 
| 
 | 
   345         elif(output_type == "FVA"):
 | 
| 
 | 
   346             fva = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
 | 
| 
 | 
   347             columns = []
 | 
| 
 | 
   348             for rxn in fva.index.to_list():
 | 
| 
 | 
   349                 columns.append(rxn + "_min")
 | 
| 
 | 
   350                 columns.append(rxn + "_max")
 | 
| 
 | 
   351             df_FVA= pd.DataFrame(columns = columns)
 | 
| 
 | 
   352             for index_rxn, row in fva.iterrows():
 | 
| 
 | 
   353                 df_FVA.loc[0, index_rxn+ "_min"] = fva.loc[index_rxn, "minimum"]
 | 
| 
 | 
   354                 df_FVA.loc[0, index_rxn+ "_max"] = fva.loc[index_rxn, "maximum"]
 | 
| 
 | 
   355             df_FVA = df_FVA.reset_index(drop=True)
 | 
| 
 | 
   356             df_FVA.index = [model_name]
 | 
| 
 | 
   357             df_FVA = df_FVA.astype(float).round(6)
 | 
| 
 | 
   358         elif(output_type == "sensitivity"):
 | 
| 
 | 
   359             model.objective = "Biomass"
 | 
| 
 | 
   360             solution_original = model.optimize().objective_value
 | 
| 
 | 
   361             reactions = model.reactions
 | 
| 
 | 
   362             single = cobra.flux_analysis.single_reaction_deletion(model)
 | 
| 
 | 
   363             newRow = []
 | 
| 
 | 
   364             df_sensitivity = pd.DataFrame(columns = [rxn.id for rxn in reactions], index = [model_name])
 | 
| 
 | 
   365             for rxn in reactions:
 | 
| 
 | 
   366                 newRow.append(single.knockout[rxn.id].growth.values[0]/solution_original)
 | 
| 
 | 
   367             df_sensitivity.loc[model_name] = newRow
 | 
| 
 | 
   368             df_sensitivity = df_sensitivity.astype(float).round(6)
 | 
| 
 | 
   369     return df_pFBA, df_FVA, df_sensitivity
 | 
| 
 | 
   370 
 | 
| 
 | 
   371 ############################# main ###########################################
 | 
| 
147
 | 
   372 def main(args :List[str] = None) -> None:
 | 
| 
4
 | 
   373     """
 | 
| 
 | 
   374     Initializes everything and sets the program in motion based on the fronted input arguments.
 | 
| 
 | 
   375 
 | 
| 
 | 
   376     Returns:
 | 
| 
 | 
   377         None
 | 
| 
 | 
   378     """
 | 
| 
 | 
   379     if not os.path.exists('flux_simulation/'):
 | 
| 
 | 
   380         os.makedirs('flux_simulation/')
 | 
| 
 | 
   381 
 | 
| 
 | 
   382     num_processors = cpu_count()
 | 
| 
 | 
   383 
 | 
| 
 | 
   384     global ARGS
 | 
| 
147
 | 
   385     ARGS = process_args(args)
 | 
| 
 | 
   386   
 | 
| 
4
 | 
   387     
 | 
| 
 | 
   388     model_type :utils.Model = ARGS.model_selector
 | 
| 
 | 
   389     if model_type is utils.Model.Custom:
 | 
| 
 | 
   390         model = model_type.getCOBRAmodel(customPath = utils.FilePath.fromStrPath(ARGS.model), customExtension = utils.FilePath.fromStrPath(ARGS.model_name).ext)
 | 
| 
 | 
   391     else:
 | 
| 
 | 
   392         model = model_type.getCOBRAmodel(toolDir=ARGS.tool_dir)
 | 
| 
 | 
   393     
 | 
| 
 | 
   394     ARGS.bounds = ARGS.input.split(",")
 | 
| 
 | 
   395     ARGS.bounds_name = ARGS.names.split(",")
 | 
| 
 | 
   396     ARGS.output_types = ARGS.output_type.split(",")
 | 
| 
 | 
   397     ARGS.output_type_analysis = ARGS.output_type_analysis.split(",")
 | 
| 
 | 
   398 
 | 
| 
 | 
   399 
 | 
| 
 | 
   400     results = Parallel(n_jobs=num_processors)(delayed(model_sampler)(model, bounds_path, cell_name) for bounds_path, cell_name in zip(ARGS.bounds, ARGS.bounds_name))
 | 
| 
 | 
   401 
 | 
| 
 | 
   402     all_mean = pd.concat([result[0] for result in results], ignore_index=False)
 | 
| 
 | 
   403     all_median = pd.concat([result[1] for result in results], ignore_index=False)
 | 
| 
 | 
   404     all_quantiles = pd.concat([result[2] for result in results], ignore_index=False)
 | 
| 
 | 
   405 
 | 
| 
 | 
   406     if("mean" in ARGS.output_types):
 | 
| 
 | 
   407         all_mean = all_mean.fillna(0.0)
 | 
| 
 | 
   408         all_mean = all_mean.sort_index()
 | 
| 
 | 
   409         write_to_file(all_mean.T, "mean", True)
 | 
| 
 | 
   410 
 | 
| 
 | 
   411     if("median" in ARGS.output_types):
 | 
| 
 | 
   412         all_median = all_median.fillna(0.0)
 | 
| 
 | 
   413         all_median = all_median.sort_index()
 | 
| 
 | 
   414         write_to_file(all_median.T, "median", True)
 | 
| 
 | 
   415     
 | 
| 
 | 
   416     if("quantiles" in ARGS.output_types):
 | 
| 
 | 
   417         all_quantiles = all_quantiles.fillna(0.0)
 | 
| 
 | 
   418         all_quantiles = all_quantiles.sort_index()
 | 
| 
 | 
   419         write_to_file(all_quantiles.T, "quantiles", True)
 | 
| 
 | 
   420 
 | 
| 
 | 
   421     index_result = 3
 | 
| 
 | 
   422     if("pFBA" in ARGS.output_type_analysis):
 | 
| 
 | 
   423         all_pFBA = pd.concat([result[index_result] for result in results], ignore_index=False)
 | 
| 
 | 
   424         all_pFBA = all_pFBA.sort_index()
 | 
| 
 | 
   425         write_to_file(all_pFBA.T, "pFBA", True)
 | 
| 
 | 
   426         index_result+=1
 | 
| 
 | 
   427     if("FVA" in ARGS.output_type_analysis):
 | 
| 
 | 
   428         all_FVA= pd.concat([result[index_result] for result in results], ignore_index=False)
 | 
| 
 | 
   429         all_FVA = all_FVA.sort_index()
 | 
| 
 | 
   430         write_to_file(all_FVA.T, "FVA", True)
 | 
| 
 | 
   431         index_result+=1
 | 
| 
 | 
   432     if("sensitivity" in ARGS.output_type_analysis):
 | 
| 
 | 
   433         all_sensitivity = pd.concat([result[index_result] for result in results], ignore_index=False)
 | 
| 
 | 
   434         all_sensitivity = all_sensitivity.sort_index()
 | 
| 
 | 
   435         write_to_file(all_sensitivity.T, "sensitivity", True)
 | 
| 
 | 
   436 
 | 
| 
 | 
   437     pass
 | 
| 
 | 
   438         
 | 
| 
 | 
   439 ##############################################################################
 | 
| 
 | 
   440 if __name__ == "__main__":
 | 
| 
 | 
   441     main() |