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