annotate COBRAxy/custom_data_generator.py @ 118:6e1a6e480969 draft

Uploaded
author luca_milaz
date Sun, 13 Oct 2024 16:32:08 +0000
parents 7e703e546998
children 3fca9b568faf
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
93
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
1 import os
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
2 import csv
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
3 import cobra
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
4 import pickle
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
5 import argparse
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
6 import pandas as pd
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
7 import utils.general_utils as utils
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
8 import utils.rule_parsing as rulesUtils
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
9 from typing import Optional, Tuple, Union, Dict
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
10 import utils.reaction_parsing as reactionUtils
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
11
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
12 ARGS : argparse.Namespace
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
13 def process_args() -> argparse.Namespace:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
14 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
15 Interfaces the script of a module with its frontend, making the user's choices for
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
16 various parameters available as values in code.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
17
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
18 Args:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
19 args : Always obtained (in file) from sys.argv
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
20
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
21 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
22 Namespace : An object containing the parsed arguments
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
23 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
24 parser = argparse.ArgumentParser(
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
25 usage = "%(prog)s [options]",
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
26 description = "generate custom data from a given model")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
27
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
28 parser.add_argument("-ol", "--out_log", type = str, required = True, help = "Output log")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
29
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
30 parser.add_argument("-orules", "--out_rules", type = str, required = True, help = "Output rules")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
31 parser.add_argument("-orxns", "--out_reactions", type = str, required = True, help = "Output reactions")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
32 parser.add_argument("-omedium", "--out_medium", type = str, required = True, help = "Output medium")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
33 parser.add_argument("-obnds", "--out_bounds", type = str, required = True, help = "Output bounds")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
34
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
35 parser.add_argument("-id", "--input", type = str, required = True, help = "Input model")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
36 parser.add_argument("-mn", "--name", type = str, required = True, help = "Input model name")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
37 # ^ I need this because galaxy converts my files into .dat but I need to know what extension they were in
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
38
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
39 argsNamespace = parser.parse_args()
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
40 argsNamespace.out_dir = "result"
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
41 # ^ 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
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
42
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
43 return argsNamespace
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
44
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
45 ################################- INPUT DATA LOADING -################################
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
46 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
47 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
48 Loads a custom model from a file, either in JSON or XML format.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
49
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
50 Args:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
51 file_path : The path to the file containing the custom model.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
52 ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
53
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
54 Raises:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
55 DataErr : if the file is in an invalid format or cannot be opened for whatever reason.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
56
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
57 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
58 cobra.Model : the model, if successfully opened.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
59 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
60 ext = ext if ext else file_path.ext
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
61 try:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
62 if ext is utils.FileFormat.XML:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
63 return cobra.io.read_sbml_model(file_path.show())
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
64
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
65 if ext is utils.FileFormat.JSON:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
66 return cobra.io.load_json_model(file_path.show())
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
67
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
68 except Exception as e: raise utils.DataErr(file_path, e.__str__())
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
69 raise utils.DataErr(file_path,
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
70 f"Formato \"{file_path.ext}\" non riconosciuto, sono supportati solo file JSON e XML")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
71
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
72 ################################- DATA GENERATION -################################
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
73 ReactionId = str
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
74 def generate_rules(model: cobra.Model, *, asParsed = True) -> Union[Dict[ReactionId, rulesUtils.OpList], Dict[ReactionId, str]]:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
75 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
76 Generates a dictionary mapping reaction ids to rules from the model.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
77
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
78 Args:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
79 model : the model to derive data from.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
80 asParsed : if True parses the rules to an optimized runtime format, otherwise leaves them as strings.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
81
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
82 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
83 Dict[ReactionId, rulesUtils.OpList] : the generated dictionary of parsed rules.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
84 Dict[ReactionId, str] : the generated dictionary of raw rules.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
85 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
86 # Is the below approach convoluted? yes
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
87 # Ok but is it inefficient? probably
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
88 # Ok but at least I don't have to repeat the check at every rule (I'm clinically insane)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
89 _ruleGetter = lambda reaction : reaction.gene_reaction_rule
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
90 ruleExtractor = (lambda reaction :
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
91 rulesUtils.parseRuleToNestedList(_ruleGetter(reaction))) if asParsed else _ruleGetter
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
92
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
93 return {
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
94 reaction.id : ruleExtractor(reaction)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
95 for reaction in model.reactions
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
96 if reaction.gene_reaction_rule }
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
97
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
98 def generate_reactions(model :cobra.Model, *, asParsed = True) -> Dict[ReactionId, str]:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
99 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
100 Generates a dictionary mapping reaction ids to reaction formulas from the model.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
101
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
102 Args:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
103 model : the model to derive data from.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
104 asParsed : if True parses the reactions to an optimized runtime format, otherwise leaves them as they are.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
105
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
106 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
107 Dict[ReactionId, str] : the generated dictionary.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
108 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
109
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
110 unparsedReactions = {
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
111 reaction.id : reaction.reaction
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
112 for reaction in model.reactions
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
113 if reaction.reaction
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
114 }
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
115
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
116 if not asParsed: return unparsedReactions
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
117
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
118 return reactionUtils.create_reaction_dict(unparsedReactions)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
119
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
120 def get_medium(model:cobra.Model) -> pd.DataFrame:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
121 trueMedium=[]
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
122 for r in model.reactions:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
123 positiveCoeff=0
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
124 for m in r.metabolites:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
125 if r.get_coefficient(m.id)>0:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
126 positiveCoeff=1;
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
127 if (positiveCoeff==0 and r.lower_bound<0):
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
128 trueMedium.append(r.id)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
129
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
130 df_medium = pd.DataFrame()
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
131 df_medium["reaction"] = trueMedium
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
132 return df_medium
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
133
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
134 def generate_bounds(model:cobra.Model) -> pd.DataFrame:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
135
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
136 rxns = []
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
137 for reaction in model.reactions:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
138 rxns.append(reaction.id)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
139
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
140 bounds = pd.DataFrame(columns = ["lower_bound", "upper_bound"], index=rxns)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
141
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
142 for reaction in model.reactions:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
143 bounds.loc[reaction.id] = [reaction.lower_bound, reaction.upper_bound]
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
144 return bounds
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
145
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
146
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
147 ###############################- FILE SAVING -################################
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
148 def save_as_csv_filePath(data :dict, file_path :utils.FilePath, fieldNames :Tuple[str, str]) -> None:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
149 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
150 Saves any dictionary-shaped data in a .csv file created at the given file_path as FilePath.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
151
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
152 Args:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
153 data : the data to be written to the file.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
154 file_path : the path to the .csv file.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
155 fieldNames : the names of the fields (columns) in the .csv file.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
156
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
157 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
158 None
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
159 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
160 with open(file_path.show(), 'w', newline='') as csvfile:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
161 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
162 writer.writeheader()
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
163
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
164 for key, value in data.items():
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
165 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
166
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
167 def save_as_csv(data :dict, file_path :str, fieldNames :Tuple[str, str]) -> None:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
168 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
169 Saves any dictionary-shaped data in a .csv file created at the given file_path as string.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
170
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
171 Args:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
172 data : the data to be written to the file.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
173 file_path : the path to the .csv file.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
174 fieldNames : the names of the fields (columns) in the .csv file.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
175
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
176 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
177 None
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
178 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
179 with open(file_path, 'w', newline='') as csvfile:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
180 writer = csv.DictWriter(csvfile, fieldnames = fieldNames, dialect="excel-tab")
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
181 writer.writeheader()
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
182
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
183 for key, value in data.items():
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
184 writer.writerow({ fieldNames[0] : key, fieldNames[1] : value })
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
185
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
186 ###############################- ENTRY POINT -################################
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
187 def main() -> None:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
188 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
189 Initializes everything and sets the program in motion based on the fronted input arguments.
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
190
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
191 Returns:
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
192 None
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
193 """
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
194 # get args from frontend (related xml)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
195 global ARGS
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
196 ARGS = process_args()
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
197
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
198 # this is the worst thing I've seen so far, congrats to the former MaREA devs for suggesting this!
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
199 if os.path.isdir(ARGS.out_dir) == False: os.makedirs(ARGS.out_dir)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
200
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
201 # load custom model
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
202 model = load_custom_model(
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
203 utils.FilePath.fromStrPath(ARGS.input), utils.FilePath.fromStrPath(ARGS.name).ext)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
204
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
205 # generate data
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
206 rules = generate_rules(model, asParsed = False)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
207 reactions = generate_reactions(model, asParsed = False)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
208 bounds = generate_bounds(model)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
209 medium = get_medium(model)
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
210
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
211 # save files out of collection: path coming from xml
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
212 save_as_csv(rules, ARGS.out_rules, ("ReactionID", "Rule"))
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
213 save_as_csv(reactions, ARGS.out_reactions, ("ReactionID", "Reaction"))
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
214 bounds.to_csv(ARGS.out_bounds, sep = '\t')
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
215 medium.to_csv(ARGS.out_medium, sep = '\t')
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
216
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
217 if __name__ == '__main__':
7e703e546998 Uploaded
luca_milaz
parents:
diff changeset
218 main()