annotate COBRAxy/custom_data_generator.py @ 200:20f2a6fd6b1a draft

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