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("-meo", "--medium", type = str,
|
|
35 help = "path to input file with custom medium, 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
|
|
68
|
|
69 ARGS = parser.parse_args(args)
|
|
70 return ARGS
|
|
71
|
|
72 ########################### warning ###########################################
|
|
73 def warning(s :str) -> None:
|
|
74 """
|
|
75 Log a warning message to an output log file and print it to the console.
|
|
76
|
|
77 Args:
|
|
78 s (str): The warning message to be logged and printed.
|
|
79
|
|
80 Returns:
|
|
81 None
|
|
82 """
|
|
83 with open(ARGS.out_log, 'a') as log:
|
|
84 log.write(s + "\n\n")
|
|
85 print(s)
|
|
86
|
|
87 ############################ dataset input ####################################
|
|
88 def read_dataset(data :str, name :str) -> pd.DataFrame:
|
|
89 """
|
|
90 Read a dataset from a CSV file and return it as a pandas DataFrame.
|
|
91
|
|
92 Args:
|
|
93 data (str): Path to the CSV file containing the dataset.
|
|
94 name (str): Name of the dataset, used in error messages.
|
|
95
|
|
96 Returns:
|
|
97 pandas.DataFrame: DataFrame containing the dataset.
|
|
98
|
|
99 Raises:
|
|
100 pd.errors.EmptyDataError: If the CSV file is empty.
|
|
101 sys.exit: If the CSV file has the wrong format, the execution is aborted.
|
|
102 """
|
|
103 try:
|
|
104 dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python')
|
|
105 except pd.errors.EmptyDataError:
|
|
106 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
107 if len(dataset.columns) < 2:
|
|
108 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
109 return dataset
|
|
110
|
|
111
|
|
112 def apply_ras_bounds(bounds, ras_row):
|
|
113 """
|
|
114 Adjust the bounds of reactions in the model based on RAS values.
|
|
115
|
|
116 Args:
|
|
117 bounds (pd.DataFrame): Model bounds.
|
|
118 ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
|
|
119 Returns:
|
|
120 new_bounds (pd.DataFrame): integrated bounds.
|
|
121 """
|
|
122 new_bounds = bounds.copy()
|
|
123 for reaction in ras_row.index:
|
|
124 scaling_factor = ras_row[reaction]
|
|
125 if not np.isnan(scaling_factor):
|
|
126 lower_bound=bounds.loc[reaction, "lower_bound"]
|
|
127 upper_bound=bounds.loc[reaction, "upper_bound"]
|
|
128 valMax=float((upper_bound)*scaling_factor)
|
|
129 valMin=float((lower_bound)*scaling_factor)
|
|
130 if upper_bound!=0 and lower_bound==0:
|
|
131 new_bounds.loc[reaction, "upper_bound"] = valMax
|
|
132 if upper_bound==0 and lower_bound!=0:
|
|
133 new_bounds.loc[reaction, "lower_bound"] = valMin
|
|
134 if upper_bound!=0 and lower_bound!=0:
|
|
135 new_bounds.loc[reaction, "lower_bound"] = valMin
|
|
136 new_bounds.loc[reaction, "upper_bound"] = valMax
|
|
137 return new_bounds
|
|
138
|
|
139 def process_ras_cell(cellName, ras_row, model, rxns_ids, output_folder):
|
|
140 """
|
|
141 Process a single RAS cell, apply bounds, and save the bounds to a CSV file.
|
|
142
|
|
143 Args:
|
|
144 cellName (str): The name of the RAS cell (used for naming the output file).
|
|
145 ras_row (pd.Series): A row from a RAS DataFrame containing scaling factors for reaction bounds.
|
|
146 model (cobra.Model): The metabolic model to be modified.
|
|
147 rxns_ids (list of str): List of reaction IDs to which the scaling factors will be applied.
|
|
148 output_folder (str): Folder path where the output CSV file will be saved.
|
|
149
|
|
150 Returns:
|
|
151 None
|
|
152 """
|
|
153 bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
|
|
154 new_bounds = apply_ras_bounds(bounds, ras_row)
|
|
155 new_bounds.to_csv(output_folder + cellName + ".csv", sep='\t', index=True)
|
|
156 pass
|
|
157
|
407
|
158 def generate_bounds(model: cobra.Model, ras=None, output_folder='output/') -> pd.DataFrame:
|
406
|
159 """
|
|
160 Generate reaction bounds for a metabolic model based on medium conditions and optional RAS adjustments.
|
|
161
|
|
162 Args:
|
|
163 model (cobra.Model): The metabolic model for which bounds will be generated.
|
|
164 medium (dict): A dictionary where keys are reaction IDs and values are the medium conditions.
|
|
165 ras (pd.DataFrame, optional): RAS pandas dataframe. Defaults to None.
|
|
166 output_folder (str, optional): Folder path where output CSV files will be saved. Defaults to 'output/'.
|
|
167
|
|
168 Returns:
|
|
169 pd.DataFrame: DataFrame containing the bounds of reactions in the model.
|
|
170 """
|
407
|
171 rxns_ids = [rxn.id for rxn in model.reactions]
|
406
|
172
|
|
173 # Perform Flux Variability Analysis (FVA) on this medium
|
|
174 df_FVA = cobra.flux_analysis.flux_variability_analysis(model, fraction_of_optimum=0, processes=1).round(8)
|
|
175
|
|
176 # Set FVA bounds
|
|
177 for reaction in rxns_ids:
|
|
178 model.reactions.get_by_id(reaction).lower_bound = float(df_FVA.loc[reaction, "minimum"])
|
|
179 model.reactions.get_by_id(reaction).upper_bound = float(df_FVA.loc[reaction, "maximum"])
|
|
180
|
|
181 if ras is not None:
|
|
182 Parallel(n_jobs=cpu_count())(delayed(process_ras_cell)(cellName, ras_row, model, rxns_ids, output_folder) for cellName, ras_row in ras.iterrows())
|
|
183 else:
|
|
184 bounds = pd.DataFrame([(rxn.lower_bound, rxn.upper_bound) for rxn in model.reactions], index=rxns_ids, columns=["lower_bound", "upper_bound"])
|
|
185 newBounds = apply_ras_bounds(bounds, pd.Series([1]*len(rxns_ids), index=rxns_ids))
|
|
186 newBounds.to_csv(output_folder + "bounds.csv", sep='\t', index=True)
|
|
187 pass
|
|
188
|
|
189 ############################# main ###########################################
|
|
190 def main(args:List[str] = None) -> None:
|
|
191 """
|
|
192 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
193
|
|
194 Returns:
|
|
195 None
|
|
196 """
|
|
197 if not os.path.exists('ras_to_bounds'):
|
|
198 os.makedirs('ras_to_bounds')
|
|
199
|
|
200
|
|
201 global ARGS
|
|
202 ARGS = process_args(args)
|
|
203
|
|
204 if(ARGS.ras_selector == True):
|
|
205 ras_file_list = ARGS.input_ras.split(",")
|
|
206 ras_file_names = ARGS.name.split(",")
|
|
207 if len(ras_file_names) != len(set(ras_file_names)):
|
|
208 error_message = "Duplicated file names in the uploaded RAS matrices."
|
|
209 warning(error_message)
|
|
210 raise ValueError(error_message)
|
|
211 pass
|
|
212 ras_class_names = []
|
|
213 for file in ras_file_names:
|
|
214 ras_class_names.append(file.rsplit(".", 1)[0])
|
|
215 ras_list = []
|
|
216 class_assignments = pd.DataFrame(columns=["Patient_ID", "Class"])
|
|
217 for ras_matrix, ras_class_name in zip(ras_file_list, ras_class_names):
|
|
218 ras = read_dataset(ras_matrix, "ras dataset")
|
|
219 ras.replace("None", None, inplace=True)
|
|
220 ras.set_index("Reactions", drop=True, inplace=True)
|
|
221 ras = ras.T
|
|
222 ras = ras.astype(float)
|
|
223 if(len(ras_file_list)>1):
|
|
224 #append class name to patient id (dataframe index)
|
|
225 ras.index = [f"{idx}_{ras_class_name}" for idx in ras.index]
|
|
226 else:
|
|
227 ras.index = [f"{idx}" for idx in ras.index]
|
|
228 ras_list.append(ras)
|
|
229 for patient_id in ras.index:
|
|
230 class_assignments.loc[class_assignments.shape[0]] = [patient_id, ras_class_name]
|
|
231
|
|
232
|
|
233 # Concatenate all ras DataFrames into a single DataFrame
|
|
234 ras_combined = pd.concat(ras_list, axis=0)
|
|
235 # Normalize the RAS values by max RAS
|
|
236 ras_combined = ras_combined.div(ras_combined.max(axis=0))
|
|
237 ras_combined.dropna(axis=1, how='all', inplace=True)
|
|
238
|
|
239
|
|
240
|
407
|
241 #model_type :utils.Model = ARGS.model_selector
|
|
242 #if model_type is utils.Model.Custom:
|
|
243 # model = model_type.getCOBRAmodel(customPath = utils.FilePath.fromStrPath(ARGS.model), customExtension = utils.FilePath.fromStrPath(ARGS.model_name).ext)
|
|
244 #else:
|
|
245 # model = model_type.getCOBRAmodel(toolDir=ARGS.tool_dir)
|
|
246
|
|
247 # TODO LOAD MODEL FROM UPLOAD
|
|
248
|
408
|
249 model = utils.build_cobra_model_from_csv(ARGS.model_upload)
|
407
|
250
|
408
|
251 validation = utils.validate_model(model)
|
406
|
252
|
407
|
253 print("\n=== VALIDAZIONE MODELLO ===")
|
|
254 for key, value in validation.items():
|
|
255 print(f"{key}: {value}")
|
|
256
|
|
257 #if(ARGS.medium_selector == "Custom"):
|
|
258 # medium = read_dataset(ARGS.medium, "medium dataset")
|
|
259 # medium.set_index(medium.columns[0], inplace=True)
|
|
260 # medium = medium.astype(float)
|
|
261 # medium = medium[medium.columns[0]].to_dict()
|
|
262 #else:
|
|
263 # df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0)
|
|
264 # ARGS.medium_selector = ARGS.medium_selector.replace("_", " ")
|
|
265 # medium = df_mediums[[ARGS.medium_selector]]
|
|
266 # medium = medium[ARGS.medium_selector].to_dict()
|
406
|
267
|
|
268 if(ARGS.ras_selector == True):
|
407
|
269 generate_bounds(model, ras = ras_combined, output_folder=ARGS.output_path)
|
406
|
270 class_assignments.to_csv(ARGS.cell_class, sep = '\t', index = False)
|
|
271 else:
|
407
|
272 generate_bounds(model, output_folder=ARGS.output_path)
|
406
|
273
|
|
274 pass
|
|
275
|
|
276 ##############################################################################
|
|
277 if __name__ == "__main__":
|
|
278 main() |