489
|
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 """
|
93
|
11 import argparse
|
|
12 import utils.general_utils as utils
|
489
|
13 from typing import Optional, Dict, Set, List, Tuple, Union
|
93
|
14 import os
|
|
15 import numpy as np
|
|
16 import pandas as pd
|
|
17 import cobra
|
489
|
18 from cobra import Model
|
93
|
19 import sys
|
|
20 from joblib import Parallel, delayed, cpu_count
|
489
|
21 import utils.model_utils as modelUtils
|
93
|
22
|
|
23 ################################# process args ###############################
|
147
|
24 def process_args(args :List[str] = None) -> argparse.Namespace:
|
93
|
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
|
489
|
38 parser.add_argument("-mo", "--model_upload", type = str,
|
93
|
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
|
98
|
54 parser.add_argument('-rn', '--name',
|
94
|
55 type=str,
|
|
56 help = 'ras class names')
|
93
|
57
|
|
58 parser.add_argument('-cc', '--cell_class',
|
|
59 type = str,
|
|
60 help = 'output of cell class')
|
147
|
61 parser.add_argument(
|
|
62 '-idop', '--output_path',
|
|
63 type = str,
|
|
64 default='ras_to_bounds/',
|
|
65 help = 'output path for maps')
|
93
|
66
|
489
|
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
|
94
|
82
|
147
|
83 ARGS = parser.parse_args(args)
|
93
|
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 """
|
489
|
97 if ARGS.out_log:
|
|
98 with open(ARGS.out_log, 'a') as log:
|
|
99 log.write(s + "\n\n")
|
93
|
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
|
216
|
127 def apply_ras_bounds(bounds, ras_row):
|
93
|
128 """
|
|
129 Adjust the bounds of reactions in the model based on RAS values.
|
|
130
|
|
131 Args:
|
216
|
132 bounds (pd.DataFrame): Model bounds.
|
93
|
133 ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
|
|
134 Returns:
|
216
|
135 new_bounds (pd.DataFrame): integrated bounds.
|
93
|
136 """
|
216
|
137 new_bounds = bounds.copy()
|
122
|
138 for reaction in ras_row.index:
|
|
139 scaling_factor = ras_row[reaction]
|
222
|
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
|
216
|
152 return new_bounds
|
93
|
153
|
489
|
154
|
|
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
|
|
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)
|
|
180
|
506
|
181 compartments = modelUtils.generate_compartments(model)
|
489
|
182
|
|
183 df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"])
|
|
184 df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"])
|
|
185 df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
|
|
186 df_medium = medium.rename(columns = {"reaction": "ReactionID"})
|
|
187 df_medium["InMedium"] = True
|
|
188
|
|
189 merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
|
|
190 merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
|
506
|
191 # Add compartments only if they exist
|
|
192 if compartments is not None:
|
489
|
193 merged = merged.merge(compartments, on = "ReactionID", how = "outer")
|
|
194
|
|
195 merged = merged.merge(df_medium, on = "ReactionID", how = "left")
|
|
196 merged["InMedium"] = merged["InMedium"].fillna(False)
|
|
197 merged = merged.sort_values(by = "InMedium", ascending = False)
|
|
198
|
|
199 merged.to_csv(filepath, sep="\t", index=False)
|
|
200
|
|
201 else:
|
|
202 # Standard COBRA formats
|
|
203 filepath = os.path.join(output_folder, f"{filename}.{file_format}")
|
|
204
|
|
205 if file_format == 'xml':
|
|
206 cobra.io.write_sbml_model(model, filepath)
|
|
207 elif file_format == 'json':
|
|
208 cobra.io.save_json_model(model, filepath)
|
|
209 elif file_format == 'mat':
|
|
210 cobra.io.save_matlab_model(model, filepath)
|
|
211 elif file_format == 'yaml':
|
|
212 cobra.io.save_yaml_model(model, filepath)
|
|
213 else:
|
|
214 raise ValueError(f"Unsupported format: {file_format}")
|
|
215
|
|
216 print(f"Model saved: {filepath}")
|
|
217
|
|
218 except Exception as e:
|
|
219 warning(f"Error saving model {filename}: {str(e)}")
|
|
220
|
|
221 def apply_bounds_to_model(model, bounds):
|
|
222 """
|
|
223 Apply bounds from a DataFrame to a COBRA model.
|
|
224
|
|
225 Args:
|
|
226 model (cobra.Model): The metabolic model to modify.
|
|
227 bounds (pd.DataFrame): DataFrame with reaction bounds.
|
|
228
|
|
229 Returns:
|
|
230 cobra.Model: Modified model with new bounds.
|
|
231 """
|
|
232 model_copy = model.copy()
|
|
233 for reaction_id in bounds.index:
|
|
234 try:
|
|
235 reaction = model_copy.reactions.get_by_id(reaction_id)
|
|
236 reaction.lower_bound = bounds.loc[reaction_id, "lower_bound"]
|
|
237 reaction.upper_bound = bounds.loc[reaction_id, "upper_bound"]
|
|
238 except KeyError:
|
|
239 # Reaction not found in model, skip
|
|
240 continue
|
|
241 return model_copy
|
|
242
|
|
243 def process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder, save_models=False, save_models_path='saved_models/', save_models_format='csv'):
|
93
|
244 """
|
|
245 Process a single RAS cell, apply bounds, and save the bounds to a CSV file.
|
|
246
|
|
247 Args:
|
|
248 cellName (str): The name of the RAS cell (used for naming the output file).
|
|
249 ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
|
|
250 model (cobra.Model): The metabolic model to be modified.
|
|
251 rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
|
|
252 output_folder (str): Folder path where the output CSV file will be saved.
|
489
|
253 save_models (bool): Whether to save models with applied bounds.
|
|
254 save_models_path (str): Path where to save models.
|
|
255 save_models_format (str): Format for saved models.
|
93
|
256
|
|
257 Returns:
|
|
258 None
|
|
259 """
|
216
|
260 bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
|
|
261 new_bounds = apply_ras_bounds(bounds, ras_row)
|
|
262 new_bounds.to_csv(output_folder + cellName + ".csv", sep='\t', index=True)
|
489
|
263
|
|
264 # Save model if requested
|
|
265 if save_models:
|
|
266 modified_model = apply_bounds_to_model(model, new_bounds)
|
|
267 save_model(modified_model, cellName, save_models_path, save_models_format)
|
|
268
|
|
269 return
|
93
|
270
|
489
|
271 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:
|
93
|
272 """
|
|
273 Generate reaction bounds for a metabolic model based on medium conditions and optional RAS adjustments.
|
|
274
|
|
275 Args:
|
|
276 model (cobra.Model): The metabolic model for which bounds will be generated.
|
|
277 ras (pd.DataFrame, optional): RAS pandas dataframe. Defaults to None.
|
|
278 output_folder (str, optional): Folder path where output CSV files will be saved. Defaults to 'output/'.
|
489
|
279 save_models (bool): Whether to save models with applied bounds.
|
|
280 save_models_path (str): Path where to save models.
|
|
281 save_models_format (str): Format for saved models.
|
93
|
282
|
|
283 Returns:
|
|
284 pd.DataFrame: DataFrame containing the bounds of reactions in the model.
|
|
285 """
|
489
|
286 rxns_ids = [rxn.id for rxn in model.reactions]
|
107
|
287
|
120
|
288 # Perform Flux Variability Analysis (FVA) on this medium
|
93
|
289 df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
|
|
290
|
|
291 # Set FVA bounds
|
|
292 for reaction in rxns_ids:
|
102
|
293 model.reactions.get_by_id(reaction).lower_bound = float(df_FVA.loc[reaction, "minimum"])
|
|
294 model.reactions.get_by_id(reaction).upper_bound = float(df_FVA.loc[reaction, "maximum"])
|
93
|
295
|
|
296 if ras is not None:
|
489
|
297 Parallel(n_jobs=cpu_count())(delayed(process_ras_cell)(
|
|
298 cellName, ras_row, model, rxns_ids, output_folder,
|
|
299 save_models, save_models_path, save_models_format
|
|
300 ) for cellName, ras_row in ras.iterrows())
|
93
|
301 else:
|
489
|
302 raise ValueError("RAS DataFrame is None. Cannot generate bounds without RAS data.")
|
|
303 return
|
93
|
304
|
|
305 ############################# main ###########################################
|
147
|
306 def main(args:List[str] = None) -> None:
|
93
|
307 """
|
489
|
308 Initialize and execute RAS-to-bounds pipeline based on the frontend input arguments.
|
93
|
309
|
|
310 Returns:
|
|
311 None
|
|
312 """
|
|
313 if not os.path.exists('ras_to_bounds'):
|
|
314 os.makedirs('ras_to_bounds')
|
|
315
|
|
316 global ARGS
|
147
|
317 ARGS = process_args(args)
|
93
|
318
|
489
|
319
|
|
320 ras_file_list = ARGS.input_ras.split(",")
|
|
321 ras_file_names = ARGS.name.split(",")
|
|
322 if len(ras_file_names) != len(set(ras_file_names)):
|
|
323 error_message = "Duplicated file names in the uploaded RAS matrices."
|
|
324 warning(error_message)
|
|
325 raise ValueError(error_message)
|
94
|
326
|
489
|
327 ras_class_names = []
|
|
328 for file in ras_file_names:
|
|
329 ras_class_names.append(file.rsplit(".", 1)[0])
|
|
330 ras_list = []
|
|
331 class_assignments = pd.DataFrame(columns=["Patient_ID", "Class"])
|
|
332 for ras_matrix, ras_class_name in zip(ras_file_list, ras_class_names):
|
|
333 ras = read_dataset(ras_matrix, "ras dataset")
|
|
334 ras.replace("None", None, inplace=True)
|
|
335 ras.set_index("Reactions", drop=True, inplace=True)
|
|
336 ras = ras.T
|
|
337 ras = ras.astype(float)
|
|
338 if(len(ras_file_list)>1):
|
|
339 # Append class name to patient id (DataFrame index)
|
|
340 ras.index = [f"{idx}_{ras_class_name}" for idx in ras.index]
|
|
341 else:
|
|
342 ras.index = [f"{idx}" for idx in ras.index]
|
|
343 ras_list.append(ras)
|
|
344 for patient_id in ras.index:
|
|
345 class_assignments.loc[class_assignments.shape[0]] = [patient_id, ras_class_name]
|
|
346
|
93
|
347
|
489
|
348 # Concatenate all RAS DataFrames into a single DataFrame
|
94
|
349 ras_combined = pd.concat(ras_list, axis=0)
|
489
|
350 # Normalize RAS values column-wise by max RAS
|
93
|
351 ras_combined = ras_combined.div(ras_combined.max(axis=0))
|
123
|
352 ras_combined.dropna(axis=1, how='all', inplace=True)
|
93
|
353
|
489
|
354 model = modelUtils.build_cobra_model_from_csv(ARGS.model_upload)
|
93
|
355
|
489
|
356 validation = modelUtils.validate_model(model)
|
|
357
|
|
358 print("\n=== MODEL VALIDATION ===")
|
|
359 for key, value in validation.items():
|
|
360 print(f"{key}: {value}")
|
93
|
361
|
|
362
|
489
|
363 generate_bounds_model(model, ras=ras_combined, output_folder=ARGS.output_path,
|
|
364 save_models=ARGS.save_models, save_models_path=ARGS.save_models_path,
|
|
365 save_models_format=ARGS.save_models_format)
|
|
366 class_assignments.to_csv(ARGS.cell_class, sep='\t', index=False)
|
93
|
367
|
489
|
368
|
|
369 return
|
93
|
370
|
|
371 ##############################################################################
|
|
372 if __name__ == "__main__":
|
|
373 main() |