annotate marea_2/custom_data_generator.py @ 15:6ba96cfa8d7b draft

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