annotate COBRAxy/custom_data_generator.py @ 25:80bfd8743ea6 draft

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