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