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,
|
|
34 help="Medium selection option (default/custom)")
|
|
35 parser.add_argument("--medium", type=str,
|
|
36 help="Custom medium file if medium_selector=Custom")
|
|
37
|
375
|
38 parser.add_argument("--out_tabular", type=str,
|
|
39 help="Output file for the merged dataset (CSV or XLSX)")
|
|
40
|
353
|
41 parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__),
|
363
|
42 help="Tool directory (passed from Galaxy as $__tool_directory__)")
|
353
|
43
|
93
|
44
|
343
|
45 return parser.parse_args(args)
|
93
|
46
|
|
47 ################################- INPUT DATA LOADING -################################
|
|
48 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
|
|
49 """
|
|
50 Loads a custom model from a file, either in JSON or XML format.
|
|
51
|
|
52 Args:
|
|
53 file_path : The path to the file containing the custom model.
|
|
54 ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
|
|
55
|
|
56 Raises:
|
|
57 DataErr : if the file is in an invalid format or cannot be opened for whatever reason.
|
|
58
|
|
59 Returns:
|
|
60 cobra.Model : the model, if successfully opened.
|
|
61 """
|
|
62 ext = ext if ext else file_path.ext
|
|
63 try:
|
|
64 if ext is utils.FileFormat.XML:
|
|
65 return cobra.io.read_sbml_model(file_path.show())
|
|
66
|
|
67 if ext is utils.FileFormat.JSON:
|
|
68 return cobra.io.load_json_model(file_path.show())
|
|
69
|
|
70 except Exception as e: raise utils.DataErr(file_path, e.__str__())
|
|
71 raise utils.DataErr(file_path,
|
|
72 f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML")
|
|
73
|
|
74 ################################- DATA GENERATION -################################
|
|
75 ReactionId = str
|
|
76 def generate_rules(model: cobra.Model, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]:
|
|
77 """
|
|
78 Generates a dictionary mapping reaction ids to rules from the model.
|
|
79
|
|
80 Args:
|
|
81 model : the model to derive data from.
|
|
82 asParsed : if True parses the rules to an optimized runtime format, otherwise leaves them as strings.
|
|
83
|
|
84 Returns:
|
|
85 Dict[ReactionId, rulesUtils.OpList] : the generated dictionary of parsed rules.
|
|
86 Dict[ReactionId, str] : the generated dictionary of raw rules.
|
|
87 """
|
|
88 # Is the below approach convoluted? yes
|
|
89 # Ok but is it inefficient? probably
|
|
90 # Ok but at least I don't have to repeat the check at every rule (I'm clinically insane)
|
|
91 _ruleGetter = lambda reaction : reaction.gene_reaction_rule
|
|
92 ruleExtractor = (lambda reaction :
|
|
93 rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter
|
|
94
|
|
95 return {
|
|
96 reaction.id : ruleExtractor(reaction)
|
|
97 for reaction in model.reactions
|
|
98 if reaction.gene_reaction_rule }
|
|
99
|
|
100 def generate_reactions(model :cobra.Model, *, asParsed = True) -> Dict[ReactionId, str]:
|
|
101 """
|
|
102 Generates a dictionary mapping reaction ids to reaction formulas from the model.
|
|
103
|
|
104 Args:
|
|
105 model : the model to derive data from.
|
|
106 asParsed : if True parses the reactions to an optimized runtime format, otherwise leaves them as they are.
|
|
107
|
|
108 Returns:
|
|
109 Dict[ReactionId, str] : the generated dictionary.
|
|
110 """
|
|
111
|
|
112 unparsedReactions = {
|
|
113 reaction.id : reaction.reaction
|
|
114 for reaction in model.reactions
|
|
115 if reaction.reaction
|
|
116 }
|
|
117
|
|
118 if not asParsed: return unparsedReactions
|
|
119
|
|
120 return reactionUtils.create_reaction_dict(unparsedReactions)
|
|
121
|
|
122 def get_medium(model:cobra.Model) -> pd.DataFrame:
|
|
123 trueMedium=[]
|
|
124 for r in model.reactions:
|
|
125 positiveCoeff=0
|
|
126 for m in r.metabolites:
|
|
127 if r.get_coefficient(m.id)>0:
|
|
128 positiveCoeff=1;
|
|
129 if (positiveCoeff==0 and r.lower_bound<0):
|
|
130 trueMedium.append(r.id)
|
|
131
|
|
132 df_medium = pd.DataFrame()
|
|
133 df_medium["reaction"] = trueMedium
|
|
134 return df_medium
|
|
135
|
|
136 def generate_bounds(model:cobra.Model) -> pd.DataFrame:
|
|
137
|
|
138 rxns = []
|
|
139 for reaction in model.reactions:
|
|
140 rxns.append(reaction.id)
|
|
141
|
|
142 bounds = pd.DataFrame(columns = ["lower_bound", "upper_bound"], index=rxns)
|
|
143
|
|
144 for reaction in model.reactions:
|
|
145 bounds.loc[reaction.id] = [reaction.lower_bound, reaction.upper_bound]
|
|
146 return bounds
|
|
147
|
|
148
|
|
149 ###############################- FILE SAVING -################################
|
|
150 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None:
|
|
151 """
|
|
152 Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath.
|
|
153
|
|
154 Args:
|
|
155 data : the data to be written to the file.
|
|
156 file_path : the path to the .csv file.
|
|
157 fieldNames : the names of the fields (columns) in the .csv file.
|
|
158
|
|
159 Returns:
|
|
160 None
|
|
161 """
|
|
162 with open(file_path.show(), 'w', newline='') as csvfile:
|
|
163 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
|
|
164 writer.writeheader()
|
|
165
|
|
166 for key, value in data.items():
|
|
167 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
|
|
168
|
|
169 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None:
|
|
170 """
|
|
171 Saves any dictionary-shaped data in a .csv file created at the given file_path as string.
|
|
172
|
|
173 Args:
|
|
174 data : the data to be written to the file.
|
|
175 file_path : the path to the .csv file.
|
|
176 fieldNames : the names of the fields (columns) in the .csv file.
|
|
177
|
|
178 Returns:
|
|
179 None
|
|
180 """
|
|
181 with open(file_path, 'w', newline='') as csvfile:
|
|
182 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
|
|
183 writer.writeheader()
|
|
184
|
|
185 for key, value in data.items():
|
|
186 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
|
|
187
|
377
|
188 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None:
|
|
189 try:
|
|
190 os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
191 df.to_csv(path, sep="\t", index=False)
|
|
192 except Exception as e:
|
|
193 raise utils.DataErr(path, f"failed writing tabular output: {e}")
|
|
194
|
|
195
|
93
|
196 ###############################- ENTRY POINT -################################
|
147
|
197 def main(args:List[str] = None) -> None:
|
93
|
198 """
|
|
199 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
200
|
|
201 Returns:
|
|
202 None
|
|
203 """
|
|
204 # get args from frontend (related xml)
|
|
205 global ARGS
|
147
|
206 ARGS = process_args(args)
|
93
|
207
|
343
|
208
|
350
|
209 if ARGS.input:
|
343
|
210 # load custom model
|
|
211 model = load_custom_model(
|
|
212 utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext)
|
|
213 else:
|
|
214 # load built-in model
|
93
|
215
|
343
|
216 try:
|
|
217 model_enum = utils.Model[ARGS.model] # e.g., Model['ENGRO2']
|
|
218 except KeyError:
|
|
219 raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model)
|
|
220
|
|
221 # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models)
|
|
222 try:
|
353
|
223 model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir)
|
343
|
224 except Exception as e:
|
|
225 # Wrap/normalize load errors as DataErr for consistency
|
|
226 raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}")
|
|
227
|
|
228 # Determine final model name: explicit --name overrides, otherwise use the model id
|
|
229 model_name = ARGS.name if ARGS.name else ARGS.model
|
93
|
230
|
|
231 # generate data
|
|
232 rules = generate_rules(model, asParsed = False)
|
|
233 reactions = generate_reactions(model, asParsed = False)
|
|
234 bounds = generate_bounds(model)
|
|
235 medium = get_medium(model)
|
|
236
|
343
|
237 df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "Rule"])
|
|
238 df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Reaction"])
|
|
239
|
|
240 df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
|
|
241 df_medium = medium.rename(columns = {"reaction": "ReactionID"})
|
|
242 df_medium["InMedium"] = True # flag per indicare la presenza nel medium
|
|
243
|
|
244 merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
|
|
245 merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
|
|
246
|
|
247 merged = merged.merge(df_medium, on = "ReactionID", how = "left")
|
|
248
|
|
249 merged["InMedium"] = merged["InMedium"].fillna(False)
|
|
250
|
|
251 merged = merged.sort_values(by = "InMedium", ascending = False)
|
|
252
|
359
|
253 #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data")
|
343
|
254
|
|
255 #merged.to_csv(out_file, sep = '\t', index = False)
|
|
256
|
|
257
|
|
258 ####
|
|
259
|
384
|
260
|
|
261 if not ARGS.out_tabular:
|
|
262 raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular)
|
|
263 save_as_tabular_df(merged, ARGS.out_tabular)
|
|
264 expected = ARGS.out_tabular
|
377
|
265
|
|
266 # verify output exists and non-empty
|
|
267 if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0:
|
|
268 raise utils.DataErr(expected, "Output non creato o vuoto")
|
343
|
269
|
386
|
270 print("CustomDataGenerator: completed successfully")
|
93
|
271
|
|
272 if __name__ == '__main__':
|
|
273 main() |