406
|
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
|
|
9 from typing import Optional, Tuple, Union, List, Dict
|
|
10 import utils.reaction_parsing as reactionUtils
|
418
|
11 import utils.model_utils as modelUtils
|
426
|
12 import logging
|
406
|
13
|
|
14 ARGS : argparse.Namespace
|
|
15 def process_args(args: List[str] = None) -> argparse.Namespace:
|
|
16 """
|
|
17 Parse command-line arguments for CustomDataGenerator.
|
|
18 """
|
|
19
|
|
20 parser = argparse.ArgumentParser(
|
|
21 usage="%(prog)s [options]",
|
|
22 description="Generate custom data from a given model"
|
|
23 )
|
|
24
|
|
25 parser.add_argument("--out_log", type=str, required=True,
|
|
26 help="Output log file")
|
|
27
|
|
28 parser.add_argument("--model", type=str,
|
|
29 help="Built-in model identifier (e.g., ENGRO2, Recon, HMRcore)")
|
|
30 parser.add_argument("--input", type=str,
|
|
31 help="Custom model file (JSON or XML)")
|
|
32 parser.add_argument("--name", type=str, required=True,
|
|
33 help="Model name (default or custom)")
|
|
34
|
|
35 parser.add_argument("--medium_selector", type=str, required=True,
|
|
36 help="Medium selection option")
|
|
37
|
|
38 parser.add_argument("--gene_format", type=str, default="Default",
|
|
39 help="Gene nomenclature format: Default (original), ENSNG, HGNC_SYMBOL, HGNC_ID, ENTREZ")
|
|
40
|
|
41 parser.add_argument("--out_tabular", type=str,
|
|
42 help="Output file for the merged dataset (CSV or XLSX)")
|
|
43
|
|
44 parser.add_argument("--tool_dir", type=str, default=os.path.dirname(__file__),
|
|
45 help="Tool directory (passed from Galaxy as $__tool_directory__)")
|
|
46
|
|
47
|
|
48 return parser.parse_args(args)
|
|
49
|
|
50 ################################- INPUT DATA LOADING -################################
|
|
51 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
|
|
52 """
|
|
53 Loads a custom model from a file, either in JSON or XML format.
|
|
54
|
|
55 Args:
|
|
56 file_path : The path to the file containing the custom model.
|
|
57 ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
|
|
58
|
|
59 Raises:
|
|
60 DataErr : if the file is in an invalid format or cannot be opened for whatever reason.
|
|
61
|
|
62 Returns:
|
|
63 cobra.Model : the model, if successfully opened.
|
|
64 """
|
|
65 ext = ext if ext else file_path.ext
|
|
66 try:
|
|
67 if ext is utils.FileFormat.XML:
|
|
68 return cobra.io.read_sbml_model(file_path.show())
|
|
69
|
|
70 if ext is utils.FileFormat.JSON:
|
|
71 return cobra.io.load_json_model(file_path.show())
|
|
72
|
|
73 except Exception as e: raise utils.DataErr(file_path, e.__str__())
|
|
74 raise utils.DataErr(file_path,
|
|
75 f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML")
|
|
76
|
|
77
|
|
78 ###############################- FILE SAVING -################################
|
|
79 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None:
|
|
80 """
|
|
81 Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath.
|
|
82
|
|
83 Args:
|
|
84 data : the data to be written to the file.
|
|
85 file_path : the path to the .csv file.
|
|
86 fieldNames : the names of the fields (columns) in the .csv file.
|
|
87
|
|
88 Returns:
|
|
89 None
|
|
90 """
|
|
91 with open(file_path.show(), 'w', newline='') as csvfile:
|
|
92 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
|
|
93 writer.writeheader()
|
|
94
|
|
95 for key, value in data.items():
|
|
96 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
|
|
97
|
|
98 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None:
|
|
99 """
|
|
100 Saves any dictionary-shaped data in a .csv file created at the given file_path as string.
|
|
101
|
|
102 Args:
|
|
103 data : the data to be written to the file.
|
|
104 file_path : the path to the .csv file.
|
|
105 fieldNames : the names of the fields (columns) in the .csv file.
|
|
106
|
|
107 Returns:
|
|
108 None
|
|
109 """
|
|
110 with open(file_path, 'w', newline='') as csvfile:
|
|
111 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
|
|
112 writer.writeheader()
|
|
113
|
|
114 for key, value in data.items():
|
|
115 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
|
|
116
|
|
117 def save_as_tabular_df(df: pd.DataFrame, path: str) -> None:
|
|
118 try:
|
|
119 os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
120 df.to_csv(path, sep="\t", index=False)
|
|
121 except Exception as e:
|
|
122 raise utils.DataErr(path, f"failed writing tabular output: {e}")
|
|
123
|
|
124
|
|
125 ###############################- ENTRY POINT -################################
|
|
126 def main(args:List[str] = None) -> None:
|
|
127 """
|
|
128 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
129
|
|
130 Returns:
|
|
131 None
|
|
132 """
|
|
133 # get args from frontend (related xml)
|
|
134 global ARGS
|
|
135 ARGS = process_args(args)
|
|
136
|
|
137
|
|
138 if ARGS.input:
|
|
139 # load custom model
|
|
140 model = load_custom_model(
|
|
141 utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext)
|
|
142 else:
|
|
143 # load built-in model
|
|
144
|
|
145 try:
|
|
146 model_enum = utils.Model[ARGS.model] # e.g., Model['ENGRO2']
|
|
147 except KeyError:
|
|
148 raise utils.ArgsErr("model", "one of Recon/ENGRO2/HMRcore/Custom_model", ARGS.model)
|
|
149
|
|
150 # Load built-in model (Model.getCOBRAmodel uses tool_dir to locate local models)
|
|
151 try:
|
|
152 model = model_enum.getCOBRAmodel(toolDir=ARGS.tool_dir)
|
|
153 except Exception as e:
|
|
154 # Wrap/normalize load errors as DataErr for consistency
|
|
155 raise utils.DataErr(ARGS.model, f"failed loading built-in model: {e}")
|
|
156
|
|
157 # Determine final model name: explicit --name overrides, otherwise use the model id
|
|
158
|
|
159 model_name = ARGS.name if ARGS.name else ARGS.model
|
|
160
|
|
161 if ARGS.name == "ENGRO2" and ARGS.medium_selector != "Default":
|
|
162 df_mediums = pd.read_csv(ARGS.tool_dir + "/local/medium/medium.csv", index_col = 0)
|
|
163 ARGS.medium_selector = ARGS.medium_selector.replace("_", " ")
|
|
164 medium = df_mediums[[ARGS.medium_selector]]
|
|
165 medium = medium[ARGS.medium_selector].to_dict()
|
|
166
|
|
167 # Set all reactions to zero in the medium
|
|
168 for rxn_id, _ in model.medium.items():
|
|
169 model.reactions.get_by_id(rxn_id).lower_bound = float(0.0)
|
|
170
|
|
171 # Set medium conditions
|
|
172 for reaction, value in medium.items():
|
|
173 if value is not None:
|
|
174 model.reactions.get_by_id(reaction).lower_bound = -float(value)
|
|
175
|
444
|
176 #if ARGS.name == "ENGRO2" and ARGS.gene_format != "Default":
|
|
177 # logging.basicConfig(level=logging.INFO)
|
|
178 # logger = logging.getLogger(__name__)
|
|
179
|
|
180 #model = modelUtils.translate_model_genes(
|
|
181 # model=model,
|
|
182 # mapping_df= pd.read_csv(ARGS.tool_dir + "/local/mappings/genes_human.csv"), dtype={'entrez_id': str},
|
|
183 # target_nomenclature=ARGS.gene_format.replace("HGNC_", "HGNC "),
|
|
184 # source_nomenclature='HGNC_ID',
|
|
185 # logger=logger
|
|
186 #)
|
|
187 #model = modelUtils.convert_genes(model, ARGS.gene_format.replace("HGNC_", "HGNC "))
|
|
188
|
|
189 if (ARGS.name == "Recon" or ARGS.name == "ENGRO2") and ARGS.gene_format != "Default":
|
426
|
190 logging.basicConfig(level=logging.INFO)
|
|
191 logger = logging.getLogger(__name__)
|
406
|
192
|
426
|
193 model = modelUtils.translate_model_genes(
|
|
194 model=model,
|
444
|
195 mapping_df= pd.read_csv(ARGS.tool_dir + "/local/mappings/genes_human.csv", dtype={'entrez_id': str}),
|
445
|
196 target_nomenclature=ARGS.gene_format,
|
426
|
197 source_nomenclature='HGNC_symbol',
|
|
198 logger=logger
|
|
199 )
|
406
|
200
|
|
201 # generate data
|
418
|
202 rules = modelUtils.generate_rules(model, asParsed = False)
|
|
203 reactions = modelUtils.generate_reactions(model, asParsed = False)
|
|
204 bounds = modelUtils.generate_bounds(model)
|
|
205 medium = modelUtils.get_medium(model)
|
426
|
206 objective_function = modelUtils.extract_objective_coefficients(model)
|
|
207
|
406
|
208 if ARGS.name == "ENGRO2":
|
418
|
209 compartments = modelUtils.generate_compartments(model)
|
406
|
210
|
426
|
211 df_rules = pd.DataFrame(list(rules.items()), columns = ["ReactionID", "GPR"])
|
|
212 df_reactions = pd.DataFrame(list(reactions.items()), columns = ["ReactionID", "Formula"])
|
406
|
213
|
|
214 df_bounds = bounds.reset_index().rename(columns = {"index": "ReactionID"})
|
|
215 df_medium = medium.rename(columns = {"reaction": "ReactionID"})
|
|
216 df_medium["InMedium"] = True # flag per indicare la presenza nel medium
|
|
217
|
|
218 merged = df_reactions.merge(df_rules, on = "ReactionID", how = "outer")
|
|
219 merged = merged.merge(df_bounds, on = "ReactionID", how = "outer")
|
426
|
220 merged = merged.merge(objective_function, on = "ReactionID", how = "outer")
|
406
|
221 if ARGS.name == "ENGRO2":
|
|
222 merged = merged.merge(compartments, on = "ReactionID", how = "outer")
|
|
223 merged = merged.merge(df_medium, on = "ReactionID", how = "left")
|
|
224
|
|
225 merged["InMedium"] = merged["InMedium"].fillna(False)
|
|
226
|
|
227 merged = merged.sort_values(by = "InMedium", ascending = False)
|
|
228
|
|
229 #out_file = os.path.join(ARGS.output_path, f"{os.path.basename(ARGS.name).split('.')[0]}_custom_data")
|
|
230
|
|
231 #merged.to_csv(out_file, sep = '\t', index = False)
|
|
232
|
|
233 ####
|
|
234
|
|
235 if not ARGS.out_tabular:
|
|
236 raise utils.ArgsErr("out_tabular", "output path (--out_tabular) is required when output_format == tabular", ARGS.out_tabular)
|
|
237 save_as_tabular_df(merged, ARGS.out_tabular)
|
|
238 expected = ARGS.out_tabular
|
|
239
|
|
240 # verify output exists and non-empty
|
|
241 if not expected or not os.path.exists(expected) or os.path.getsize(expected) == 0:
|
|
242 raise utils.DataErr(expected, "Output non creato o vuoto")
|
|
243
|
|
244 print("CustomDataGenerator: completed successfully")
|
|
245
|
|
246 if __name__ == '__main__':
|
|
247 main() |