4
|
1 import math
|
|
2 import argparse
|
|
3
|
|
4 import numpy as np
|
|
5 import pickle as pk
|
|
6 import pandas as pd
|
|
7
|
293
|
8 from typing import Optional, List, Dict
|
4
|
9
|
|
10 import utils.general_utils as utils
|
|
11 import utils.reaction_parsing as reactionUtils
|
|
12
|
|
13 ########################## argparse ##########################################
|
|
14 ARGS :argparse.Namespace
|
147
|
15 def process_args(args:List[str] = None) -> argparse.Namespace:
|
4
|
16 """
|
|
17 Processes command-line arguments.
|
|
18
|
|
19 Args:
|
|
20 args (list): List of command-line arguments.
|
|
21
|
|
22 Returns:
|
|
23 Namespace: An object containing parsed arguments.
|
|
24 """
|
|
25 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
|
|
26 description = 'process some value\'s'+
|
|
27 ' abundances and reactions to create RPS scores.')
|
|
28 parser.add_argument('-rc', '--reaction_choice',
|
|
29 type = str,
|
|
30 default = 'default',
|
|
31 choices = ['default','custom'],
|
|
32 help = 'chose which type of reaction dataset you want use')
|
|
33 parser.add_argument('-cm', '--custom',
|
|
34 type = str,
|
|
35 help='your dataset if you want custom reactions')
|
|
36 parser.add_argument('-td', '--tool_dir',
|
|
37 type = str,
|
|
38 required = True,
|
|
39 help = 'your tool directory')
|
|
40 parser.add_argument('-ol', '--out_log',
|
|
41 help = "Output log")
|
|
42 parser.add_argument('-id', '--input',
|
|
43 type = str,
|
293
|
44 required = True,
|
4
|
45 help = 'input dataset')
|
|
46 parser.add_argument('-rp', '--rps_output',
|
|
47 type = str,
|
|
48 required = True,
|
|
49 help = 'rps output')
|
|
50
|
147
|
51 args = parser.parse_args(args)
|
4
|
52 return args
|
|
53
|
|
54 ############################ dataset name #####################################
|
|
55 def name_dataset(name_data :str, count :int) -> str:
|
|
56 """
|
|
57 Produces a unique name for a dataset based on what was provided by the user. The default name for any dataset is "Dataset", thus if the user didn't change it this function appends f"_{count}" to make it unique.
|
|
58
|
|
59 Args:
|
|
60 name_data : name associated with the dataset (from frontend input params)
|
|
61 count : counter from 1 to make these names unique (external)
|
|
62
|
|
63 Returns:
|
|
64 str : the name made unique
|
|
65 """
|
|
66 if str(name_data) == 'Dataset':
|
|
67 return str(name_data) + '_' + str(count)
|
|
68 else:
|
|
69 return str(name_data)
|
|
70
|
|
71 ############################ get_abund_data ####################################
|
|
72 def get_abund_data(dataset: pd.DataFrame, cell_line_index:int) -> Optional[pd.Series]:
|
|
73 """
|
|
74 Extracts abundance data and turns it into a series for a specific cell line from the dataset, which rows are
|
|
75 metabolites and columns are cell lines.
|
|
76
|
|
77 Args:
|
|
78 dataset (pandas.DataFrame): The DataFrame containing abundance data for all cell lines and metabolites.
|
|
79 cell_line_index (int): The index of the cell line of interest in the dataset.
|
|
80
|
|
81 Returns:
|
|
82 pd.Series or None: A series containing abundance values for the specified cell line.
|
|
83 The name of the series is the name of the cell line.
|
|
84 Returns None if the cell index is invalid.
|
|
85 """
|
|
86 if cell_line_index < 0 or cell_line_index >= len(dataset.index):
|
|
87 print(f"Errore: This cell line index: '{cell_line_index}' is not valid.")
|
|
88 return None
|
|
89
|
|
90 cell_line_name = dataset.columns[cell_line_index]
|
|
91 abundances_series = dataset[cell_line_name][1:]
|
|
92
|
|
93 return abundances_series
|
|
94
|
|
95 ############################ clean_metabolite_name ####################################
|
|
96 def clean_metabolite_name(name :str) -> str:
|
|
97 """
|
|
98 Removes some characters from a metabolite's name, provided as input, and makes it lowercase in order to simplify
|
|
99 the search of a match in the dictionary of synonyms.
|
|
100
|
|
101 Args:
|
|
102 name : the metabolite's name, as given in the dataset.
|
|
103
|
|
104 Returns:
|
|
105 str : a new string with the cleaned name.
|
|
106 """
|
|
107 return "".join(ch for ch in name if ch not in ",;-_'([{ }])").lower()
|
|
108
|
|
109 ############################ get_metabolite_id ####################################
|
|
110 def get_metabolite_id(name :str, syn_dict :Dict[str, List[str]]) -> str:
|
|
111 """
|
|
112 Looks through a dictionary of synonyms to find a match for a given metabolite's name.
|
|
113
|
|
114 Args:
|
|
115 name : the metabolite's name, as given in the dataset.
|
|
116 syn_dict : the dictionary of synonyms, using unique identifiers as keys and lists of clean synonyms as values.
|
|
117
|
|
118 Returns:
|
|
119 str : the internal :str unique identifier of that metabolite, used in all other parts of the model in use.
|
|
120 An empty string is returned if a match isn't found.
|
|
121 """
|
|
122 name = clean_metabolite_name(name)
|
|
123 for id, synonyms in syn_dict.items():
|
|
124 if name in synonyms: return id
|
|
125
|
|
126 return ""
|
|
127
|
|
128 ############################ check_missing_metab ####################################
|
|
129 def check_missing_metab(reactions: Dict[str, Dict[str, int]], dataset_by_rows: Dict[str, List[float]], cell_lines_amt :int) -> List[str]:
|
|
130 """
|
|
131 Check for missing metabolites in the abundances dictionary compared to the reactions dictionary and update abundances accordingly.
|
|
132
|
|
133 Parameters:
|
|
134 reactions (dict): A dictionary representing reactions where keys are reaction names and values are dictionaries containing metabolite names as keys and stoichiometric coefficients as values.
|
|
135 dataset_by_rows (dict): A dictionary representing abundances where keys are metabolite names and values are their corresponding abundances for all cell lines.
|
|
136 cell_lines_amt : amount of cell lines, needed to add a new list of abundances for missing metabolites.
|
|
137
|
|
138 Returns:
|
|
139 list[str] : list of metabolite names that were missing in the original abundances dictionary and thus their aboundances were set to 1.
|
|
140
|
|
141 Side effects:
|
|
142 dataset_by_rows : mut
|
|
143 """
|
|
144 missing_list = []
|
|
145 for reaction in reactions.values():
|
|
146 for metabolite in reaction.keys():
|
|
147 if metabolite not in dataset_by_rows:
|
|
148 dataset_by_rows[metabolite] = [1] * cell_lines_amt
|
|
149 missing_list.append(metabolite)
|
|
150
|
|
151 return missing_list
|
|
152
|
|
153 ############################ calculate_rps ####################################
|
293
|
154 def calculate_rps(reactions: Dict[str, Dict[str, int]], abundances: Dict[str, float], black_list: List[str], missing_list: List[str], substrateFreqTable: Dict[str, int]) -> Dict[str, float]:
|
4
|
155 """
|
|
156 Calculate the Reaction Propensity scores (RPS) based on the availability of reaction substrates, for (ideally) each input model reaction and for each sample.
|
|
157 The score is computed as the product of the concentrations of the reacting substances, with each concentration raised to a power equal to its stoichiometric coefficient
|
293
|
158 for each reaction using the provided coefficient and abundance values. The value is then normalized, based on how frequent the metabolite is in the selected model's reactions,
|
|
159 and log-transformed.
|
4
|
160
|
|
161 Parameters:
|
|
162 reactions (dict): A dictionary representing reactions where keys are reaction names and values are dictionaries containing metabolite names as keys and stoichiometric coefficients as values.
|
|
163 abundances (dict): A dictionary representing metabolite abundances where keys are metabolite names and values are their corresponding abundances.
|
|
164 black_list (list): A list containing metabolite names that should be excluded from the RPS calculation.
|
|
165 missing_list (list): A list containing metabolite names that were missing in the original abundances dictionary and thus their values were set to 1.
|
293
|
166 substrateFreqTable (dict): A dictionary where each metabolite name (key) is associated with how many times it shows up in the model's reactions (value).
|
|
167
|
4
|
168 Returns:
|
|
169 dict: A dictionary containing Reaction Propensity Scores (RPS) where keys are reaction names and values are the corresponding RPS scores.
|
|
170 """
|
|
171 rps_scores = {}
|
293
|
172
|
4
|
173 for reaction_name, substrates in reactions.items():
|
|
174 total_contribution = 1
|
293
|
175 metab_significant = False
|
4
|
176 for metabolite, stoichiometry in substrates.items():
|
293
|
177 abundance = 1 if math.isnan(abundances[metabolite]) else abundances[metabolite]
|
4
|
178 if metabolite not in black_list and metabolite not in missing_list:
|
293
|
179 metab_significant = True
|
|
180
|
|
181 total_contribution += math.log((abundance + np.finfo(float).eps) / substrateFreqTable[metabolite]) * stoichiometry
|
4
|
182
|
|
183 rps_scores[reaction_name] = total_contribution if metab_significant else math.nan
|
|
184
|
|
185 return rps_scores
|
|
186
|
|
187 ############################ rps_for_cell_lines ####################################
|
293
|
188 def rps_for_cell_lines(dataset: List[List[str]], reactions: Dict[str, Dict[str, int]], black_list: List[str], syn_dict: Dict[str, List[str]], substrateFreqTable: Dict[str, int]) -> None:
|
4
|
189 """
|
|
190 Calculate Reaction Propensity Scores (RPS) for each cell line represented in the dataframe and creates an output file.
|
|
191
|
|
192 Parameters:
|
|
193 dataset : the dataset's data, by rows
|
|
194 reactions (dict): A dictionary representing reactions where keys are reaction names and values are dictionaries containing metabolite names as keys and stoichiometric coefficients as values.
|
|
195 black_list (list): A list containing metabolite names that should be excluded from the RPS calculation.
|
|
196 syn_dict (dict): A dictionary where keys are general metabolite names and values are lists of possible synonyms.
|
293
|
197 substrateFreqTable (dict): A dictionary where each metabolite name (key) is associated with how many times it shows up in the model's reactions (value).
|
4
|
198
|
|
199 Returns:
|
|
200 None
|
|
201 """
|
|
202 cell_lines = dataset[0][1:]
|
|
203 abundances_dict = {}
|
|
204
|
|
205 translationIsApplied = ARGS.reaction_choice == "default"
|
|
206 for row in dataset[1:]:
|
|
207 id = get_metabolite_id(row[0], syn_dict) if translationIsApplied else row[0]
|
|
208 if id: abundances_dict[id] = list(map(utils.Float(), row[1:]))
|
|
209
|
|
210 missing_list = check_missing_metab(reactions, abundances_dict, len((cell_lines)))
|
|
211
|
|
212 rps_scores :Dict[Dict[str, float]] = {}
|
|
213 for pos, cell_line_name in enumerate(cell_lines):
|
|
214 abundances = { metab : abundances[pos] for metab, abundances in abundances_dict.items() }
|
293
|
215 rps_scores[cell_line_name] = calculate_rps(reactions, abundances, black_list, missing_list, substrateFreqTable)
|
4
|
216
|
|
217 df = pd.DataFrame.from_dict(rps_scores)
|
293
|
218
|
281
|
219 df.index.name = 'Reactions'
|
|
220 df.to_csv(ARGS.rps_output, sep='\t', na_rep='None', index=True)
|
|
221
|
4
|
222 ############################ main ####################################
|
147
|
223 def main(args:List[str] = None) -> None:
|
4
|
224 """
|
|
225 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
226
|
|
227 Returns:
|
|
228 None
|
|
229 """
|
|
230 global ARGS
|
147
|
231 ARGS = process_args(args)
|
4
|
232
|
|
233 # TODO:use utils functions vvv
|
|
234 with open(ARGS.tool_dir + '/local/pickle files/black_list.pickle', 'rb') as bl:
|
|
235 black_list = pk.load(bl)
|
|
236
|
|
237 with open(ARGS.tool_dir + '/local/pickle files/synonyms.pickle', 'rb') as sd:
|
|
238 syn_dict = pk.load(sd)
|
|
239
|
|
240 dataset = utils.readCsv(utils.FilePath.fromStrPath(ARGS.input), '\t', skipHeader = False)
|
|
241
|
|
242 if ARGS.reaction_choice == 'default':
|
|
243 reactions = pk.load(open(ARGS.tool_dir + '/local/pickle files/reactions.pickle', 'rb'))
|
293
|
244 substrateFreqTable = pk.load(open(ARGS.tool_dir + '/local/pickle files/substrate_frequencies.pickle', 'rb'))
|
4
|
245
|
|
246 elif ARGS.reaction_choice == 'custom':
|
|
247 reactions = reactionUtils.parse_custom_reactions(ARGS.custom)
|
293
|
248 substrateFreqTable = {}
|
|
249 for _, substrates in reactions.items():
|
|
250 for substrateName, _ in substrates.items():
|
|
251 if substrateName not in substrateFreqTable: substrateFreqTable[substrateName] = 0
|
|
252 substrateFreqTable[substrateName] += 1
|
|
253
|
|
254 rps_for_cell_lines(dataset, reactions, black_list, syn_dict, substrateFreqTable)
|
4
|
255 print('Execution succeded')
|
|
256
|
|
257 ##############################################################################
|
293
|
258 if __name__ == "__main__": main() |