| 489 | 1 """ | 
|  | 2 Flux sampling and analysis utilities for COBRA models. | 
|  | 3 | 
|  | 4 This script supports two modes: | 
|  | 5 - Mode 1 (model_and_bounds=True): load a base model and apply bounds from | 
|  | 6     separate files before sampling. | 
|  | 7 - Mode 2 (model_and_bounds=False): load complete models and sample directly. | 
|  | 8 | 
|  | 9 Sampling algorithms supported: OPTGP and CBS. Outputs include flux samples | 
|  | 10 and optional analyses (pFBA, FVA, sensitivity), saved as tabular files. | 
|  | 11 """ | 
|  | 12 | 
| 4 | 13 import argparse | 
|  | 14 import utils.general_utils as utils | 
| 489 | 15 from typing import List | 
| 4 | 16 import os | 
| 489 | 17 import pandas as pd | 
| 4 | 18 import numpy as np | 
|  | 19 import cobra | 
|  | 20 import utils.CBS_backend as CBS_backend | 
|  | 21 from joblib import Parallel, delayed, cpu_count | 
|  | 22 from cobra.sampling import OptGPSampler | 
|  | 23 import sys | 
| 489 | 24 import utils.model_utils as model_utils | 
|  | 25 | 
| 4 | 26 | 
|  | 27 ################################# process args ############################### | 
| 489 | 28 def process_args(args: List[str] = None) -> argparse.Namespace: | 
| 4 | 29     """ | 
|  | 30     Processes command-line arguments. | 
| 489 | 31 | 
| 4 | 32     Args: | 
|  | 33         args (list): List of command-line arguments. | 
| 489 | 34 | 
| 4 | 35     Returns: | 
|  | 36         Namespace: An object containing parsed arguments. | 
|  | 37     """ | 
| 489 | 38     parser = argparse.ArgumentParser(usage='%(prog)s [options]', | 
|  | 39                                      description='process some value\'s') | 
|  | 40 | 
|  | 41     parser.add_argument("-mo", "--model_upload", type=str, | 
|  | 42         help="path to input file with custom rules, if provided") | 
|  | 43 | 
|  | 44     parser.add_argument("-mab", "--model_and_bounds", type=str, | 
|  | 45         choices=['True', 'False'], | 
|  | 46         required=True, | 
|  | 47         help="upload mode: True for model+bounds, False for complete models") | 
|  | 48 | 
|  | 49     parser.add_argument("-ens", "--sampling_enabled", type=str, | 
|  | 50         choices=['true', 'false'], | 
|  | 51         required=True, | 
|  | 52         help="enable sampling: 'true' for sampling, 'false' for no sampling") | 
|  | 53 | 
|  | 54     parser.add_argument('-ol', '--out_log', | 
|  | 55                         help="Output log") | 
| 4 | 56 | 
|  | 57     parser.add_argument('-td', '--tool_dir', | 
| 489 | 58                         type=str, | 
|  | 59                         required=True, | 
|  | 60                         help='your tool directory') | 
| 4 | 61 | 
|  | 62     parser.add_argument('-in', '--input', | 
| 489 | 63                         required=True, | 
| 4 | 64                         type=str, | 
| 489 | 65                         help='input bounds files or complete model files') | 
| 4 | 66 | 
| 489 | 67     parser.add_argument('-ni', '--name', | 
|  | 68                         required=True, | 
|  | 69                         type=str, | 
|  | 70                         help='cell names') | 
| 4 | 71 | 
|  | 72     parser.add_argument('-a', '--algorithm', | 
| 489 | 73                         type=str, | 
|  | 74                         choices=['OPTGP', 'CBS'], | 
|  | 75                         required=True, | 
|  | 76                         help='choose sampling algorithm') | 
| 4 | 77 | 
| 489 | 78     parser.add_argument('-th', '--thinning', | 
|  | 79                         type=int, | 
|  | 80                         default=100, | 
|  | 81                         required=True, | 
|  | 82                         help='choose thinning') | 
| 4 | 83 | 
| 489 | 84     parser.add_argument('-ns', '--n_samples', | 
|  | 85                         type=int, | 
|  | 86                         required=True, | 
|  | 87                         help='choose how many samples (set to 0 for optimization only)') | 
|  | 88 | 
|  | 89     parser.add_argument('-sd', '--seed', | 
|  | 90                         type=int, | 
|  | 91                         required=True, | 
|  | 92                         help='seed for random number generation') | 
| 4 | 93 | 
| 489 | 94     parser.add_argument('-nb', '--n_batches', | 
|  | 95                         type=int, | 
|  | 96                         required=True, | 
|  | 97                         help='choose how many batches') | 
| 4 | 98 | 
| 489 | 99     parser.add_argument('-opt', '--perc_opt', | 
|  | 100                         type=float, | 
|  | 101                         default=0.9, | 
|  | 102                         required=False, | 
|  | 103                         help='choose the fraction of optimality for FVA (0-1)') | 
| 4 | 104 | 
| 489 | 105     parser.add_argument('-ot', '--output_type', | 
|  | 106                         type=str, | 
|  | 107                         required=True, | 
|  | 108                         help='output type for sampling results') | 
| 4 | 109 | 
| 489 | 110     parser.add_argument('-ota', '--output_type_analysis', | 
|  | 111                         type=str, | 
|  | 112                         required=False, | 
|  | 113                         help='output type analysis (optimization methods)') | 
| 4 | 114 | 
| 489 | 115     parser.add_argument('-idop', '--output_path', | 
|  | 116                         type=str, | 
| 159 | 117                         default='flux_simulation', | 
| 489 | 118                         help='output path for maps') | 
| 147 | 119 | 
|  | 120     ARGS = parser.parse_args(args) | 
| 4 | 121     return ARGS | 
|  | 122 ########################### warning ########################################### | 
|  | 123 def warning(s :str) -> None: | 
|  | 124     """ | 
|  | 125     Log a warning message to an output log file and print it to the console. | 
|  | 126 | 
|  | 127     Args: | 
|  | 128         s (str): The warning message to be logged and printed. | 
|  | 129 | 
|  | 130     Returns: | 
|  | 131       None | 
|  | 132     """ | 
|  | 133     with open(ARGS.out_log, 'a') as log: | 
|  | 134         log.write(s + "\n\n") | 
|  | 135     print(s) | 
|  | 136 | 
|  | 137 | 
|  | 138 def write_to_file(dataset: pd.DataFrame, name: str, keep_index:bool=False)->None: | 
| 489 | 139     """ | 
|  | 140     Write a DataFrame to a TSV file under ARGS.output_path with a given base name. | 
|  | 141 | 
|  | 142     Args: | 
|  | 143         dataset: The DataFrame to write. | 
|  | 144         name: Base file name (without extension). | 
|  | 145         keep_index: Whether to keep the DataFrame index in the file. | 
|  | 146 | 
|  | 147     Returns: | 
|  | 148         None | 
|  | 149     """ | 
| 4 | 150     dataset.index.name = 'Reactions' | 
| 161 | 151     dataset.to_csv(ARGS.output_path + "/" + name + ".csv", sep = '\t', index = keep_index) | 
| 4 | 152 | 
|  | 153 ############################ dataset input #################################### | 
|  | 154 def read_dataset(data :str, name :str) -> pd.DataFrame: | 
|  | 155     """ | 
|  | 156     Read a dataset from a CSV file and return it as a pandas DataFrame. | 
|  | 157 | 
|  | 158     Args: | 
|  | 159         data (str): Path to the CSV file containing the dataset. | 
|  | 160         name (str): Name of the dataset, used in error messages. | 
|  | 161 | 
|  | 162     Returns: | 
|  | 163         pandas.DataFrame: DataFrame containing the dataset. | 
|  | 164 | 
|  | 165     Raises: | 
|  | 166         pd.errors.EmptyDataError: If the CSV file is empty. | 
|  | 167         sys.exit: If the CSV file has the wrong format, the execution is aborted. | 
|  | 168     """ | 
|  | 169     try: | 
|  | 170         dataset = pd.read_csv(data, sep = '\t', header = 0, index_col=0, engine='python') | 
|  | 171     except pd.errors.EmptyDataError: | 
|  | 172         sys.exit('Execution aborted: wrong format of ' + name + '\n') | 
|  | 173     if len(dataset.columns) < 2: | 
|  | 174         sys.exit('Execution aborted: wrong format of ' + name + '\n') | 
|  | 175     return dataset | 
|  | 176 | 
|  | 177 | 
|  | 178 | 
| 489 | 179 def OPTGP_sampler(model: cobra.Model, model_name: str, n_samples: int = 1000, thinning: int = 100, n_batches: int = 1, seed: int = 0) -> None: | 
| 4 | 180     """ | 
|  | 181     Samples from the OPTGP (Optimal Global Perturbation) algorithm and saves the results to CSV files. | 
| 489 | 182 | 
| 4 | 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         thinning (int, optional): Thinning parameter for the sampler. Default is 100. | 
|  | 188         n_batches (int, optional): Number of batches to run. Default is 1. | 
|  | 189         seed (int, optional): Random seed for reproducibility. Default is 0. | 
| 489 | 190 | 
| 4 | 191     Returns: | 
|  | 192         None | 
|  | 193     """ | 
| 489 | 194     import numpy as np | 
|  | 195 | 
|  | 196     # Get reaction IDs for consistent column ordering | 
|  | 197     reaction_ids = [rxn.id for rxn in model.reactions] | 
|  | 198 | 
|  | 199     # Sample and save each batch as numpy file | 
|  | 200     for i in range(n_batches): | 
| 4 | 201         optgp = OptGPSampler(model, thinning, seed) | 
|  | 202         samples = optgp.sample(n_samples) | 
| 489 | 203 | 
|  | 204         # Save as numpy array (more memory efficient) | 
|  | 205         batch_filename = f"{ARGS.output_path}/{model_name}_{i}_OPTGP.npy" | 
|  | 206         np.save(batch_filename, samples.to_numpy()) | 
|  | 207 | 
|  | 208         seed += 1 | 
|  | 209 | 
|  | 210     # Merge all batches into a single DataFrame | 
|  | 211     all_samples = [] | 
|  | 212 | 
|  | 213     for i in range(n_batches): | 
|  | 214         batch_filename = f"{ARGS.output_path}/{model_name}_{i}_OPTGP.npy" | 
|  | 215         batch_data = np.load(batch_filename, allow_pickle=True) | 
|  | 216         all_samples.append(batch_data) | 
|  | 217 | 
|  | 218     # Concatenate all batches | 
|  | 219     samplesTotal_array = np.vstack(all_samples) | 
|  | 220 | 
|  | 221     # Convert back to DataFrame with proper column names | 
|  | 222     samplesTotal = pd.DataFrame(samplesTotal_array, columns=reaction_ids) | 
|  | 223 | 
|  | 224     # Save the final merged result as CSV | 
| 4 | 225     write_to_file(samplesTotal.T, model_name, True) | 
| 489 | 226 | 
|  | 227     # Clean up temporary numpy files | 
|  | 228     for i in range(n_batches): | 
|  | 229         batch_filename = f"{ARGS.output_path}/{model_name}_{i}_OPTGP.npy" | 
|  | 230         if os.path.exists(batch_filename): | 
|  | 231             os.remove(batch_filename) | 
| 4 | 232 | 
|  | 233 | 
| 489 | 234 def CBS_sampler(model: cobra.Model, model_name: str, n_samples: int = 1000, n_batches: int = 1, seed: int = 0) -> None: | 
| 4 | 235     """ | 
|  | 236     Samples using the CBS (Constraint-based Sampling) algorithm and saves the results to CSV files. | 
| 489 | 237 | 
| 4 | 238     Args: | 
|  | 239         model (cobra.Model): The COBRA model to sample from. | 
|  | 240         model_name (str): The name of the model, used in naming output files. | 
|  | 241         n_samples (int, optional): Number of samples per batch. Default is 1000. | 
|  | 242         n_batches (int, optional): Number of batches to run. Default is 1. | 
|  | 243         seed (int, optional): Random seed for reproducibility. Default is 0. | 
| 489 | 244 | 
| 4 | 245     Returns: | 
|  | 246         None | 
|  | 247     """ | 
| 489 | 248     import numpy as np | 
|  | 249 | 
|  | 250     # Get reaction IDs for consistent column ordering | 
|  | 251     reaction_ids = [reaction.id for reaction in model.reactions] | 
|  | 252 | 
|  | 253     # Perform FVA analysis once for all batches | 
|  | 254     df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0).round(6) | 
|  | 255 | 
|  | 256     # Generate random objective functions for all samples across all batches | 
|  | 257     df_coefficients = CBS_backend.randomObjectiveFunction(model, n_samples * n_batches, df_FVA, seed=seed) | 
| 4 | 258 | 
| 489 | 259     # Sample and save each batch as numpy file | 
|  | 260     for i in range(n_batches): | 
|  | 261         samples = pd.DataFrame(columns=reaction_ids, index=range(n_samples)) | 
|  | 262 | 
| 4 | 263         try: | 
| 489 | 264             CBS_backend.randomObjectiveFunctionSampling( | 
|  | 265                 model, | 
|  | 266                 n_samples, | 
|  | 267                 df_coefficients.iloc[:, i * n_samples:(i + 1) * n_samples], | 
|  | 268                 samples | 
|  | 269             ) | 
| 4 | 270         except Exception as e: | 
|  | 271             utils.logWarning( | 
| 489 | 272                 f"Warning: GLPK solver has failed for {model_name}. Trying with COBRA interface. Error: {str(e)}", | 
|  | 273                 ARGS.out_log | 
|  | 274             ) | 
|  | 275             CBS_backend.randomObjectiveFunctionSampling_cobrapy( | 
|  | 276                 model, | 
|  | 277                 n_samples, | 
|  | 278                 df_coefficients.iloc[:, i * n_samples:(i + 1) * n_samples], | 
|  | 279                 samples | 
|  | 280             ) | 
|  | 281 | 
|  | 282         # Save as numpy array (more memory efficient) | 
|  | 283         batch_filename = f"{ARGS.output_path}/{model_name}_{i}_CBS.npy" | 
|  | 284         utils.logWarning(batch_filename, ARGS.out_log) | 
|  | 285         np.save(batch_filename, samples.to_numpy()) | 
|  | 286 | 
|  | 287     # Merge all batches into a single DataFrame | 
|  | 288     all_samples = [] | 
|  | 289 | 
|  | 290     for i in range(n_batches): | 
|  | 291         batch_filename = f"{ARGS.output_path}/{model_name}_{i}_CBS.npy" | 
|  | 292         batch_data = np.load(batch_filename, allow_pickle=True) | 
|  | 293         all_samples.append(batch_data) | 
|  | 294 | 
|  | 295     # Concatenate all batches | 
|  | 296     samplesTotal_array = np.vstack(all_samples) | 
|  | 297 | 
|  | 298     # Convert back to DataFrame with proper column namesq | 
|  | 299     samplesTotal = pd.DataFrame(samplesTotal_array, columns=reaction_ids) | 
|  | 300 | 
|  | 301     # Save the final merged result as CSV | 
| 4 | 302     write_to_file(samplesTotal.T, model_name, True) | 
| 489 | 303 | 
|  | 304     # Clean up temporary numpy files | 
|  | 305     for i in range(n_batches): | 
|  | 306         batch_filename = f"{ARGS.output_path}/{model_name}_{i}_CBS.npy" | 
|  | 307         if os.path.exists(batch_filename): | 
|  | 308             os.remove(batch_filename) | 
| 4 | 309 | 
|  | 310 | 
| 489 | 311 | 
|  | 312 def model_sampler_with_bounds(model_input_original: cobra.Model, bounds_path: str, cell_name: str) -> List[pd.DataFrame]: | 
| 4 | 313     """ | 
| 489 | 314     MODE 1: Prepares the model with bounds from separate bounds file and performs sampling. | 
| 4 | 315 | 
|  | 316     Args: | 
|  | 317         model_input_original (cobra.Model): The original COBRA model. | 
|  | 318         bounds_path (str): Path to the CSV file containing the bounds dataset. | 
|  | 319         cell_name (str): Name of the cell, used to generate filenames for output. | 
|  | 320 | 
|  | 321     Returns: | 
|  | 322         List[pd.DataFrame]: A list of DataFrames containing statistics and analysis results. | 
|  | 323     """ | 
|  | 324 | 
|  | 325     model_input = model_input_original.copy() | 
|  | 326     bounds_df = read_dataset(bounds_path, "bounds dataset") | 
|  | 327 | 
| 489 | 328     # Apply bounds to model | 
|  | 329     for rxn_index, row in bounds_df.iterrows(): | 
|  | 330         try: | 
|  | 331             model_input.reactions.get_by_id(rxn_index).lower_bound = row.lower_bound | 
|  | 332             model_input.reactions.get_by_id(rxn_index).upper_bound = row.upper_bound | 
|  | 333         except KeyError: | 
|  | 334             warning(f"Warning: Reaction {rxn_index} not found in model. Skipping.") | 
| 4 | 335 | 
| 489 | 336     return perform_sampling_and_analysis(model_input, cell_name) | 
|  | 337 | 
| 4 | 338 | 
| 489 | 339 def perform_sampling_and_analysis(model_input: cobra.Model, cell_name: str) -> List[pd.DataFrame]: | 
|  | 340     """ | 
|  | 341     Common function to perform sampling and analysis on a prepared model. | 
| 4 | 342 | 
| 489 | 343     Args: | 
|  | 344         model_input (cobra.Model): The prepared COBRA model with bounds applied. | 
|  | 345         cell_name (str): Name of the cell, used to generate filenames for output. | 
| 4 | 346 | 
| 489 | 347     Returns: | 
|  | 348         List[pd.DataFrame]: A list of DataFrames containing statistics and analysis results. | 
|  | 349     """ | 
| 4 | 350 | 
|  | 351     returnList = [] | 
| 489 | 352 | 
|  | 353     if ARGS.sampling_enabled == "true": | 
|  | 354 | 
|  | 355         if ARGS.algorithm == 'OPTGP': | 
|  | 356             OPTGP_sampler(model_input, cell_name, ARGS.n_samples, ARGS.thinning, ARGS.n_batches, ARGS.seed) | 
|  | 357         elif ARGS.algorithm == 'CBS': | 
|  | 358             CBS_sampler(model_input, cell_name, ARGS.n_samples, ARGS.n_batches, ARGS.seed) | 
|  | 359 | 
|  | 360         df_mean, df_median, df_quantiles = fluxes_statistics(cell_name, ARGS.output_types) | 
|  | 361 | 
|  | 362         if("fluxes" not in ARGS.output_types): | 
|  | 363             os.remove(ARGS.output_path + "/" + cell_name + '.csv') | 
|  | 364 | 
|  | 365         returnList = [df_mean, df_median, df_quantiles] | 
| 4 | 366 | 
| 210 | 367     df_pFBA, df_FVA, df_sensitivity = fluxes_analysis(model_input, cell_name, ARGS.output_type_analysis) | 
| 4 | 368 | 
|  | 369     if("pFBA" in ARGS.output_type_analysis): | 
|  | 370         returnList.append(df_pFBA) | 
|  | 371     if("FVA" in ARGS.output_type_analysis): | 
|  | 372         returnList.append(df_FVA) | 
|  | 373     if("sensitivity" in ARGS.output_type_analysis): | 
|  | 374         returnList.append(df_sensitivity) | 
|  | 375 | 
|  | 376     return returnList | 
|  | 377 | 
|  | 378 def fluxes_statistics(model_name: str,  output_types:List)-> List[pd.DataFrame]: | 
|  | 379     """ | 
|  | 380     Computes statistics (mean, median, quantiles) for the fluxes. | 
|  | 381 | 
|  | 382     Args: | 
|  | 383         model_name (str): Name of the model, used in filename for input. | 
|  | 384         output_types (List[str]): Types of statistics to compute (mean, median, quantiles). | 
|  | 385 | 
|  | 386     Returns: | 
|  | 387         List[pd.DataFrame]: List of DataFrames containing mean, median, and quantiles statistics. | 
|  | 388     """ | 
|  | 389 | 
|  | 390     df_mean = pd.DataFrame() | 
|  | 391     df_median= pd.DataFrame() | 
|  | 392     df_quantiles= pd.DataFrame() | 
|  | 393 | 
| 161 | 394     df_samples = pd.read_csv(ARGS.output_path + "/"  +  model_name + '.csv', sep = '\t', index_col = 0).T | 
| 4 | 395     df_samples = df_samples.round(8) | 
|  | 396 | 
|  | 397     for output_type in output_types: | 
|  | 398         if(output_type == "mean"): | 
|  | 399             df_mean = df_samples.mean() | 
|  | 400             df_mean = df_mean.to_frame().T | 
|  | 401             df_mean = df_mean.reset_index(drop=True) | 
|  | 402             df_mean.index = [model_name] | 
|  | 403         elif(output_type == "median"): | 
|  | 404             df_median = df_samples.median() | 
|  | 405             df_median = df_median.to_frame().T | 
|  | 406             df_median = df_median.reset_index(drop=True) | 
|  | 407             df_median.index = [model_name] | 
|  | 408         elif(output_type == "quantiles"): | 
|  | 409             newRow = [] | 
|  | 410             cols = [] | 
|  | 411             for rxn in df_samples.columns: | 
|  | 412                 quantiles = df_samples[rxn].quantile([0.25, 0.50, 0.75]) | 
|  | 413                 newRow.append(quantiles[0.25]) | 
|  | 414                 cols.append(rxn + "_q1") | 
|  | 415                 newRow.append(quantiles[0.5]) | 
|  | 416                 cols.append(rxn + "_q2") | 
|  | 417                 newRow.append(quantiles[0.75]) | 
|  | 418                 cols.append(rxn + "_q3") | 
|  | 419             df_quantiles = pd.DataFrame(columns=cols) | 
|  | 420             df_quantiles.loc[0] = newRow | 
|  | 421             df_quantiles = df_quantiles.reset_index(drop=True) | 
|  | 422             df_quantiles.index = [model_name] | 
|  | 423 | 
|  | 424     return df_mean, df_median, df_quantiles | 
|  | 425 | 
|  | 426 def fluxes_analysis(model:cobra.Model,  model_name:str, output_types:List)-> List[pd.DataFrame]: | 
|  | 427     """ | 
| 489 | 428     Performs flux analysis including pFBA, FVA, and sensitivity analysis. The objective function | 
|  | 429     is assumed to be already set in the model. | 
| 4 | 430 | 
|  | 431     Args: | 
|  | 432         model (cobra.Model): The COBRA model to analyze. | 
|  | 433         model_name (str): Name of the model, used in filenames for output. | 
|  | 434         output_types (List[str]): Types of analysis to perform (pFBA, FVA, sensitivity). | 
|  | 435 | 
|  | 436     Returns: | 
|  | 437         List[pd.DataFrame]: List of DataFrames containing pFBA, FVA, and sensitivity analysis results. | 
|  | 438     """ | 
|  | 439 | 
|  | 440     df_pFBA = pd.DataFrame() | 
|  | 441     df_FVA= pd.DataFrame() | 
|  | 442     df_sensitivity= pd.DataFrame() | 
|  | 443 | 
|  | 444     for output_type in output_types: | 
|  | 445         if(output_type == "pFBA"): | 
|  | 446             solution = cobra.flux_analysis.pfba(model) | 
|  | 447             fluxes = solution.fluxes | 
| 489 | 448             df_pFBA.loc[0,[rxn.id for rxn in model.reactions]] = fluxes.tolist() | 
| 4 | 449             df_pFBA = df_pFBA.reset_index(drop=True) | 
|  | 450             df_pFBA.index = [model_name] | 
|  | 451             df_pFBA = df_pFBA.astype(float).round(6) | 
|  | 452         elif(output_type == "FVA"): | 
| 489 | 453             fva = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=ARGS.perc_opt, processes=1).round(8) | 
| 4 | 454             columns = [] | 
|  | 455             for rxn in fva.index.to_list(): | 
|  | 456                 columns.append(rxn + "_min") | 
|  | 457                 columns.append(rxn + "_max") | 
|  | 458             df_FVA= pd.DataFrame(columns = columns) | 
|  | 459             for index_rxn, row in fva.iterrows(): | 
|  | 460                 df_FVA.loc[0, index_rxn+ "_min"] = fva.loc[index_rxn, "minimum"] | 
|  | 461                 df_FVA.loc[0, index_rxn+ "_max"] = fva.loc[index_rxn, "maximum"] | 
|  | 462             df_FVA = df_FVA.reset_index(drop=True) | 
|  | 463             df_FVA.index = [model_name] | 
|  | 464             df_FVA = df_FVA.astype(float).round(6) | 
|  | 465         elif(output_type == "sensitivity"): | 
|  | 466             solution_original = model.optimize().objective_value | 
|  | 467             reactions = model.reactions | 
|  | 468             single = cobra.flux_analysis.single_reaction_deletion(model) | 
|  | 469             newRow = [] | 
|  | 470             df_sensitivity = pd.DataFrame(columns = [rxn.id for rxn in reactions], index = [model_name]) | 
|  | 471             for rxn in reactions: | 
|  | 472                 newRow.append(single.knockout[rxn.id].growth.values[0]/solution_original) | 
|  | 473             df_sensitivity.loc[model_name] = newRow | 
|  | 474             df_sensitivity = df_sensitivity.astype(float).round(6) | 
|  | 475     return df_pFBA, df_FVA, df_sensitivity | 
|  | 476 | 
|  | 477 ############################# main ########################################### | 
| 489 | 478 def main(args: List[str] = None) -> None: | 
| 4 | 479     """ | 
| 489 | 480     Initialize and run sampling/analysis based on the frontend input arguments. | 
| 4 | 481 | 
|  | 482     Returns: | 
|  | 483         None | 
|  | 484     """ | 
|  | 485 | 
| 489 | 486     num_processors = max(1, cpu_count() - 1) | 
| 4 | 487 | 
|  | 488     global ARGS | 
| 147 | 489     ARGS = process_args(args) | 
| 158 | 490 | 
| 159 | 491     if not os.path.exists(ARGS.output_path): | 
|  | 492         os.makedirs(ARGS.output_path) | 
| 489 | 493 | 
|  | 494     # --- Normalize inputs (the tool may pass comma-separated --input and either --name or --names) --- | 
|  | 495     ARGS.input_files = ARGS.input.split(",") if ARGS.input else [] | 
|  | 496     ARGS.file_names = ARGS.name.split(",") | 
|  | 497     # output types (required) -> list | 
|  | 498     ARGS.output_types = ARGS.output_type.split(",") if ARGS.output_type else [] | 
|  | 499     # optional analysis output types -> list or empty | 
|  | 500     ARGS.output_type_analysis = ARGS.output_type_analysis.split(",") if ARGS.output_type_analysis else [] | 
|  | 501 | 
|  | 502     # Determine if sampling should be performed | 
|  | 503     if ARGS.sampling_enabled == "true": | 
|  | 504         perform_sampling = True | 
| 4 | 505     else: | 
| 489 | 506         perform_sampling = False | 
| 334 | 507 | 
| 489 | 508     print("=== INPUT FILES ===") | 
|  | 509     print(f"{ARGS.input_files}") | 
|  | 510     print(f"{ARGS.file_names}") | 
|  | 511     print(f"{ARGS.output_type}") | 
|  | 512     print(f"{ARGS.output_types}") | 
|  | 513     print(f"{ARGS.output_type_analysis}") | 
|  | 514     print(f"Sampling enabled: {perform_sampling} (n_samples: {ARGS.n_samples})") | 
| 4 | 515 | 
| 489 | 516     if ARGS.model_and_bounds == "True": | 
|  | 517         # MODE 1: Model + bounds (separate files) | 
|  | 518         print("=== MODE 1: Model + Bounds (separate files) ===") | 
|  | 519 | 
|  | 520         # Load base model | 
|  | 521         if not ARGS.model_upload: | 
|  | 522             sys.exit("Error: model_upload is required for Mode 1") | 
| 4 | 523 | 
| 489 | 524         base_model = model_utils.build_cobra_model_from_csv(ARGS.model_upload) | 
| 4 | 525 | 
| 489 | 526         validation = model_utils.validate_model(base_model) | 
|  | 527 | 
|  | 528         print("\n=== MODEL VALIDATION ===") | 
|  | 529         for key, value in validation.items(): | 
|  | 530             print(f"{key}: {value}") | 
|  | 531 | 
|  | 532         # Set solver verbosity to 1 to see warning and error messages only. | 
|  | 533         base_model.solver.configuration.verbosity = 1 | 
| 4 | 534 | 
| 489 | 535         # Process each bounds file with the base model | 
|  | 536         results = Parallel(n_jobs=num_processors)( | 
|  | 537             delayed(model_sampler_with_bounds)(base_model, bounds_file, cell_name) | 
|  | 538             for bounds_file, cell_name in zip(ARGS.input_files, ARGS.file_names) | 
|  | 539         ) | 
| 4 | 540 | 
| 489 | 541     else: | 
|  | 542         # MODE 2: Multiple complete models | 
|  | 543         print("=== MODE 2: Multiple complete models ===") | 
|  | 544 | 
|  | 545         # Process each complete model file | 
|  | 546         results = Parallel(n_jobs=num_processors)( | 
|  | 547             delayed(perform_sampling_and_analysis)(model_utils.build_cobra_model_from_csv(model_file), cell_name) | 
|  | 548             for model_file, cell_name in zip(ARGS.input_files, ARGS.file_names) | 
|  | 549         ) | 
|  | 550 | 
|  | 551     # Handle sampling outputs (only if sampling was performed) | 
|  | 552     if perform_sampling: | 
|  | 553         print("=== PROCESSING SAMPLING RESULTS ===") | 
|  | 554 | 
|  | 555         all_mean = pd.concat([result[0] for result in results], ignore_index=False) | 
|  | 556         all_median = pd.concat([result[1] for result in results], ignore_index=False) | 
|  | 557         all_quantiles = pd.concat([result[2] for result in results], ignore_index=False) | 
| 4 | 558 | 
| 489 | 559         if "mean" in ARGS.output_types: | 
|  | 560             all_mean = all_mean.fillna(0.0) | 
|  | 561             all_mean = all_mean.sort_index() | 
|  | 562             write_to_file(all_mean.T, "mean", True) | 
|  | 563 | 
|  | 564         if "median" in ARGS.output_types: | 
|  | 565             all_median = all_median.fillna(0.0) | 
|  | 566             all_median = all_median.sort_index() | 
|  | 567             write_to_file(all_median.T, "median", True) | 
|  | 568 | 
|  | 569         if "quantiles" in ARGS.output_types: | 
|  | 570             all_quantiles = all_quantiles.fillna(0.0) | 
|  | 571             all_quantiles = all_quantiles.sort_index() | 
|  | 572             write_to_file(all_quantiles.T, "quantiles", True) | 
|  | 573     else: | 
|  | 574         print("=== SAMPLING SKIPPED (n_samples = 0 or sampling disabled) ===") | 
|  | 575 | 
|  | 576     # Handle optimization analysis outputs (always available) | 
|  | 577     print("=== PROCESSING OPTIMIZATION RESULTS ===") | 
| 4 | 578 | 
| 489 | 579     # Determine the starting index for optimization results | 
|  | 580     # If sampling was performed, optimization results start at index 3 | 
|  | 581     # If no sampling, optimization results start at index 0 | 
|  | 582     index_result = 3 if perform_sampling else 0 | 
|  | 583 | 
|  | 584     if "pFBA" in ARGS.output_type_analysis: | 
| 4 | 585         all_pFBA = pd.concat([result[index_result] for result in results], ignore_index=False) | 
|  | 586         all_pFBA = all_pFBA.sort_index() | 
|  | 587         write_to_file(all_pFBA.T, "pFBA", True) | 
| 489 | 588         index_result += 1 | 
|  | 589 | 
|  | 590     if "FVA" in ARGS.output_type_analysis: | 
|  | 591         all_FVA = pd.concat([result[index_result] for result in results], ignore_index=False) | 
| 4 | 592         all_FVA = all_FVA.sort_index() | 
|  | 593         write_to_file(all_FVA.T, "FVA", True) | 
| 489 | 594         index_result += 1 | 
|  | 595 | 
|  | 596     if "sensitivity" in ARGS.output_type_analysis: | 
| 4 | 597         all_sensitivity = pd.concat([result[index_result] for result in results], ignore_index=False) | 
|  | 598         all_sensitivity = all_sensitivity.sort_index() | 
|  | 599         write_to_file(all_sensitivity.T, "sensitivity", True) | 
|  | 600 | 
| 489 | 601     return | 
| 4 | 602 | 
|  | 603 ############################################################################## | 
|  | 604 if __name__ == "__main__": | 
|  | 605     main() |