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"
|
479
|
206 np.save(batch_filename, samples.to_numpy())
|
461
|
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"
|
480
|
215 batch_data = np.load(batch_filename, allow_pickle=True)
|
461
|
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)
|
479
|
285 np.save(batch_filename, samples.to_numpy())
|
461
|
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"
|
480
|
292 batch_data = np.load(batch_filename, allow_pickle=True)
|
461
|
293 all_samples.append(batch_data)
|
|
294
|
|
295 # Concatenate all batches
|
|
296 samplesTotal_array = np.vstack(all_samples)
|
|
297
|
480
|
298 # Convert back to DataFrame with proper column namesq
|
461
|
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
|
477
|
351 returnList = []
|
|
352
|
473
|
353 if ARGS.sampling_enabled == "true":
|
469
|
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)
|
410
|
359
|
469
|
360 df_mean, df_median, df_quantiles = fluxes_statistics(cell_name, ARGS.output_types)
|
410
|
361
|
469
|
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]
|
410
|
366
|
|
367 df_pFBA, df_FVA, df_sensitivity = fluxes_analysis(model_input, cell_name, ARGS.output_type_analysis)
|
|
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
|
|
394 df_samples = pd.read_csv(ARGS.output_path + "/" + model_name + '.csv', sep = '\t', index_col = 0).T
|
|
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 """
|
|
428 Performs flux analysis including pFBA, FVA, and sensitivity analysis.
|
|
429
|
|
430 Args:
|
|
431 model (cobra.Model): The COBRA model to analyze.
|
|
432 model_name (str): Name of the model, used in filenames for output.
|
|
433 output_types (List[str]): Types of analysis to perform (pFBA, FVA, sensitivity).
|
|
434
|
|
435 Returns:
|
|
436 List[pd.DataFrame]: List of DataFrames containing pFBA, FVA, and sensitivity analysis results.
|
|
437 """
|
|
438
|
|
439 df_pFBA = pd.DataFrame()
|
|
440 df_FVA= pd.DataFrame()
|
|
441 df_sensitivity= pd.DataFrame()
|
|
442
|
|
443 for output_type in output_types:
|
|
444 if(output_type == "pFBA"):
|
|
445 model.objective = "Biomass"
|
|
446 solution = cobra.flux_analysis.pfba(model)
|
|
447 fluxes = solution.fluxes
|
419
|
448 df_pFBA.loc[0,[rxn.id for rxn in model.reactions]] = fluxes.tolist()
|
410
|
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"):
|
430
|
453 fva = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=ARGS.perc_opt, processes=1).round(8)
|
410
|
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 model.objective = "Biomass"
|
|
467 solution_original = model.optimize().objective_value
|
|
468 reactions = model.reactions
|
|
469 single = cobra.flux_analysis.single_reaction_deletion(model)
|
|
470 newRow = []
|
|
471 df_sensitivity = pd.DataFrame(columns = [rxn.id for rxn in reactions], index = [model_name])
|
|
472 for rxn in reactions:
|
|
473 newRow.append(single.knockout[rxn.id].growth.values[0]/solution_original)
|
|
474 df_sensitivity.loc[model_name] = newRow
|
|
475 df_sensitivity = df_sensitivity.astype(float).round(6)
|
|
476 return df_pFBA, df_FVA, df_sensitivity
|
|
477
|
|
478 ############################# main ###########################################
|
461
|
479 def main(args: List[str] = None) -> None:
|
410
|
480 """
|
456
|
481 Initialize and run sampling/analysis based on the frontend input arguments.
|
410
|
482
|
|
483 Returns:
|
|
484 None
|
|
485 """
|
|
486
|
419
|
487 num_processors = max(1, cpu_count() - 1)
|
410
|
488
|
|
489 global ARGS
|
|
490 ARGS = process_args(args)
|
|
491
|
|
492 if not os.path.exists(ARGS.output_path):
|
|
493 os.makedirs(ARGS.output_path)
|
419
|
494
|
|
495 # --- Normalize inputs (the tool may pass comma-separated --input and either --name or --names) ---
|
421
|
496 ARGS.input_files = ARGS.input.split(",") if ARGS.input else []
|
419
|
497 ARGS.file_names = ARGS.name.split(",")
|
|
498 # output types (required) -> list
|
421
|
499 ARGS.output_types = ARGS.output_type.split(",") if ARGS.output_type else []
|
419
|
500 # optional analysis output types -> list or empty
|
421
|
501 ARGS.output_type_analysis = ARGS.output_type_analysis.split(",") if ARGS.output_type_analysis else []
|
419
|
502
|
461
|
503 # Determine if sampling should be performed
|
473
|
504 if ARGS.sampling_enabled == "true":
|
469
|
505 perform_sampling = True
|
475
|
506 else:
|
|
507 perform_sampling = False
|
461
|
508
|
421
|
509 print("=== INPUT FILES ===")
|
422
|
510 print(f"{ARGS.input_files}")
|
|
511 print(f"{ARGS.file_names}")
|
|
512 print(f"{ARGS.output_type}")
|
|
513 print(f"{ARGS.output_types}")
|
|
514 print(f"{ARGS.output_type_analysis}")
|
461
|
515 print(f"Sampling enabled: {perform_sampling} (n_samples: {ARGS.n_samples})")
|
410
|
516
|
419
|
517 if ARGS.model_and_bounds == "True":
|
|
518 # MODE 1: Model + bounds (separate files)
|
|
519 print("=== MODE 1: Model + Bounds (separate files) ===")
|
|
520
|
|
521 # Load base model
|
|
522 if not ARGS.model_upload:
|
|
523 sys.exit("Error: model_upload is required for Mode 1")
|
410
|
524
|
419
|
525 base_model = model_utils.build_cobra_model_from_csv(ARGS.model_upload)
|
410
|
526
|
419
|
527 validation = model_utils.validate_model(base_model)
|
|
528
|
456
|
529 print("\n=== MODEL VALIDATION ===")
|
419
|
530 for key, value in validation.items():
|
|
531 print(f"{key}: {value}")
|
|
532
|
456
|
533 # Set solver verbosity to 1 to see warning and error messages only.
|
419
|
534 base_model.solver.configuration.verbosity = 1
|
410
|
535
|
456
|
536 # Process each bounds file with the base model
|
419
|
537 results = Parallel(n_jobs=num_processors)(
|
|
538 delayed(model_sampler_with_bounds)(base_model, bounds_file, cell_name)
|
|
539 for bounds_file, cell_name in zip(ARGS.input_files, ARGS.file_names)
|
|
540 )
|
410
|
541
|
419
|
542 else:
|
|
543 # MODE 2: Multiple complete models
|
|
544 print("=== MODE 2: Multiple complete models ===")
|
|
545
|
|
546 # Process each complete model file
|
|
547 results = Parallel(n_jobs=num_processors)(
|
|
548 delayed(perform_sampling_and_analysis)(model_utils.build_cobra_model_from_csv(model_file), cell_name)
|
|
549 for model_file, cell_name in zip(ARGS.input_files, ARGS.file_names)
|
|
550 )
|
410
|
551
|
461
|
552 # Handle sampling outputs (only if sampling was performed)
|
|
553 if perform_sampling:
|
|
554 print("=== PROCESSING SAMPLING RESULTS ===")
|
|
555
|
|
556 all_mean = pd.concat([result[0] for result in results], ignore_index=False)
|
|
557 all_median = pd.concat([result[1] for result in results], ignore_index=False)
|
|
558 all_quantiles = pd.concat([result[2] for result in results], ignore_index=False)
|
410
|
559
|
461
|
560 if "mean" in ARGS.output_types:
|
|
561 all_mean = all_mean.fillna(0.0)
|
|
562 all_mean = all_mean.sort_index()
|
|
563 write_to_file(all_mean.T, "mean", True)
|
410
|
564
|
461
|
565 if "median" in ARGS.output_types:
|
|
566 all_median = all_median.fillna(0.0)
|
|
567 all_median = all_median.sort_index()
|
|
568 write_to_file(all_median.T, "median", True)
|
|
569
|
|
570 if "quantiles" in ARGS.output_types:
|
|
571 all_quantiles = all_quantiles.fillna(0.0)
|
|
572 all_quantiles = all_quantiles.sort_index()
|
|
573 write_to_file(all_quantiles.T, "quantiles", True)
|
|
574 else:
|
469
|
575 print("=== SAMPLING SKIPPED (n_samples = 0 or sampling disabled) ===")
|
461
|
576
|
|
577 # Handle optimization analysis outputs (always available)
|
|
578 print("=== PROCESSING OPTIMIZATION RESULTS ===")
|
410
|
579
|
461
|
580 # Determine the starting index for optimization results
|
|
581 # If sampling was performed, optimization results start at index 3
|
|
582 # If no sampling, optimization results start at index 0
|
|
583 index_result = 3 if perform_sampling else 0
|
|
584
|
|
585 if "pFBA" in ARGS.output_type_analysis:
|
410
|
586 all_pFBA = pd.concat([result[index_result] for result in results], ignore_index=False)
|
|
587 all_pFBA = all_pFBA.sort_index()
|
|
588 write_to_file(all_pFBA.T, "pFBA", True)
|
461
|
589 index_result += 1
|
|
590
|
|
591 if "FVA" in ARGS.output_type_analysis:
|
|
592 all_FVA = pd.concat([result[index_result] for result in results], ignore_index=False)
|
410
|
593 all_FVA = all_FVA.sort_index()
|
|
594 write_to_file(all_FVA.T, "FVA", True)
|
461
|
595 index_result += 1
|
|
596
|
|
597 if "sensitivity" in ARGS.output_type_analysis:
|
410
|
598 all_sensitivity = pd.concat([result[index_result] for result in results], ignore_index=False)
|
|
599 all_sensitivity = all_sensitivity.sort_index()
|
|
600 write_to_file(all_sensitivity.T, "sensitivity", True)
|
|
601
|
456
|
602 return
|
410
|
603
|
|
604 ##############################################################################
|
|
605 if __name__ == "__main__":
|
|
606 main() |