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