93
|
1 import os
|
|
2 import csv
|
|
3 import cobra
|
|
4 import pickle
|
|
5 import argparse
|
|
6 import pandas as pd
|
|
7 import utils.general_utils as utils
|
|
8 import utils.rule_parsing as rulesUtils
|
147
|
9 from typing import Optional, Tuple, Union, List, Dict
|
93
|
10 import utils.reaction_parsing as reactionUtils
|
|
11
|
|
12 ARGS : argparse.Namespace
|
343
|
13 def process_args(args: List[str] = None) -> argparse.Namespace:
|
|
14 """
|
|
15 Parse command-line arguments for CustomDataGenerator.
|
93
|
16 """
|
343
|
17
|
|
18 parser = argparse.ArgumentParser(
|
|
19 usage="%(prog)s [options]",
|
|
20 description="Generate custom data from a given model"
|
|
21 )
|
93
|
22
|
343
|
23 parser.add_argument("--out_log", type=str, required=True,
|
|
24 help="Output log file")
|
93
|
25
|
343
|
26 parser.add_argument("--model", type=str,
|
|
27 help="Built-in model identifier (e.g., ENGRO2, Recon, HMRcore)")
|
|
28 parser.add_argument("--input", type=str,
|
|
29 help="Custom model file (JSON or XML)")
|
|
30 parser.add_argument("--name", type=str, required=True,
|
|
31 help="Model name (default or custom)")
|
93
|
32
|
343
|
33 parser.add_argument("--medium_selector", type=str, required=True,
|
393
|
34 help="Medium selection option")
|
|
35
|
|
36 parser.add_argument("--gene_format", type=str, default="Default",
|
|
37 help="Gene nomenclature format: Default (original), ENSNG, HGNC_SYMBOL, HGNC_ID, ENTREZ")
|
343
|
38
|
375
|
39 parser.add_argument("--out_tabular", type=str,
|
|
40 help="Output file for the merged dataset (CSV or XLSX)")
|
|
41
|
353
|
42 parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__),
|
363
|
43 help="Tool directory (passed from Galaxy as $__tool_directory__)")
|
353
|
44
|
93
|
45
|
343
|
46 return parser.parse_args(args)
|
93
|
47
|
|
48 ################################- INPUT DATA LOADING -################################
|
|
49 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
|
|
50 """
|
|
51 Loads a custom model from a file, either in JSON or XML format.
|
|
52
|
|
53 Args:
|
|
54 file_path : The path to the file containing the custom model.
|
|
55 ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
|
|
56
|
|
57 Raises:
|
|
58 DataErr : if the file is in an invalid format or cannot be opened for whatever reason.
|
|
59
|
|
60 Returns:
|
|
61 cobra.Model : the model, if successfully opened.
|
|
62 """
|
|
63 ext = ext if ext else file_path.ext
|
|
64 try:
|
|
65 if ext is utils.FileFormat.XML:
|
|
66 return cobra.io.read_sbml_model(file_path.show())
|
|
67
|
|
68 if ext is utils.FileFormat.JSON:
|
|
69 return cobra.io.load_json_model(file_path.show())
|
|
70
|
|
71 except Exception as e: raise utils.DataErr(file_path, e.__str__())
|
|
72 raise utils.DataErr(file_path,
|
|
73 f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML")
|
|
74
|
|
75 ################################- DATA GENERATION -################################
|
|
76 ReactionId = str
|
|
77 def generate_rules(model: cobra.Model, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]:
|
|
78 """
|
|
79 Generates a dictionary mapping reaction ids to rules from the model.
|
|
80
|
|
81 Args:
|
|
82 model : the model to derive data from.
|
|
83 asParsed : if True parses the rules to an optimized runtime format, otherwise leaves them as strings.
|
|
84
|
|
85 Returns:
|
|
86 Dict[ReactionId, rulesUtils.OpList] : the generated dictionary of parsed rules.
|
|
87 Dict[ReactionId, str] : the generated dictionary of raw rules.
|
|
88 """
|
|
89 # Is the below approach convoluted? yes
|
|
90 # Ok but is it inefficient? probably
|
|
91 # Ok but at least I don't have to repeat the check at every rule (I'm clinically insane)
|
|
92 _ruleGetter = lambda reaction : reaction.gene_reaction_rule
|
|
93 ruleExtractor = (lambda reaction :
|
|
94 rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter
|
|
95
|
|
96 return {
|
|
97 reaction.id : ruleExtractor(reaction)
|
|
98 for reaction in model.reactions
|
|
99 if reaction.gene_reaction_rule }
|
|
100
|
|
101 def generate_reactions(model :cobra.Model, *, asParsed = True) -> Dict[ReactionId, str]:
|
|
102 """
|
|
103 Generates a dictionary mapping reaction ids to reaction formulas from the model.
|
|
104
|
|
105 Args:
|
|
106 model : the model to derive data from.
|
|
107 asParsed : if True parses the reactions to an optimized runtime format, otherwise leaves them as they are.
|
|
108
|
|
109 Returns:
|
|
110 Dict[ReactionId, str] : the generated dictionary.
|
|
111 """
|
|
112
|
|
113 unparsedReactions = {
|
|
114 reaction.id : reaction.reaction
|
|
115 for reaction in model.reactions
|
|
116 if reaction.reaction
|
|
117 }
|
|
118
|
|
119 if not asParsed: return unparsedReactions
|
|
120
|
|
121 return reactionUtils.create_reaction_dict(unparsedReactions)
|
|
122
|
|
123 def get_medium(model:cobra.Model) -> pd.DataFrame:
|
|
124 trueMedium=[]
|
|
125 for r in model.reactions:
|
|
126 positiveCoeff=0
|
|
127 for m in r.metabolites:
|
|
128 if r.get_coefficient(m.id)>0:
|
|
129 positiveCoeff=1;
|
|
130 if (positiveCoeff==0 and r.lower_bound<0):
|
|
131 trueMedium.append(r.id)
|
|
132
|
|
133 df_medium = pd.DataFrame()
|
|
134 df_medium["reaction"] = trueMedium
|
|
135 return df_medium
|
|
136
|
|
137 def generate_bounds(model:cobra.Model) -> pd.DataFrame:
|
|
138
|
|
139 rxns = []
|
|
140 for reaction in model.reactions:
|
|
141 rxns.append(reaction.id)
|
|
142
|
|
143 bounds = pd.DataFrame(columns = ["lower_bound", "upper_bound"], index=rxns)
|
|
144
|
|
145 for reaction in model.reactions:
|
|
146 bounds.loc[reaction.id] = [reaction.lower_bound, reaction.upper_bound]
|
|
147 return bounds
|
|
148
|
|
149
|
403
|
150
|
|
151 def generate_compartments(model: cobra.Model) -> pd.DataFrame:
|
|
152 """
|
|
153 Generates a DataFrame containing compartment information for each reaction.
|
|
154 Creates columns for each compartment position (Compartment_1, Compartment_2, etc.)
|
|
155
|
|
156 Args:
|
|
157 model: the COBRA model to extract compartment data from.
|
|
158
|
|
159 Returns:
|
|
160 pd.DataFrame: DataFrame with ReactionID and compartment columns
|
|
161 """
|
|
162 compartment_data = []
|
|
163
|
|
164 # First pass: determine the maximum number of compartments any reaction has
|
|
165 max_compartments = 0
|
|
166 reaction_compartments = {}
|
|
167
|
|
168 for reaction in model.reactions:
|
|
169 # Get unique compartments from all metabolites in the reaction
|
|
170 if type(reaction.annotation['pathways']) == list:
|
|
171 reaction_compartments[reaction.id] = reaction.annotation['pathways']
|
|
172 max_compartments = max(max_compartments, len(reaction.annotation['pathways']))
|
|
173 else:
|
|
174 reaction_compartments[reaction.id] = [reaction.annotation['pathways']]
|
|
175
|
|
176 # Create column names for compartments
|
|
177 compartment_columns = [f"Compartment_{i+1}" for i in range(max_compartments)]
|
|
178
|
|
179 # Second pass: create the data
|
|
180 for reaction_id, compartments in reaction_compartments.items():
|
|
181 row = {"ReactionID": reaction_id}
|
|
182
|
|
183 # Fill compartment columns
|
|
184 for i in range(max_compartments):
|
|
185 col_name = compartment_columns[i]
|
|
186 if i < len(compartments):
|
|
187 row[col_name] = compartments[i]
|
|
188
|
|
189 else:
|
|
190 row[col_name] = None # or "" if you prefer empty strings
|
|
191
|
|
192 compartment_data.append(row)
|
|
193
|
|
194 return pd.DataFrame(compartment_data)
|
|
195
|
|
196
|
93
|
197 ###############################- FILE SAVING -################################
|
|
198 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None:
|
|
199 """
|
|
200 Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath.
|
|
201
|
|
202 Args:
|
|
203 data : the data to be written to the file.
|
|
204 file_path : the path to the .csv file.
|
|
205 fieldNames : the names of the fields (columns) in the .csv file.
|
|
206
|
|
207 Returns:
|
|
208 None
|
|
209 """
|
|
210 with open(file_path.show(), 'w', newline='') as csvfile:
|
|
211 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
|
|
212 writer.writeheader()
|
|
213
|
|
214 for key, value in data.items():
|
|
215 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
|
|
216
|
|
217 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None:
|
|
218 """
|
|
219 Saves any dictionary-shaped data in a .csv file created at the given file_path as string.
|
|
220
|
|
221 Args:
|
|
222 data : the data to be written to the file.
|
|
223 file_path : the path to the .csv file.
|
|
224 fieldNames : the names of the fields (columns) in the .csv file.
|
|
225
|
|
226 Returns:
|
|
227 None
|
|
228 """
|
|
229 with open(file_path, 'w', newline='') as csvfile:
|
|
230 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
|
|
231 writer.writeheader()
|
|
232
|
|
233 for key, value in data.items():
|
|
234 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
|
|
235
|
377
|
236 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None:
|
|
237 try:
|
|
238 os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
239 df.to_csv(path, sep="\t", index=False)
|
|
240 except Exception as e:
|
|
241 raise utils.DataErr(path, f"failed writing tabular output: {e}")
|
|
242
|
|
243
|
93
|
244 ###############################- ENTRY POINT -################################
|
147
|
245 def main(args:List[str] = None) -> None:
|
93
|
246 """
|
|
247 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
248
|
|
249 Returns:
|
|
250 None
|
|
251 """
|
|
252 # get args from frontend (related xml)
|
|
253 global ARGS
|
147
|
254 ARGS = process_args(args)
|
93
|
255
|
343
|
256
|
350
|
257 if ARGS.input:
|
343
|
258 # load custom model
|
|
259 model = load_custom_model(
|
|
260 utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext)
|
|
261 else:
|
|
262 # load built-in model
|
93
|
263
|
343
|
264 try:
|
|
265 model_enum = utils.Model[ARGS.model] # e.g., Model['ENGRO2']
|
|
266 except KeyError:
|
|
267 raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model)
|
|
268
|
|
269 # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models)
|
|
270 try:
|
353
|
271 model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir)
|
343
|
272 except Exception as e:
|
|
273 # Wrap/normalize load errors as DataErr for consistency
|
|
274 raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}")
|
|
275
|
|
276 # Determine final model name: explicit --name overrides, otherwise use the model id
|
393
|
277
|
343
|
278 model_name = ARGS.name if ARGS.name else ARGS.model
|
393
|
279
|
|
280 if ARGS.name == "ENGRO2" and ARGS.medium_selector != "Default":
|
|
281 df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0)
|
|
282 ARGS.medium_selector = ARGS.medium_selector.replace("_", " ")
|
|
283 medium = df_mediums[[ARGS.medium_selector]]
|
|
284 medium = medium[ARGS.medium_selector].to_dict()
|
|
285
|
|
286 # Set all reactions to zero in the medium
|
|
287 for rxn_id, _ in model.medium.items():
|
|
288 model.reactions.get_by_id(rxn_id).lower_bound = float(0.0)
|
|
289
|
|
290 # Set medium conditions
|
|
291 for reaction, value in medium.items():
|
|
292 if value is not None:
|
|
293 model.reactions.get_by_id(reaction).lower_bound = -float(value)
|
|
294
|
|
295 if ARGS.name == "ENGRO2" and ARGS.gene_format != "Default":
|
396
|
296
|
397
|
297 model = utils.convert_genes(model, ARGS.gene_format.replace("HGNC_", "HGNC "))
|
93
|
298
|
|
299 # generate data
|
|
300 rules = generate_rules(model, asParsed = False)
|
|
301 reactions = generate_reactions(model, asParsed = False)
|
|
302 bounds = generate_bounds(model)
|
|
303 medium = get_medium(model)
|
403
|
304 compartments = generate_compartments(model)
|
93
|
305
|
343
|
306 df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"])
|
|
307 df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"])
|
|
308
|
|
309 df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
|
|
310 df_medium = medium.rename(columns = {"reaction": "ReactionID"})
|
|
311 df_medium["InMedium"] = True # flag per indicare la presenza nel medium
|
|
312
|
|
313 merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
|
|
314 merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
|
403
|
315 merged = merged.merge(compartments, on = "ReactionID", how = "outer")
|
343
|
316 merged = merged.merge(df_medium, on = "ReactionID", how = "left")
|
|
317
|
|
318 merged["InMedium"] = merged["InMedium"].fillna(False)
|
|
319
|
|
320 merged = merged.sort_values(by = "InMedium", ascending = False)
|
|
321
|
359
|
322 #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data")
|
343
|
323
|
|
324 #merged.to_csv(out_file, sep = '\t', index = False)
|
|
325
|
|
326
|
|
327 ####
|
|
328
|
384
|
329
|
|
330 if not ARGS.out_tabular:
|
|
331 raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular)
|
|
332 save_as_tabular_df(merged, ARGS.out_tabular)
|
|
333 expected = ARGS.out_tabular
|
377
|
334
|
|
335 # verify output exists and non-empty
|
|
336 if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0:
|
|
337 raise utils.DataErr(expected, "Output non creato o vuoto")
|
343
|
338
|
386
|
339 print("CustomDataGenerator: completed successfully")
|
93
|
340
|
|
341 if __name__ == '__main__':
|
|
342 main() |