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