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