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