456
|
1 """
|
|
2 Apply RAS-based scaling to reaction bounds and optionally save updated models.
|
|
3
|
|
4 Workflow:
|
|
5 - Read one or more RAS matrices (patients/samples x reactions)
|
|
6 - Normalize and merge them, optionally adding class suffixes to sample IDs
|
|
7 - Build a COBRA model from a tabular CSV
|
|
8 - Run FVA to initialize bounds, then scale per-sample based on RAS values
|
|
9 - Save bounds per sample and optionally export updated models in chosen formats
|
|
10 """
|
406
|
11 import argparse
|
|
12 import utils.general_utils as utils
|
416
|
13 from typing import Optional, Dict, Set, List, Tuple, Union
|
406
|
14 import os
|
|
15 import numpy as np
|
|
16 import pandas as pd
|
|
17 import cobra
|
456
|
18 from cobra import Model
|
406
|
19 import sys
|
|
20 from joblib import Parallel, delayed, cpu_count
|
418
|
21 import utils.model_utils as modelUtils
|
406
|
22
|
|
23 ################################# process args ###############################
|
|
24 def process_args(args :List[str] = None) -> argparse.Namespace:
|
|
25 """
|
|
26 Processes command-line arguments.
|
|
27
|
|
28 Args:
|
|
29 args (list): List of command-line arguments.
|
|
30
|
|
31 Returns:
|
|
32 Namespace: An object containing parsed arguments.
|
|
33 """
|
|
34 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
|
|
35 description = 'process some value\'s')
|
|
36
|
|
37
|
407
|
38 parser.add_argument("-mo", "--model_upload", type = str,
|
406
|
39 help = "path to input file with custom rules, if provided")
|
|
40
|
|
41 parser.add_argument('-ol', '--out_log',
|
|
42 help = "Output log")
|
|
43
|
|
44 parser.add_argument('-td', '--tool_dir',
|
|
45 type = str,
|
|
46 required = True,
|
|
47 help = 'your tool directory')
|
|
48
|
|
49 parser.add_argument('-ir', '--input_ras',
|
|
50 type=str,
|
|
51 required = False,
|
|
52 help = 'input ras')
|
|
53
|
|
54 parser.add_argument('-rn', '--name',
|
|
55 type=str,
|
|
56 help = 'ras class names')
|
|
57
|
|
58 parser.add_argument('-cc', '--cell_class',
|
|
59 type = str,
|
|
60 help = 'output of cell class')
|
|
61 parser.add_argument(
|
|
62 '-idop', '--output_path',
|
|
63 type = str,
|
|
64 default='ras_to_bounds/',
|
|
65 help = 'output path for maps')
|
|
66
|
411
|
67 parser.add_argument('-sm', '--save_models',
|
|
68 type=utils.Bool("save_models"),
|
|
69 default=False,
|
|
70 help = 'whether to save models with applied bounds')
|
|
71
|
|
72 parser.add_argument('-smp', '--save_models_path',
|
|
73 type = str,
|
|
74 default='saved_models/',
|
|
75 help = 'output path for saved models')
|
|
76
|
|
77 parser.add_argument('-smf', '--save_models_format',
|
|
78 type = str,
|
|
79 default='csv',
|
|
80 help = 'format for saved models (csv, xml, json, mat, yaml, tabular)')
|
|
81
|
406
|
82
|
|
83 ARGS = parser.parse_args(args)
|
|
84 return ARGS
|
|
85
|
|
86 ########################### warning ###########################################
|
|
87 def warning(s :str) -> None:
|
|
88 """
|
|
89 Log a warning message to an output log file and print it to the console.
|
|
90
|
|
91 Args:
|
|
92 s (str): The warning message to be logged and printed.
|
|
93
|
|
94 Returns:
|
|
95 None
|
|
96 """
|
411
|
97 if ARGS.out_log:
|
|
98 with open(ARGS.out_log, 'a') as log:
|
|
99 log.write(s + "\n\n")
|
406
|
100 print(s)
|
|
101
|
|
102 ############################ dataset input ####################################
|
|
103 def read_dataset(data :str, name :str) -> pd.DataFrame:
|
|
104 """
|
|
105 Read a dataset from a CSV file and return it as a pandas DataFrame.
|
|
106
|
|
107 Args:
|
|
108 data (str): Path to the CSV file containing the dataset.
|
|
109 name (str): Name of the dataset, used in error messages.
|
|
110
|
|
111 Returns:
|
|
112 pandas.DataFrame: DataFrame containing the dataset.
|
|
113
|
|
114 Raises:
|
|
115 pd.errors.EmptyDataError: If the CSV file is empty.
|
|
116 sys.exit: If the CSV file has the wrong format, the execution is aborted.
|
|
117 """
|
|
118 try:
|
|
119 dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python')
|
|
120 except pd.errors.EmptyDataError:
|
|
121 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
122 if len(dataset.columns) < 2:
|
|
123 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
124 return dataset
|
|
125
|
|
126
|
|
127 def apply_ras_bounds(bounds, ras_row):
|
|
128 """
|
|
129 Adjust the bounds of reactions in the model based on RAS values.
|
|
130
|
|
131 Args:
|
|
132 bounds (pd.DataFrame): Model bounds.
|
|
133 ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
|
|
134 Returns:
|
|
135 new_bounds (pd.DataFrame): integrated bounds.
|
|
136 """
|
|
137 new_bounds = bounds.copy()
|
|
138 for reaction in ras_row.index:
|
|
139 scaling_factor = ras_row[reaction]
|
|
140 if not np.isnan(scaling_factor):
|
|
141 lower_bound=bounds.loc[reaction, "lower_bound"]
|
|
142 upper_bound=bounds.loc[reaction, "upper_bound"]
|
|
143 valMax=float((upper_bound)*scaling_factor)
|
|
144 valMin=float((lower_bound)*scaling_factor)
|
|
145 if upper_bound!=0 and lower_bound==0:
|
|
146 new_bounds.loc[reaction, "upper_bound"] = valMax
|
|
147 if upper_bound==0 and lower_bound!=0:
|
|
148 new_bounds.loc[reaction, "lower_bound"] = valMin
|
|
149 if upper_bound!=0 and lower_bound!=0:
|
|
150 new_bounds.loc[reaction, "lower_bound"] = valMin
|
|
151 new_bounds.loc[reaction, "upper_bound"] = valMax
|
|
152 return new_bounds
|
|
153
|
414
|
154
|
411
|
155 def save_model(model, filename, output_folder, file_format='csv'):
|
|
156 """
|
|
157 Save a COBRA model to file in the specified format.
|
|
158
|
|
159 Args:
|
|
160 model (cobra.Model): The model to save.
|
|
161 filename (str): Base filename (without extension).
|
|
162 output_folder (str): Output directory.
|
|
163 file_format (str): File format ('xml', 'json', 'mat', 'yaml', 'tabular', 'csv').
|
|
164
|
|
165 Returns:
|
|
166 None
|
|
167 """
|
|
168 if not os.path.exists(output_folder):
|
|
169 os.makedirs(output_folder)
|
|
170
|
|
171 try:
|
|
172 if file_format == 'tabular' or file_format == 'csv':
|
|
173 # Special handling for tabular format using utils functions
|
|
174 filepath = os.path.join(output_folder, f"{filename}.csv")
|
|
175
|
418
|
176 rules = modelUtils.generate_rules(model, asParsed = False)
|
|
177 reactions = modelUtils.generate_reactions(model, asParsed = False)
|
|
178 bounds = modelUtils.generate_bounds(model)
|
|
179 medium = modelUtils.get_medium(model)
|
411
|
180
|
|
181 try:
|
418
|
182 compartments = modelUtils.generate_compartments(model)
|
411
|
183 except:
|
|
184 compartments = None
|
|
185
|
|
186 df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"])
|
|
187 df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"])
|
|
188 df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
|
|
189 df_medium = medium.rename(columns = {"reaction": "ReactionID"})
|
456
|
190 df_medium["InMedium"] = True
|
411
|
191
|
|
192 merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
|
|
193 merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
|
|
194
|
|
195 # Add compartments only if they exist and model name is ENGRO2
|
|
196 if compartments is not None and hasattr(ARGS, 'name') and ARGS.name == "ENGRO2":
|
|
197 merged = merged.merge(compartments, on = "ReactionID", how = "outer")
|
|
198
|
|
199 merged = merged.merge(df_medium, on = "ReactionID", how = "left")
|
|
200 merged["InMedium"] = merged["InMedium"].fillna(False)
|
|
201 merged = merged.sort_values(by = "InMedium", ascending = False)
|
|
202
|
|
203 merged.to_csv(filepath, sep="\t", index=False)
|
|
204
|
|
205 else:
|
|
206 # Standard COBRA formats
|
|
207 filepath = os.path.join(output_folder, f"{filename}.{file_format}")
|
|
208
|
|
209 if file_format == 'xml':
|
|
210 cobra.io.write_sbml_model(model, filepath)
|
|
211 elif file_format == 'json':
|
|
212 cobra.io.save_json_model(model, filepath)
|
|
213 elif file_format == 'mat':
|
|
214 cobra.io.save_matlab_model(model, filepath)
|
|
215 elif file_format == 'yaml':
|
|
216 cobra.io.save_yaml_model(model, filepath)
|
|
217 else:
|
|
218 raise ValueError(f"Unsupported format: {file_format}")
|
|
219
|
|
220 print(f"Model saved: {filepath}")
|
|
221
|
|
222 except Exception as e:
|
|
223 warning(f"Error saving model {filename}: {str(e)}")
|
|
224
|
|
225 def apply_bounds_to_model(model, bounds):
|
|
226 """
|
|
227 Apply bounds from a DataFrame to a COBRA model.
|
|
228
|
|
229 Args:
|
|
230 model (cobra.Model): The metabolic model to modify.
|
|
231 bounds (pd.DataFrame): DataFrame with reaction bounds.
|
|
232
|
|
233 Returns:
|
|
234 cobra.Model: Modified model with new bounds.
|
|
235 """
|
|
236 model_copy = model.copy()
|
|
237 for reaction_id in bounds.index:
|
|
238 try:
|
|
239 reaction = model_copy.reactions.get_by_id(reaction_id)
|
|
240 reaction.lower_bound = bounds.loc[reaction_id, "lower_bound"]
|
|
241 reaction.upper_bound = bounds.loc[reaction_id, "upper_bound"]
|
|
242 except KeyError:
|
|
243 # Reaction not found in model, skip
|
|
244 continue
|
|
245 return model_copy
|
|
246
|
|
247 def process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder, save_models=False, save_models_path='saved_models/', save_models_format='csv'):
|
406
|
248 """
|
|
249 Process a single RAS cell, apply bounds, and save the bounds to a CSV file.
|
|
250
|
|
251 Args:
|
|
252 cellName (str): The name of the RAS cell (used for naming the output file).
|
|
253 ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
|
|
254 model (cobra.Model): The metabolic model to be modified.
|
|
255 rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
|
|
256 output_folder (str): Folder path where the output CSV file will be saved.
|
411
|
257 save_models (bool): Whether to save models with applied bounds.
|
|
258 save_models_path (str): Path where to save models.
|
|
259 save_models_format (str): Format for saved models.
|
406
|
260
|
|
261 Returns:
|
|
262 None
|
|
263 """
|
|
264 bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
|
|
265 new_bounds = apply_ras_bounds(bounds, ras_row)
|
|
266 new_bounds.to_csv(output_folder + cellName + ".csv", sep='\t', index=True)
|
411
|
267
|
|
268 # Save model if requested
|
|
269 if save_models:
|
|
270 modified_model = apply_bounds_to_model(model, new_bounds)
|
|
271 save_model(modified_model, cellName, save_models_path, save_models_format)
|
|
272
|
456
|
273 return
|
406
|
274
|
414
|
275 def generate_bounds_model(model: cobra.Model, ras=None, output_folder='output/', save_models=False, save_models_path='saved_models/', save_models_format='csv') -> pd.DataFrame:
|
406
|
276 """
|
|
277 Generate reaction bounds for a metabolic model based on medium conditions and optional RAS adjustments.
|
|
278
|
|
279 Args:
|
|
280 model (cobra.Model): The metabolic model for which bounds will be generated.
|
|
281 ras (pd.DataFrame, optional): RAS pandas dataframe. Defaults to None.
|
|
282 output_folder (str, optional): Folder path where output CSV files will be saved. Defaults to 'output/'.
|
411
|
283 save_models (bool): Whether to save models with applied bounds.
|
|
284 save_models_path (str): Path where to save models.
|
|
285 save_models_format (str): Format for saved models.
|
406
|
286
|
|
287 Returns:
|
|
288 pd.DataFrame: DataFrame containing the bounds of reactions in the model.
|
|
289 """
|
407
|
290 rxns_ids = [rxn.id for rxn in model.reactions]
|
406
|
291
|
|
292 # Perform Flux Variability Analysis (FVA) on this medium
|
|
293 df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
|
|
294
|
|
295 # Set FVA bounds
|
|
296 for reaction in rxns_ids:
|
|
297 model.reactions.get_by_id(reaction).lower_bound = float(df_FVA.loc[reaction, "minimum"])
|
|
298 model.reactions.get_by_id(reaction).upper_bound = float(df_FVA.loc[reaction, "maximum"])
|
|
299
|
|
300 if ras is not None:
|
411
|
301 Parallel(n_jobs=cpu_count())(delayed(process_ras_cell)(
|
|
302 cellName, ras_row, model, rxns_ids, output_folder,
|
|
303 save_models, save_models_path, save_models_format
|
|
304 ) for cellName, ras_row in ras.iterrows())
|
406
|
305 else:
|
428
|
306 raise ValueError("RAS DataFrame is None. Cannot generate bounds without RAS data.")
|
456
|
307 return
|
406
|
308
|
|
309 ############################# main ###########################################
|
|
310 def main(args:List[str] = None) -> None:
|
|
311 """
|
456
|
312 Initialize and execute RAS-to-bounds pipeline based on the frontend input arguments.
|
406
|
313
|
|
314 Returns:
|
|
315 None
|
|
316 """
|
|
317 if not os.path.exists('ras_to_bounds'):
|
|
318 os.makedirs('ras_to_bounds')
|
|
319
|
|
320 global ARGS
|
|
321 ARGS = process_args(args)
|
|
322
|
428
|
323
|
|
324 ras_file_list = ARGS.input_ras.split(",")
|
|
325 ras_file_names = ARGS.name.split(",")
|
|
326 if len(ras_file_names) != len(set(ras_file_names)):
|
|
327 error_message = "Duplicated file names in the uploaded RAS matrices."
|
|
328 warning(error_message)
|
|
329 raise ValueError(error_message)
|
456
|
330
|
428
|
331 ras_class_names = []
|
|
332 for file in ras_file_names:
|
|
333 ras_class_names.append(file.rsplit(".", 1)[0])
|
|
334 ras_list = []
|
|
335 class_assignments = pd.DataFrame(columns=["Patient_ID", "Class"])
|
|
336 for ras_matrix, ras_class_name in zip(ras_file_list, ras_class_names):
|
|
337 ras = read_dataset(ras_matrix, "ras dataset")
|
|
338 ras.replace("None", None, inplace=True)
|
|
339 ras.set_index("Reactions", drop=True, inplace=True)
|
|
340 ras = ras.T
|
|
341 ras = ras.astype(float)
|
|
342 if(len(ras_file_list)>1):
|
456
|
343 # Append class name to patient id (DataFrame index)
|
428
|
344 ras.index = [f"{idx}_{ras_class_name}" for idx in ras.index]
|
|
345 else:
|
|
346 ras.index = [f"{idx}" for idx in ras.index]
|
|
347 ras_list.append(ras)
|
|
348 for patient_id in ras.index:
|
|
349 class_assignments.loc[class_assignments.shape[0]] = [patient_id, ras_class_name]
|
|
350
|
406
|
351
|
456
|
352 # Concatenate all RAS DataFrames into a single DataFrame
|
406
|
353 ras_combined = pd.concat(ras_list, axis=0)
|
456
|
354 # Normalize RAS values column-wise by max RAS
|
406
|
355 ras_combined = ras_combined.div(ras_combined.max(axis=0))
|
|
356 ras_combined.dropna(axis=1, how='all', inplace=True)
|
|
357
|
420
|
358 model = modelUtils.build_cobra_model_from_csv(ARGS.model_upload)
|
407
|
359
|
420
|
360 validation = modelUtils.validate_model(model)
|
406
|
361
|
456
|
362 print("\n=== MODEL VALIDATION ===")
|
407
|
363 for key, value in validation.items():
|
|
364 print(f"{key}: {value}")
|
|
365
|
428
|
366
|
|
367 generate_bounds_model(model, ras=ras_combined, output_folder=ARGS.output_path,
|
|
368 save_models=ARGS.save_models, save_models_path=ARGS.save_models_path,
|
|
369 save_models_format=ARGS.save_models_format)
|
|
370 class_assignments.to_csv(ARGS.cell_class, sep='\t', index=False)
|
|
371
|
406
|
372
|
456
|
373 return
|
406
|
374
|
|
375 ##############################################################################
|
|
376 if __name__ == "__main__":
|
|
377 main() |