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