| 456 | 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 | 
| 410 | 13 import argparse | 
|  | 14 import utils.general_utils as utils | 
| 456 | 15 from typing import List | 
| 410 | 16 import os | 
|  | 17 import pandas as pd | 
| 461 | 18 import numpy as np | 
| 410 | 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 | 
| 419 | 24 import utils.model_utils as model_utils | 
| 410 | 25 | 
|  | 26 | 
|  | 27 ################################# process args ############################### | 
| 461 | 28 def process_args(args: List[str] = None) -> argparse.Namespace: | 
| 410 | 29     """ | 
|  | 30     Processes command-line arguments. | 
| 461 | 31 | 
| 410 | 32     Args: | 
|  | 33         args (list): List of command-line arguments. | 
| 461 | 34 | 
| 410 | 35     Returns: | 
|  | 36         Namespace: An object containing parsed arguments. | 
|  | 37     """ | 
| 461 | 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") | 
| 410 | 43 | 
| 461 | 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 | 
| 469 | 49     parser.add_argument("-ens", "--sampling_enabled", type=str, | 
| 470 | 50         choices=['true', 'false'], | 
| 469 | 51         required=True, | 
| 470 | 52         help="enable sampling: 'true' for sampling, 'false' for no sampling") | 
| 469 | 53 | 
| 461 | 54     parser.add_argument('-ol', '--out_log', | 
|  | 55                         help="Output log") | 
| 410 | 56 | 
|  | 57     parser.add_argument('-td', '--tool_dir', | 
| 461 | 58                         type=str, | 
|  | 59                         required=True, | 
|  | 60                         help='your tool directory') | 
| 410 | 61 | 
|  | 62     parser.add_argument('-in', '--input', | 
| 461 | 63                         required=True, | 
|  | 64                         type=str, | 
|  | 65                         help='input bounds files or complete model files') | 
| 410 | 66 | 
| 419 | 67     parser.add_argument('-ni', '--name', | 
| 461 | 68                         required=True, | 
| 410 | 69                         type=str, | 
| 461 | 70                         help='cell names') | 
| 410 | 71 | 
|  | 72     parser.add_argument('-a', '--algorithm', | 
| 461 | 73                         type=str, | 
|  | 74                         choices=['OPTGP', 'CBS'], | 
|  | 75                         required=True, | 
|  | 76                         help='choose sampling algorithm') | 
| 410 | 77 | 
| 461 | 78     parser.add_argument('-th', '--thinning', | 
|  | 79                         type=int, | 
|  | 80                         default=100, | 
| 473 | 81                         required=True, | 
| 461 | 82                         help='choose thinning') | 
| 410 | 83 | 
| 461 | 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)') | 
| 410 | 88 | 
| 461 | 89     parser.add_argument('-sd', '--seed', | 
|  | 90                         type=int, | 
|  | 91                         required=True, | 
|  | 92                         help='seed for random number generation') | 
| 410 | 93 | 
| 461 | 94     parser.add_argument('-nb', '--n_batches', | 
|  | 95                         type=int, | 
|  | 96                         required=True, | 
|  | 97                         help='choose how many batches') | 
| 410 | 98 | 
| 430 | 99     parser.add_argument('-opt', '--perc_opt', | 
| 461 | 100                         type=float, | 
| 430 | 101                         default=0.9, | 
| 474 | 102                         required=False, | 
| 461 | 103                         help='choose the fraction of optimality for FVA (0-1)') | 
| 430 | 104 | 
| 461 | 105     parser.add_argument('-ot', '--output_type', | 
|  | 106                         type=str, | 
|  | 107                         required=True, | 
|  | 108                         help='output type for sampling results') | 
| 410 | 109 | 
| 461 | 110     parser.add_argument('-ota', '--output_type_analysis', | 
|  | 111                         type=str, | 
|  | 112                         required=False, | 
|  | 113                         help='output type analysis (optimization methods)') | 
| 410 | 114 | 
| 461 | 115     parser.add_argument('-idop', '--output_path', | 
|  | 116                         type=str, | 
| 410 | 117                         default='flux_simulation', | 
| 461 | 118                         help='output path for maps') | 
| 410 | 119 | 
|  | 120     ARGS = parser.parse_args(args) | 
|  | 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: | 
| 456 | 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     """ | 
| 410 | 150     dataset.index.name = 'Reactions' | 
|  | 151     dataset.to_csv(ARGS.output_path + "/" + name + ".csv", sep = '\t', index = keep_index) | 
|  | 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 | 
| 461 | 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: | 
| 410 | 180     """ | 
|  | 181     Samples from the OPTGP (Optimal Global Perturbation) algorithm and saves the results to CSV files. | 
| 461 | 182 | 
| 410 | 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. | 
| 461 | 190 | 
| 410 | 191     Returns: | 
|  | 192         None | 
|  | 193     """ | 
| 461 | 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): | 
| 410 | 201         optgp = OptGPSampler(model, thinning, seed) | 
|  | 202         samples = optgp.sample(n_samples) | 
| 461 | 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.values) | 
|  | 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) | 
|  | 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 | 
| 410 | 225     write_to_file(samplesTotal.T, model_name, True) | 
| 461 | 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) | 
| 410 | 232 | 
|  | 233 | 
| 461 | 234 def CBS_sampler(model: cobra.Model, model_name: str, n_samples: int = 1000, n_batches: int = 1, seed: int = 0) -> None: | 
| 410 | 235     """ | 
|  | 236     Samples using the CBS (Constraint-based Sampling) algorithm and saves the results to CSV files. | 
| 461 | 237 | 
| 410 | 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. | 
| 461 | 244 | 
| 410 | 245     Returns: | 
|  | 246         None | 
|  | 247     """ | 
| 461 | 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) | 
| 410 | 258 | 
| 461 | 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 | 
| 410 | 263         try: | 
| 461 | 264             CBS_backend.randomObjectiveFunctionSampling( | 
|  | 265                 model, | 
|  | 266                 n_samples, | 
|  | 267                 df_coefficients.iloc[:, i * n_samples:(i + 1) * n_samples], | 
|  | 268                 samples | 
|  | 269             ) | 
| 410 | 270         except Exception as e: | 
|  | 271             utils.logWarning( | 
| 461 | 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.values) | 
|  | 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) | 
|  | 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 names | 
|  | 299     samplesTotal = pd.DataFrame(samplesTotal_array, columns=reaction_ids) | 
|  | 300 | 
|  | 301     # Save the final merged result as CSV | 
| 410 | 302     write_to_file(samplesTotal.T, model_name, True) | 
| 461 | 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) | 
| 410 | 309 | 
|  | 310 | 
| 419 | 311 | 
|  | 312 def model_sampler_with_bounds(model_input_original: cobra.Model, bounds_path: str, cell_name: str) -> List[pd.DataFrame]: | 
| 410 | 313     """ | 
| 419 | 314     MODE 1: Prepares the model with bounds from separate bounds file and performs sampling. | 
| 410 | 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") | 
| 419 | 327 | 
|  | 328     # Apply bounds to model | 
| 410 | 329     for rxn_index, row in bounds_df.iterrows(): | 
| 419 | 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.") | 
| 410 | 335 | 
| 419 | 336     return perform_sampling_and_analysis(model_input, cell_name) | 
|  | 337 | 
|  | 338 | 
|  | 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. | 
|  | 342 | 
|  | 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. | 
|  | 346 | 
|  | 347     Returns: | 
|  | 348         List[pd.DataFrame]: A list of DataFrames containing statistics and analysis results. | 
|  | 349     """ | 
| 410 | 350 | 
| 473 | 351     if ARGS.sampling_enabled == "true": | 
| 469 | 352 | 
|  | 353         if ARGS.algorithm == 'OPTGP': | 
|  | 354             OPTGP_sampler(model_input, cell_name, ARGS.n_samples, ARGS.thinning, ARGS.n_batches, ARGS.seed) | 
|  | 355         elif ARGS.algorithm == 'CBS': | 
|  | 356             CBS_sampler(model_input, cell_name, ARGS.n_samples, ARGS.n_batches, ARGS.seed) | 
| 410 | 357 | 
| 469 | 358         df_mean, df_median, df_quantiles = fluxes_statistics(cell_name, ARGS.output_types) | 
| 410 | 359 | 
| 469 | 360         if("fluxes" not in ARGS.output_types): | 
|  | 361             os.remove(ARGS.output_path + "/" + cell_name + '.csv') | 
|  | 362 | 
|  | 363         returnList = [df_mean, df_median, df_quantiles] | 
| 410 | 364 | 
|  | 365     df_pFBA, df_FVA, df_sensitivity = fluxes_analysis(model_input, cell_name, ARGS.output_type_analysis) | 
|  | 366 | 
|  | 367     if("pFBA" in ARGS.output_type_analysis): | 
|  | 368         returnList.append(df_pFBA) | 
|  | 369     if("FVA" in ARGS.output_type_analysis): | 
|  | 370         returnList.append(df_FVA) | 
|  | 371     if("sensitivity" in ARGS.output_type_analysis): | 
|  | 372         returnList.append(df_sensitivity) | 
|  | 373 | 
|  | 374     return returnList | 
|  | 375 | 
|  | 376 def fluxes_statistics(model_name: str,  output_types:List)-> List[pd.DataFrame]: | 
|  | 377     """ | 
|  | 378     Computes statistics (mean, median, quantiles) for the fluxes. | 
|  | 379 | 
|  | 380     Args: | 
|  | 381         model_name (str): Name of the model, used in filename for input. | 
|  | 382         output_types (List[str]): Types of statistics to compute (mean, median, quantiles). | 
|  | 383 | 
|  | 384     Returns: | 
|  | 385         List[pd.DataFrame]: List of DataFrames containing mean, median, and quantiles statistics. | 
|  | 386     """ | 
|  | 387 | 
|  | 388     df_mean = pd.DataFrame() | 
|  | 389     df_median= pd.DataFrame() | 
|  | 390     df_quantiles= pd.DataFrame() | 
|  | 391 | 
|  | 392     df_samples = pd.read_csv(ARGS.output_path + "/"  +  model_name + '.csv', sep = '\t', index_col = 0).T | 
|  | 393     df_samples = df_samples.round(8) | 
|  | 394 | 
|  | 395     for output_type in output_types: | 
|  | 396         if(output_type == "mean"): | 
|  | 397             df_mean = df_samples.mean() | 
|  | 398             df_mean = df_mean.to_frame().T | 
|  | 399             df_mean = df_mean.reset_index(drop=True) | 
|  | 400             df_mean.index = [model_name] | 
|  | 401         elif(output_type == "median"): | 
|  | 402             df_median = df_samples.median() | 
|  | 403             df_median = df_median.to_frame().T | 
|  | 404             df_median = df_median.reset_index(drop=True) | 
|  | 405             df_median.index = [model_name] | 
|  | 406         elif(output_type == "quantiles"): | 
|  | 407             newRow = [] | 
|  | 408             cols = [] | 
|  | 409             for rxn in df_samples.columns: | 
|  | 410                 quantiles = df_samples[rxn].quantile([0.25, 0.50, 0.75]) | 
|  | 411                 newRow.append(quantiles[0.25]) | 
|  | 412                 cols.append(rxn + "_q1") | 
|  | 413                 newRow.append(quantiles[0.5]) | 
|  | 414                 cols.append(rxn + "_q2") | 
|  | 415                 newRow.append(quantiles[0.75]) | 
|  | 416                 cols.append(rxn + "_q3") | 
|  | 417             df_quantiles = pd.DataFrame(columns=cols) | 
|  | 418             df_quantiles.loc[0] = newRow | 
|  | 419             df_quantiles = df_quantiles.reset_index(drop=True) | 
|  | 420             df_quantiles.index = [model_name] | 
|  | 421 | 
|  | 422     return df_mean, df_median, df_quantiles | 
|  | 423 | 
|  | 424 def fluxes_analysis(model:cobra.Model,  model_name:str, output_types:List)-> List[pd.DataFrame]: | 
|  | 425     """ | 
|  | 426     Performs flux analysis including pFBA, FVA, and sensitivity analysis. | 
|  | 427 | 
|  | 428     Args: | 
|  | 429         model (cobra.Model): The COBRA model to analyze. | 
|  | 430         model_name (str): Name of the model, used in filenames for output. | 
|  | 431         output_types (List[str]): Types of analysis to perform (pFBA, FVA, sensitivity). | 
|  | 432 | 
|  | 433     Returns: | 
|  | 434         List[pd.DataFrame]: List of DataFrames containing pFBA, FVA, and sensitivity analysis results. | 
|  | 435     """ | 
|  | 436 | 
|  | 437     df_pFBA = pd.DataFrame() | 
|  | 438     df_FVA= pd.DataFrame() | 
|  | 439     df_sensitivity= pd.DataFrame() | 
|  | 440 | 
|  | 441     for output_type in output_types: | 
|  | 442         if(output_type == "pFBA"): | 
|  | 443             model.objective = "Biomass" | 
|  | 444             solution = cobra.flux_analysis.pfba(model) | 
|  | 445             fluxes = solution.fluxes | 
| 419 | 446             df_pFBA.loc[0,[rxn.id for rxn in model.reactions]] = fluxes.tolist() | 
| 410 | 447             df_pFBA = df_pFBA.reset_index(drop=True) | 
|  | 448             df_pFBA.index = [model_name] | 
|  | 449             df_pFBA = df_pFBA.astype(float).round(6) | 
|  | 450         elif(output_type == "FVA"): | 
| 430 | 451             fva = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=ARGS.perc_opt, processes=1).round(8) | 
| 410 | 452             columns = [] | 
|  | 453             for rxn in fva.index.to_list(): | 
|  | 454                 columns.append(rxn + "_min") | 
|  | 455                 columns.append(rxn + "_max") | 
|  | 456             df_FVA= pd.DataFrame(columns = columns) | 
|  | 457             for index_rxn, row in fva.iterrows(): | 
|  | 458                 df_FVA.loc[0, index_rxn+ "_min"] = fva.loc[index_rxn, "minimum"] | 
|  | 459                 df_FVA.loc[0, index_rxn+ "_max"] = fva.loc[index_rxn, "maximum"] | 
|  | 460             df_FVA = df_FVA.reset_index(drop=True) | 
|  | 461             df_FVA.index = [model_name] | 
|  | 462             df_FVA = df_FVA.astype(float).round(6) | 
|  | 463         elif(output_type == "sensitivity"): | 
|  | 464             model.objective = "Biomass" | 
|  | 465             solution_original = model.optimize().objective_value | 
|  | 466             reactions = model.reactions | 
|  | 467             single = cobra.flux_analysis.single_reaction_deletion(model) | 
|  | 468             newRow = [] | 
|  | 469             df_sensitivity = pd.DataFrame(columns = [rxn.id for rxn in reactions], index = [model_name]) | 
|  | 470             for rxn in reactions: | 
|  | 471                 newRow.append(single.knockout[rxn.id].growth.values[0]/solution_original) | 
|  | 472             df_sensitivity.loc[model_name] = newRow | 
|  | 473             df_sensitivity = df_sensitivity.astype(float).round(6) | 
|  | 474     return df_pFBA, df_FVA, df_sensitivity | 
|  | 475 | 
|  | 476 ############################# main ########################################### | 
| 461 | 477 def main(args: List[str] = None) -> None: | 
| 410 | 478     """ | 
| 456 | 479     Initialize and run sampling/analysis based on the frontend input arguments. | 
| 410 | 480 | 
|  | 481     Returns: | 
|  | 482         None | 
|  | 483     """ | 
|  | 484 | 
| 419 | 485     num_processors = max(1, cpu_count() - 1) | 
| 410 | 486 | 
|  | 487     global ARGS | 
|  | 488     ARGS = process_args(args) | 
|  | 489 | 
|  | 490     if not os.path.exists(ARGS.output_path): | 
|  | 491         os.makedirs(ARGS.output_path) | 
| 419 | 492 | 
|  | 493     # --- Normalize inputs (the tool may pass comma-separated --input and either --name or --names) --- | 
| 421 | 494     ARGS.input_files = ARGS.input.split(",") if ARGS.input else [] | 
| 419 | 495     ARGS.file_names = ARGS.name.split(",") | 
|  | 496     # output types (required) -> list | 
| 421 | 497     ARGS.output_types = ARGS.output_type.split(",") if ARGS.output_type else [] | 
| 419 | 498     # optional analysis output types -> list or empty | 
| 421 | 499     ARGS.output_type_analysis = ARGS.output_type_analysis.split(",") if ARGS.output_type_analysis else [] | 
| 419 | 500 | 
| 461 | 501     # Determine if sampling should be performed | 
| 473 | 502     if ARGS.sampling_enabled == "true": | 
| 469 | 503         perform_sampling = True | 
| 461 | 504 | 
| 421 | 505     print("=== INPUT FILES ===") | 
| 422 | 506     print(f"{ARGS.input_files}") | 
|  | 507     print(f"{ARGS.file_names}") | 
|  | 508     print(f"{ARGS.output_type}") | 
|  | 509     print(f"{ARGS.output_types}") | 
|  | 510     print(f"{ARGS.output_type_analysis}") | 
| 461 | 511     print(f"Sampling enabled: {perform_sampling} (n_samples: {ARGS.n_samples})") | 
| 410 | 512 | 
| 419 | 513     if ARGS.model_and_bounds == "True": | 
|  | 514         # MODE 1: Model + bounds (separate files) | 
|  | 515         print("=== MODE 1: Model + Bounds (separate files) ===") | 
|  | 516 | 
|  | 517         # Load base model | 
|  | 518         if not ARGS.model_upload: | 
|  | 519             sys.exit("Error: model_upload is required for Mode 1") | 
| 410 | 520 | 
| 419 | 521         base_model = model_utils.build_cobra_model_from_csv(ARGS.model_upload) | 
| 410 | 522 | 
| 419 | 523         validation = model_utils.validate_model(base_model) | 
|  | 524 | 
| 456 | 525         print("\n=== MODEL VALIDATION ===") | 
| 419 | 526         for key, value in validation.items(): | 
|  | 527             print(f"{key}: {value}") | 
|  | 528 | 
| 456 | 529         # Set solver verbosity to 1 to see warning and error messages only. | 
| 419 | 530         base_model.solver.configuration.verbosity = 1 | 
| 410 | 531 | 
| 456 | 532         # Process each bounds file with the base model | 
| 419 | 533         results = Parallel(n_jobs=num_processors)( | 
|  | 534             delayed(model_sampler_with_bounds)(base_model, bounds_file, cell_name) | 
|  | 535             for bounds_file, cell_name in zip(ARGS.input_files, ARGS.file_names) | 
|  | 536         ) | 
| 410 | 537 | 
| 419 | 538     else: | 
|  | 539         # MODE 2: Multiple complete models | 
|  | 540         print("=== MODE 2: Multiple complete models ===") | 
|  | 541 | 
|  | 542         # Process each complete model file | 
|  | 543         results = Parallel(n_jobs=num_processors)( | 
|  | 544             delayed(perform_sampling_and_analysis)(model_utils.build_cobra_model_from_csv(model_file), cell_name) | 
|  | 545             for model_file, cell_name in zip(ARGS.input_files, ARGS.file_names) | 
|  | 546         ) | 
| 410 | 547 | 
| 461 | 548     # Handle sampling outputs (only if sampling was performed) | 
|  | 549     if perform_sampling: | 
|  | 550         print("=== PROCESSING SAMPLING RESULTS ===") | 
|  | 551 | 
|  | 552         all_mean = pd.concat([result[0] for result in results], ignore_index=False) | 
|  | 553         all_median = pd.concat([result[1] for result in results], ignore_index=False) | 
|  | 554         all_quantiles = pd.concat([result[2] for result in results], ignore_index=False) | 
| 410 | 555 | 
| 461 | 556         if "mean" in ARGS.output_types: | 
|  | 557             all_mean = all_mean.fillna(0.0) | 
|  | 558             all_mean = all_mean.sort_index() | 
|  | 559             write_to_file(all_mean.T, "mean", True) | 
| 410 | 560 | 
| 461 | 561         if "median" in ARGS.output_types: | 
|  | 562             all_median = all_median.fillna(0.0) | 
|  | 563             all_median = all_median.sort_index() | 
|  | 564             write_to_file(all_median.T, "median", True) | 
|  | 565 | 
|  | 566         if "quantiles" in ARGS.output_types: | 
|  | 567             all_quantiles = all_quantiles.fillna(0.0) | 
|  | 568             all_quantiles = all_quantiles.sort_index() | 
|  | 569             write_to_file(all_quantiles.T, "quantiles", True) | 
|  | 570     else: | 
| 469 | 571         print("=== SAMPLING SKIPPED (n_samples = 0 or sampling disabled) ===") | 
| 461 | 572 | 
|  | 573     # Handle optimization analysis outputs (always available) | 
|  | 574     print("=== PROCESSING OPTIMIZATION RESULTS ===") | 
| 410 | 575 | 
| 461 | 576     # Determine the starting index for optimization results | 
|  | 577     # If sampling was performed, optimization results start at index 3 | 
|  | 578     # If no sampling, optimization results start at index 0 | 
|  | 579     index_result = 3 if perform_sampling else 0 | 
|  | 580 | 
|  | 581     if "pFBA" in ARGS.output_type_analysis: | 
| 410 | 582         all_pFBA = pd.concat([result[index_result] for result in results], ignore_index=False) | 
|  | 583         all_pFBA = all_pFBA.sort_index() | 
|  | 584         write_to_file(all_pFBA.T, "pFBA", True) | 
| 461 | 585         index_result += 1 | 
|  | 586 | 
|  | 587     if "FVA" in ARGS.output_type_analysis: | 
|  | 588         all_FVA = pd.concat([result[index_result] for result in results], ignore_index=False) | 
| 410 | 589         all_FVA = all_FVA.sort_index() | 
|  | 590         write_to_file(all_FVA.T, "FVA", True) | 
| 461 | 591         index_result += 1 | 
|  | 592 | 
|  | 593     if "sensitivity" in ARGS.output_type_analysis: | 
| 410 | 594         all_sensitivity = pd.concat([result[index_result] for result in results], ignore_index=False) | 
|  | 595         all_sensitivity = all_sensitivity.sort_index() | 
|  | 596         write_to_file(all_sensitivity.T, "sensitivity", True) | 
|  | 597 | 
| 456 | 598     return | 
| 410 | 599 | 
|  | 600 ############################################################################## | 
|  | 601 if __name__ == "__main__": | 
|  | 602     main() |