|
228
|
1 import argparse
|
|
|
2 import utils.general_utils as utils
|
|
|
3 from typing import Optional, List
|
|
|
4 import os
|
|
|
5 import numpy as np
|
|
|
6 import pandas as pd
|
|
|
7 import cobra
|
|
|
8 import utils.CBS_backend as CBS_backend
|
|
|
9 from joblib import Parallel, delayed, cpu_count
|
|
|
10 from cobra.sampling import OptGPSampler
|
|
|
11 import sys
|
|
|
12
|
|
|
13 ################################# process args ###############################
|
|
|
14 def process_args(args :List[str]) -> argparse.Namespace:
|
|
|
15 """
|
|
|
16 Processes command-line arguments.
|
|
|
17
|
|
|
18 Args:
|
|
|
19 args (list): List of command-line arguments.
|
|
|
20
|
|
|
21 Returns:
|
|
|
22 Namespace: An object containing parsed arguments.
|
|
|
23 """
|
|
|
24 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
|
|
|
25 description = 'process some value\'s')
|
|
|
26
|
|
|
27 parser.add_argument('-ol', '--out_log',
|
|
|
28 help = "Output log")
|
|
|
29
|
|
|
30 parser.add_argument('-td', '--tool_dir',
|
|
|
31 type = str,
|
|
|
32 required = True,
|
|
|
33 help = 'your tool directory')
|
|
|
34
|
|
|
35
|
|
|
36 parser.add_argument('-in', '--input',
|
|
|
37 required = True,
|
|
|
38 type=str,
|
|
|
39 help = 'inputs model')
|
|
|
40
|
|
|
41 parser.add_argument('-nm', '--name',
|
|
|
42 required = True,
|
|
|
43 type=str,
|
|
|
44 help = 'inputs model ids')
|
|
|
45
|
|
|
46 parser.add_argument('-a', '--algorithm',
|
|
|
47 type = str,
|
|
|
48 choices = ['OPTGP', 'CBS'],
|
|
|
49 required = True,
|
|
|
50 help = 'choose sampling algorithm')
|
|
|
51
|
|
|
52 parser.add_argument('-th', '--thinning',
|
|
|
53 type = int,
|
|
|
54 default= 100,
|
|
|
55 required=False,
|
|
|
56 help = 'choose thinning')
|
|
|
57
|
|
|
58 parser.add_argument('-ns', '--n_samples',
|
|
|
59 type = int,
|
|
|
60 required = True,
|
|
|
61 help = 'choose how many samples')
|
|
|
62
|
|
|
63 parser.add_argument('-sd', '--seed',
|
|
|
64 type = int,
|
|
|
65 required = True,
|
|
|
66 help = 'seed')
|
|
|
67
|
|
|
68 parser.add_argument('-nb', '--n_batches',
|
|
|
69 type = int,
|
|
|
70 required = True,
|
|
|
71 help = 'choose how many batches')
|
|
|
72
|
|
|
73 parser.add_argument('-ot', '--output_type',
|
|
|
74 type = str,
|
|
|
75 required = True,
|
|
|
76 help = 'output type')
|
|
|
77
|
|
|
78 ARGS = parser.parse_args()
|
|
|
79 return ARGS
|
|
|
80
|
|
|
81 ########################### warning ###########################################
|
|
|
82 def warning(s :str) -> None:
|
|
|
83 """
|
|
|
84 Log a warning message to an output log file and print it to the console.
|
|
|
85
|
|
|
86 Args:
|
|
|
87 s (str): The warning message to be logged and printed.
|
|
|
88
|
|
|
89 Returns:
|
|
|
90 None
|
|
|
91 """
|
|
|
92 with open(ARGS.out_log, 'a') as log:
|
|
|
93 log.write(s + "\n\n")
|
|
|
94 print(s)
|
|
|
95
|
|
|
96
|
|
|
97 def write_to_file(dataset: pd.DataFrame, name: str, keep_index:bool=False)->None:
|
|
|
98 dataset.to_csv(ARGS.output_folder + name + ".csv", sep = '\t', index = keep_index)
|
|
|
99
|
|
|
100
|
|
|
101
|
|
|
102 def OPTGP_sampler(model:cobra.Model, model_name:str, n_samples:int=1000, thinning:int=100, n_batches:int=1, seed:int=0)-> None:
|
|
|
103
|
|
|
104 for i in range(0, n_batches):
|
|
|
105 optgp = OptGPSampler(model, thinning, seed)
|
|
|
106 samples = optgp.sample(n_samples)
|
|
|
107 samples.to_csv(ARGS.output_folder + model_name + '_'+ str(i)+'_OPTGP.csv', index=False)
|
|
|
108 seed+=1
|
|
|
109 samplesTotal = pd.DataFrame()
|
|
|
110 for i in range(0, n_batches):
|
|
|
111 samples_batch = pd.read_csv(ARGS.output_folder + model_name + '_'+ str(i)+'_OPTGP.csv')
|
|
|
112 samplesTotal = pd.concat([samplesTotal, samples_batch], ignore_index = True)
|
|
|
113
|
|
|
114 write_to_file(samplesTotal, model_name)
|
|
|
115
|
|
|
116 for i in range(0, n_batches):
|
|
|
117 os.remove(ARGS.output_folder + model_name + '_'+ str(i)+'_OPTGP.csv')
|
|
|
118 pass
|
|
|
119
|
|
|
120
|
|
|
121 def CBS_sampler(model:cobra.Model, model_name:str, n_samples:int=1000, n_batches:int=1, seed:int=0)-> None:
|
|
|
122
|
|
|
123 df_FVA = cobra.flux_analysis.flux_variability_analysis(model,fraction_of_optimum=0).round(6)
|
|
|
124
|
|
|
125 df_coefficients = CBS_backend.randomObjectiveFunction(model, n_samples*n_batches, df_FVA, seed=seed)
|
|
|
126
|
|
|
127 for i in range(0, n_batches):
|
|
|
128 samples = pd.DataFrame(columns =[reaction.id for reaction in model.reactions], index = range(n_samples))
|
|
|
129 try:
|
|
|
130 CBS_backend.randomObjectiveFunctionSampling(model, n_samples, df_coefficients.iloc[:,i*n_samples:(i+1)*n_samples], samples)
|
|
|
131 except Exception as e:
|
|
|
132 utils.logWarning(
|
|
|
133 "Warning: GLPK solver has failed for " + model_name + ". Trying with COBRA interface. Error:" + str(e),
|
|
|
134 ARGS.out_log)
|
|
|
135 CBS_backend.randomObjectiveFunctionSampling_cobrapy(model, n_samples, df_coefficients.iloc[:,i*n_samples:(i+1)*n_samples],
|
|
|
136 samples)
|
|
|
137 samples.to_csv(ARGS.output_folder + model_name + '_'+ str(i)+'_CBS.csv', index=False)
|
|
|
138
|
|
|
139 samplesTotal = pd.DataFrame()
|
|
|
140 for i in range(0, n_batches):
|
|
|
141 samples_batch = pd.read_csv(ARGS.output_folder + model_name + '_'+ str(i)+'_CBS.csv')
|
|
|
142 samplesTotal = pd.concat([samplesTotal, samples_batch], ignore_index = True)
|
|
|
143
|
|
|
144 write_to_file(samplesTotal, model_name)
|
|
|
145
|
|
|
146 for i in range(0, n_batches):
|
|
|
147 os.remove(ARGS.output_folder + model_name + '_'+ str(i)+'_CBS.csv')
|
|
|
148 pass
|
|
|
149
|
|
|
150
|
|
|
151 def model_sampler(model_input:str, model_name:str)-> List[pd.DataFrame]:
|
|
|
152
|
|
|
153 model = load_custom_model(
|
|
|
154 utils.FilePath.fromStrPath(model_input), utils.FilePath.fromStrPath(model_name).ext)
|
|
|
155
|
|
|
156 utils.logWarning(
|
|
|
157 "Sampling model: " + model_name,
|
|
|
158 ARGS.out_log)
|
|
|
159
|
|
|
160 name = model_name.split('.')[0]
|
|
|
161
|
|
|
162 if ARGS.algorithm == 'OPTGP':
|
|
|
163 OPTGP_sampler(model, name, ARGS.n_samples, ARGS.thinning, ARGS.n_batches, ARGS.seed)
|
|
|
164
|
|
|
165 elif ARGS.algorithm == 'CBS':
|
|
|
166 CBS_sampler(model, name, ARGS.n_samples, ARGS.n_batches, ARGS.seed)
|
|
|
167
|
|
|
168 df_mean, df_median, df_quantiles = fluxes_statistics(name, ARGS.output_types)
|
|
|
169
|
|
|
170 if("fluxes" not in ARGS.output_types):
|
|
|
171 os.remove(ARGS.output_folder + name + '.csv')
|
|
|
172
|
|
|
173 return df_mean, df_median, df_quantiles
|
|
|
174
|
|
|
175 def fluxes_statistics(model_name: str, output_types:List)-> List[pd.DataFrame]:
|
|
|
176
|
|
|
177 df_mean = pd.DataFrame()
|
|
|
178 df_median= pd.DataFrame()
|
|
|
179 df_quantiles= pd.DataFrame()
|
|
|
180
|
|
|
181 df_samples = pd.read_csv(ARGS.output_folder + model_name + '.csv', sep = '\t')
|
|
|
182 for output_type in output_types:
|
|
|
183 if(output_type == "mean"):
|
|
|
184 df_mean = df_samples.mean()
|
|
|
185 df_mean = df_mean.to_frame().T
|
|
|
186 df_mean = df_mean.reset_index(drop=True)
|
|
|
187 df_mean.index = [model_name]
|
|
|
188 elif(output_type == "median"):
|
|
|
189 df_median = df_samples.median()
|
|
|
190 df_median = df_median.to_frame().T
|
|
|
191 df_median = df_median.reset_index(drop=True)
|
|
|
192 df_median.index = [model_name]
|
|
|
193 elif(output_type == "quantiles"):
|
|
|
194 df_quantile = df_samples.quantile([0.25, 0.5, 0.75])
|
|
|
195 newRow = []
|
|
|
196 cols = []
|
|
|
197 for rxn in df_quantile.columns:
|
|
|
198 newRow.append(df_quantile[rxn].loc[0.25])
|
|
|
199 cols.append(rxn + "_q1")
|
|
|
200 newRow.append(df_quantile[rxn].loc[0.5])
|
|
|
201 cols.append(rxn + "_q2")
|
|
|
202 newRow.append(df_quantile[rxn].loc[0.75])
|
|
|
203 cols.append(rxn + "_q3")
|
|
|
204 df_quantiles = pd.DataFrame(columns=cols)
|
|
|
205 df_quantiles.loc[0] = newRow
|
|
|
206 df_quantiles = df_quantiles.reset_index(drop=True)
|
|
|
207 df_quantiles.index = [model_name]
|
|
|
208
|
|
|
209 return df_mean, df_median, df_quantiles
|
|
|
210
|
|
|
211
|
|
|
212 ################################- INPUT DATA LOADING -################################
|
|
|
213 def load_custom_model(file_path :utils.FilePath, ext :Optional[utils.FileFormat] = None) -> cobra.Model:
|
|
|
214 """
|
|
|
215 Loads a custom model from a file, either in JSON or XML format.
|
|
|
216
|
|
|
217 Args:
|
|
|
218 file_path : The path to the file containing the custom model.
|
|
|
219 ext : explicit file extension. Necessary for standard use in galaxy because of its weird behaviour.
|
|
|
220
|
|
|
221 Raises:
|
|
|
222 DataErr : if the file is in an invalid format or cannot be opened for whatever reason.
|
|
|
223
|
|
|
224 Returns:
|
|
|
225 cobra.Model : the model, if successfully opened.
|
|
|
226 """
|
|
|
227 ext = ext if ext else file_path.ext
|
|
|
228 try:
|
|
|
229 if ext is utils.FileFormat.XML:
|
|
|
230 return cobra.io.read_sbml_model(file_path.show())
|
|
|
231
|
|
|
232 if ext is utils.FileFormat.JSON:
|
|
|
233 return cobra.io.load_json_model(file_path.show())
|
|
|
234
|
|
|
235 except Exception as e: raise utils.DataErr(file_path, e.__str__())
|
|
|
236 raise utils.DataErr(file_path,
|
|
|
237 f"Fomat \"{file_path.ext}\" is not recognized, only JSON and XML files are supported.")
|
|
|
238
|
|
|
239 ############################# main ###########################################
|
|
|
240 def main() -> None:
|
|
|
241 """
|
|
|
242 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
|
243
|
|
|
244 Returns:
|
|
|
245 None
|
|
|
246 """
|
|
|
247 if not os.path.exists('flux_sampling'):
|
|
|
248 os.makedirs('flux_sampling')
|
|
|
249
|
|
|
250 num_processors = cpu_count()
|
|
|
251
|
|
|
252 global ARGS
|
|
|
253 ARGS = process_args(sys.argv)
|
|
|
254
|
|
|
255 ARGS.output_folder = 'flux_sampling/'
|
|
|
256
|
|
|
257 utils.logWarning(
|
|
|
258 ARGS.output_type,
|
|
|
259 ARGS.out_log)
|
|
|
260
|
|
|
261 models_input = ARGS.input.split(",")
|
|
|
262 models_name = ARGS.name.split(",")
|
|
|
263 ARGS.output_types = ARGS.output_type.split(",")
|
|
|
264
|
|
|
265
|
|
|
266 results = Parallel(n_jobs=num_processors)(delayed(model_sampler)(model_input, model_name) for model_input, model_name in zip(models_input, models_name))
|
|
|
267
|
|
|
268 all_mean = pd.concat([result[0] for result in results], ignore_index=False)
|
|
|
269 all_median = pd.concat([result[1] for result in results], ignore_index=False)
|
|
|
270 all_quantiles = pd.concat([result[2] for result in results], ignore_index=False)
|
|
|
271
|
|
|
272 if("mean" in ARGS.output_types):
|
|
|
273 all_mean = all_mean.fillna(0.0)
|
|
|
274 all_mean = all_mean.sort_index()
|
|
|
275 write_to_file(all_mean, "mean", True)
|
|
|
276
|
|
|
277 if("median" in ARGS.output_types):
|
|
|
278 all_median = all_median.fillna(0.0)
|
|
|
279 all_median = all_median.sort_index()
|
|
|
280 write_to_file(all_median, "median", True)
|
|
|
281
|
|
|
282 if("quantiles" in ARGS.output_types):
|
|
|
283 all_quantiles = all_quantiles.fillna(0.0)
|
|
|
284 all_quantiles = all_quantiles.sort_index()
|
|
|
285 write_to_file(all_quantiles, "quantiles", True)
|
|
|
286 pass
|
|
|
287
|
|
|
288 ##############################################################################
|
|
|
289 if __name__ == "__main__":
|
|
|
290 main() |