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