Mercurial > repos > bimib > marea_2_0
comparison custom_data_generator.py @ 283:813439d60f85 draft
Uploaded
author | luca_milaz |
---|---|
date | Mon, 08 Jul 2024 22:18:11 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
282:d385c4df70c3 | 283:813439d60f85 |
---|---|
1 import os | |
2 import csv | |
3 import cobra | |
4 import pickle | |
5 import argparse | |
6 import utils.general_utils as utils | |
7 import utils.rule_parsing as rulesUtils | |
8 from typing import Optional, Tuple, Union, Dict | |
9 import utils.reaction_parsing as reactionUtils | |
10 | |
11 ARGS : argparse.Namespace | |
12 def process_args() -> argparse.Namespace: | |
13 """ | |
14 Interfaces the script of a module with its frontend, making the user's choices for | |
15 various parameters available as values in code. | |
16 | |
17 Args: | |
18 args : Always obtained (in file) from sys.argv | |
19 | |
20 Returns: | |
21 Namespace : An object containing the parsed arguments | |
22 """ | |
23 parser = argparse.ArgumentParser( | |
24 usage = "%(prog)s [options]", | |
25 description = "generate custom data from a given model") | |
26 | |
27 parser.add_argument("-ol", "--out_log", type = str, required = True, help = "Output log") | |
28 parser.add_argument("-id", "--input", type = str, required = True, help = "Input model") | |
29 parser.add_argument("-mn", "--name", type = str, required = True, help = "Input model name") | |
30 # ^ I need this because galaxy converts my files into .dat but I need to know what extension they were in | |
31 | |
32 parser.add_argument( | |
33 "-of", "--output_format", | |
34 # vvv I have to use .fromExt because enums in python are the plague and have been implemented by a chimpanzee. | |
35 type = utils.FileFormat.fromExt, default = utils.FileFormat.PICKLE, | |
36 choices = [utils.FileFormat.CSV, utils.FileFormat.PICKLE], | |
37 # ^^^ Not all variants are valid here, otherwise list(utils.FileFormat) would be best. | |
38 required = True, help = "Extension of all output files") | |
39 | |
40 argsNamespace = parser.parse_args() | |
41 argsNamespace.out_dir = "result" | |
42 # ^ can't get this one to work from xml, there doesn't seem to be a way to get the directory attribute from the collection | |
43 | |
44 return argsNamespace | |
45 | |
46 ################################- INPUT DATA LOADING -################################ | |
47 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model: | |
48 """ | |
49 Loads a custom model from a file, either in JSON or XML format. | |
50 | |
51 Args: | |
52 file_path : The path to the file containing the custom model. | |
53 ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour. | |
54 | |
55 Raises: | |
56 DataErr : if the file is in an invalid format or cannot be opened for whatever reason. | |
57 | |
58 Returns: | |
59 cobra.Model : the model, if successfully opened. | |
60 """ | |
61 ext = ext if ext else file_path.ext | |
62 try: | |
63 if ext is utils.FileFormat.XML: | |
64 return cobra.io.read_sbml_model(file_path.show()) | |
65 | |
66 if ext is utils.FileFormat.JSON: | |
67 return cobra.io.load_json_model(file_path.show()) | |
68 | |
69 except Exception as e: raise utils.DataErr(file_path, e.__str__()) | |
70 raise utils.DataErr(file_path, | |
71 f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML") | |
72 | |
73 ################################- DATA GENERATION -################################ | |
74 ReactionId = str | |
75 def generate_rules(model: cobra.Model, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]: | |
76 """ | |
77 Generates a dictionary mapping reaction ids to rules from the model. | |
78 | |
79 Args: | |
80 model : the model to derive data from. | |
81 asParsed : if True parses the rules to an optimized runtime format, otherwise leaves them as strings. | |
82 | |
83 Returns: | |
84 Dict[ReactionId, rulesUtils.OpList] : the generated dictionary of parsed rules. | |
85 Dict[ReactionId, str] : the generated dictionary of raw rules. | |
86 """ | |
87 # Is the below approach convoluted? yes | |
88 # Ok but is it inefficient? probably | |
89 # Ok but at least I don't have to repeat the check at every rule (I'm clinically insane) | |
90 _ruleGetter = lambda reaction : reaction.gene_reaction_rule | |
91 ruleExtractor = (lambda reaction : | |
92 rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter | |
93 | |
94 return { | |
95 reaction.id : ruleExtractor(reaction) | |
96 for reaction in model.reactions | |
97 if reaction.gene_reaction_rule } | |
98 | |
99 def generate_reactions(model :cobra.Model, *, asParsed = True) -> Dict[ReactionId, str]: | |
100 """ | |
101 Generates a dictionary mapping reaction ids to reaction formulas from the model. | |
102 | |
103 Args: | |
104 model : the model to derive data from. | |
105 asParsed : if True parses the reactions to an optimized runtime format, otherwise leaves them as they are. | |
106 | |
107 Returns: | |
108 Dict[ReactionId, str] : the generated dictionary. | |
109 """ | |
110 | |
111 unparsedReactions = { | |
112 reaction.id : reaction.reaction | |
113 for reaction in model.reactions | |
114 if reaction.reaction | |
115 } | |
116 | |
117 if not asParsed: return unparsedReactions | |
118 | |
119 return reactionUtils.create_reaction_dict(unparsedReactions) | |
120 | |
121 ###############################- FILE SAVING -################################ | |
122 def save_as_csv(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None: | |
123 """ | |
124 Saves any dictionary-shaped data in a .csv file created at the given file_path. | |
125 | |
126 Args: | |
127 data : the data to be written to the file. | |
128 file_path : the path to the .csv file. | |
129 fieldNames : the names of the fields (columns) in the .csv file. | |
130 | |
131 Returns: | |
132 None | |
133 """ | |
134 with open(file_path.show(), 'w', newline='') as csvfile: | |
135 writer = csv.DictWriter(csvfile, fieldnames = fieldNames) | |
136 writer.writeheader() | |
137 | |
138 for key, value in data.items(): | |
139 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value }) | |
140 | |
141 ###############################- ENTRY POINT -################################ | |
142 def main() -> None: | |
143 """ | |
144 Initializes everything and sets the program in motion based on the fronted input arguments. | |
145 | |
146 Returns: | |
147 None | |
148 """ | |
149 # get args from frontend (related xml) | |
150 global ARGS | |
151 ARGS = process_args() | |
152 | |
153 # this is the worst thing I've seen so far, congrats to the former MaREA devs for suggesting this! | |
154 if os.path.isdir(ARGS.out_dir) == False: os.makedirs(ARGS.out_dir) | |
155 | |
156 # load custom model | |
157 model = load_custom_model( | |
158 utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext) | |
159 | |
160 # generate data and save it in the desired format and in a location galaxy understands | |
161 # (it should show up as a collection in the history) | |
162 rulesPath = utils.FilePath("rules", ARGS.output_format, prefix = ARGS.out_dir) | |
163 reactionsPath = utils.FilePath("reactions", ARGS.output_format, prefix = ARGS.out_dir) | |
164 | |
165 if ARGS.output_format is utils.FileFormat.PICKLE: | |
166 rules = generate_rules(model, asParsed = True) | |
167 reactions = generate_reactions(model, asParsed = True) | |
168 utils.writePickle(rulesPath, rules) | |
169 utils.writePickle(reactionsPath, reactions) | |
170 | |
171 elif ARGS.output_format is utils.FileFormat.CSV: | |
172 rules = generate_rules(model, asParsed = False) | |
173 reactions = generate_reactions(model, asParsed = False) | |
174 save_as_csv(rules, rulesPath, ("ReactionID", "Rule")) | |
175 save_as_csv(reactions, reactionsPath, ("ReactionID", "Reaction")) | |
176 | |
177 # ^ Please if anyone works on this after updating python to 3.12 change the if/elif into a match statement!! | |
178 | |
179 if __name__ == '__main__': | |
180 main() |