4
|
1 from __future__ import division
|
|
2 # galaxy complains this ^^^ needs to be at the very beginning of the file, for some reason.
|
|
3 import sys
|
|
4 import argparse
|
|
5 import collections
|
|
6 import pandas as pd
|
|
7 import pickle as pk
|
|
8 import utils.general_utils as utils
|
|
9 import utils.rule_parsing as ruleUtils
|
|
10 from typing import Union, Optional, List, Dict, Tuple, TypeVar
|
|
11
|
|
12 ERRORS = []
|
|
13 ########################## argparse ##########################################
|
|
14 ARGS :argparse.Namespace
|
|
15 def process_args() -> argparse.Namespace:
|
|
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(
|
|
26 usage = '%(prog)s [options]',
|
|
27 description = "process some value's genes to create a comparison's map.")
|
|
28
|
|
29 parser.add_argument(
|
|
30 '-rs', '--rules_selector',
|
|
31 type = utils.Model, default = utils.Model.HMRcore, choices = list(utils.Model),
|
|
32 help = 'chose which type of dataset you want use')
|
|
33
|
|
34 parser.add_argument("-rl", "--rule_list", type = str,
|
|
35 help = "path to input file with custom rules, if provided")
|
|
36
|
|
37 parser.add_argument("-rn", "--rules_name", type = str, help = "custom rules name")
|
|
38 # ^ I need this because galaxy converts my files into .dat but I need to know what extension they were in
|
|
39
|
|
40 parser.add_argument(
|
|
41 '-n', '--none',
|
|
42 type = utils.Bool("none"), default = True,
|
|
43 help = 'compute Nan values')
|
|
44
|
|
45 parser.add_argument(
|
|
46 '-td', '--tool_dir',
|
|
47 type = str,
|
|
48 required = True, help = 'your tool directory')
|
|
49
|
|
50 parser.add_argument(
|
|
51 '-ol', '--out_log',
|
|
52 type = str,
|
|
53 help = "Output log")
|
|
54
|
|
55 parser.add_argument(
|
|
56 '-in', '--input', #id รจ diventato in
|
|
57 type = str,
|
|
58 help = 'input dataset')
|
|
59
|
|
60 parser.add_argument(
|
|
61 '-ra', '--ras_output',
|
|
62 type = str,
|
|
63 required = True, help = 'ras output')
|
|
64
|
|
65 return parser.parse_args()
|
|
66
|
|
67 ############################ dataset input ####################################
|
|
68 def read_dataset(data :str, name :str) -> pd.DataFrame:
|
|
69 """
|
|
70 Read a dataset from a CSV file and return it as a pandas DataFrame.
|
|
71
|
|
72 Args:
|
|
73 data (str): Path to the CSV file containing the dataset.
|
|
74 name (str): Name of the dataset, used in error messages.
|
|
75
|
|
76 Returns:
|
|
77 pandas.DataFrame: DataFrame containing the dataset.
|
|
78
|
|
79 Raises:
|
|
80 pd.errors.EmptyDataError: If the CSV file is empty.
|
|
81 sys.exit: If the CSV file has the wrong format, the execution is aborted.
|
|
82 """
|
|
83 try:
|
|
84 dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python')
|
|
85 except pd.errors.EmptyDataError:
|
|
86 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
87 if len(dataset.columns) < 2:
|
|
88 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
89 return dataset
|
|
90
|
|
91 ############################ load id e rules ##################################
|
|
92 def load_id_rules(reactions :Dict[str, Dict[str, List[str]]]) -> Tuple[List[str], List[Dict[str, List[str]]]]:
|
|
93 """
|
|
94 Load IDs and rules from a dictionary of reactions.
|
|
95
|
|
96 Args:
|
|
97 reactions (dict): A dictionary where keys are IDs and values are rules.
|
|
98
|
|
99 Returns:
|
|
100 tuple: A tuple containing two lists, the first list containing IDs and the second list containing rules.
|
|
101 """
|
|
102 ids, rules = [], []
|
|
103 for key, value in reactions.items():
|
|
104 ids.append(key)
|
|
105 rules.append(value)
|
|
106 return (ids, rules)
|
|
107
|
|
108 ############################ check_methods ####################################
|
|
109 def gene_type(l :str, name :str) -> str:
|
|
110 """
|
|
111 Determine the type of gene ID.
|
|
112
|
|
113 Args:
|
|
114 l (str): The gene identifier to check.
|
|
115 name (str): The name of the dataset, used in error messages.
|
|
116
|
|
117 Returns:
|
|
118 str: The type of gene ID ('hugo_id', 'ensembl_gene_id', 'symbol', or 'entrez_id').
|
|
119
|
|
120 Raises:
|
|
121 sys.exit: If the gene ID type is not supported, the execution is aborted.
|
|
122 """
|
|
123 if check_hgnc(l):
|
|
124 return 'hugo_id'
|
|
125 elif check_ensembl(l):
|
|
126 return 'ensembl_gene_id'
|
|
127 elif check_symbol(l):
|
|
128 return 'symbol'
|
|
129 elif check_entrez(l):
|
|
130 return 'entrez_id'
|
|
131 else:
|
|
132 sys.exit('Execution aborted:\n' +
|
|
133 'gene ID type in ' + name + ' not supported. Supported ID'+
|
|
134 'types are: HUGO ID, Ensemble ID, HUGO symbol, Entrez ID\n')
|
|
135
|
|
136 def check_hgnc(l :str) -> bool:
|
|
137 """
|
|
138 Check if a gene identifier follows the HGNC format.
|
|
139
|
|
140 Args:
|
|
141 l (str): The gene identifier to check.
|
|
142
|
|
143 Returns:
|
|
144 bool: True if the gene identifier follows the HGNC format, False otherwise.
|
|
145 """
|
|
146 if len(l) > 5:
|
|
147 if (l.upper()).startswith('HGNC:'):
|
|
148 return l[5:].isdigit()
|
|
149 else:
|
|
150 return False
|
|
151 else:
|
|
152 return False
|
|
153
|
|
154 def check_ensembl(l :str) -> bool:
|
|
155 """
|
|
156 Check if a gene identifier follows the Ensembl format.
|
|
157
|
|
158 Args:
|
|
159 l (str): The gene identifier to check.
|
|
160
|
|
161 Returns:
|
|
162 bool: True if the gene identifier follows the Ensembl format, False otherwise.
|
|
163 """
|
|
164 return l.upper().startswith('ENS')
|
|
165
|
|
166
|
|
167 def check_symbol(l :str) -> bool:
|
|
168 """
|
|
169 Check if a gene identifier follows the symbol format.
|
|
170
|
|
171 Args:
|
|
172 l (str): The gene identifier to check.
|
|
173
|
|
174 Returns:
|
|
175 bool: True if the gene identifier follows the symbol format, False otherwise.
|
|
176 """
|
|
177 if len(l) > 0:
|
|
178 if l[0].isalpha() and l[1:].isalnum():
|
|
179 return True
|
|
180 else:
|
|
181 return False
|
|
182 else:
|
|
183 return False
|
|
184
|
|
185 def check_entrez(l :str) -> bool:
|
|
186 """
|
|
187 Check if a gene identifier follows the Entrez ID format.
|
|
188
|
|
189 Args:
|
|
190 l (str): The gene identifier to check.
|
|
191
|
|
192 Returns:
|
|
193 bool: True if the gene identifier follows the Entrez ID format, False otherwise.
|
|
194 """
|
|
195 if len(l) > 0:
|
|
196 return l.isdigit()
|
|
197 else:
|
|
198 return False
|
|
199
|
|
200 ############################ gene #############################################
|
|
201 def data_gene(gene: pd.DataFrame, type_gene: str, name: str, gene_custom: Optional[Dict[str, str]]) -> Dict[str, str]:
|
|
202 """
|
|
203 Process gene data to ensure correct formatting and handle duplicates.
|
|
204
|
|
205 Args:
|
|
206 gene (DataFrame): DataFrame containing gene data.
|
|
207 type_gene (str): Type of gene data (e.g., 'hugo_id', 'ensembl_gene_id', 'symbol', 'entrez_id').
|
|
208 name (str): Name of the dataset.
|
|
209 gene_custom (dict or None): Custom gene data dictionary if provided.
|
|
210
|
|
211 Returns:
|
|
212 dict: A dictionary containing gene data with gene IDs as keys and corresponding values.
|
|
213 """
|
|
214 args = process_args()
|
|
215 for i in range(len(gene)):
|
|
216 tmp = gene.iloc[i, 0]
|
|
217 gene.iloc[i, 0] = tmp.strip().split('.')[0]
|
|
218
|
|
219 gene_dup = [item for item, count in
|
|
220 collections.Counter(gene[gene.columns[0]]).items() if count > 1]
|
|
221 pat_dup = [item for item, count in
|
|
222 collections.Counter(list(gene.columns)).items() if count > 1]
|
|
223
|
|
224 if gene_dup:
|
|
225 if gene_custom == None:
|
|
226 if args.rules_selector == 'HMRcore':
|
|
227 gene_in_rule = pk.load(open(args.tool_dir + '/local/pickle files/HMRcore_genes.p', 'rb'))
|
|
228
|
|
229 elif args.rules_selector == 'Recon':
|
|
230 gene_in_rule = pk.load(open(args.tool_dir + '/local/pickle files/Recon_genes.p', 'rb'))
|
|
231
|
|
232 elif args.rules_selector == 'ENGRO2':
|
|
233 gene_in_rule = pk.load(open(args.tool_dir + '/local/pickle files/ENGRO2_genes.p', 'rb'))
|
|
234 gene_in_rule = gene_in_rule.get(type_gene)
|
|
235
|
|
236 else:
|
|
237 gene_in_rule = gene_custom
|
|
238 tmp = []
|
|
239 for i in gene_dup:
|
|
240 if gene_in_rule.get(i) == 'ok':
|
|
241 tmp.append(i)
|
|
242 if tmp:
|
|
243 sys.exit('Execution aborted because gene ID '
|
|
244 +str(tmp)+' in '+name+' is duplicated\n')
|
|
245
|
|
246 if pat_dup: utils.logWarning(f"Warning: duplicated label\n{pat_dup} in {name}", ARGS.out_log)
|
|
247 return (gene.set_index(gene.columns[0])).to_dict()
|
|
248
|
|
249 ############################ resolve ##########################################
|
|
250 def replace_gene_value(l :str, d :str) -> Tuple[Union[int, float], list]:
|
|
251 """
|
|
252 Replace gene identifiers with corresponding values from a dictionary.
|
|
253
|
|
254 Args:
|
|
255 l (str): String of gene identifier.
|
|
256 d (str): String corresponding to its value.
|
|
257
|
|
258 Returns:
|
|
259 tuple: A tuple containing two lists: the first list contains replaced values, and the second list contains any errors encountered during replacement.
|
|
260 """
|
|
261 tmp = []
|
|
262 err = []
|
|
263 while l:
|
|
264 if isinstance(l[0], list):
|
|
265 tmp_rules, tmp_err = replace_gene_value(l[0], d)
|
|
266 tmp.append(tmp_rules)
|
|
267 err.extend(tmp_err)
|
|
268 else:
|
|
269 value = replace_gene(l[0], d)
|
|
270 tmp.append(value)
|
|
271 if value == None:
|
|
272 err.append(l[0])
|
|
273 l = l[1:]
|
|
274 return (tmp, err)
|
|
275
|
|
276 def replace_gene(l :str, d :str) -> Union[int, float]:
|
|
277 """
|
|
278 Replace a single gene identifier with its corresponding value from a dictionary.
|
|
279
|
|
280 Args:
|
|
281 l (str): Gene identifier to replace.
|
|
282 d (str): String corresponding to its value.
|
|
283
|
|
284 Returns:
|
|
285 float/int: Corresponding value from the dictionary if found, None otherwise.
|
|
286
|
|
287 Raises:
|
|
288 sys.exit: If the value associated with the gene identifier is not valid.
|
|
289 """
|
|
290 if l =='and' or l == 'or':
|
|
291 return l
|
|
292 else:
|
|
293 value = d.get(l, None)
|
|
294 if not(value == None or isinstance(value, (int, float))):
|
|
295 sys.exit('Execution aborted: ' + value + ' value not valid\n')
|
|
296 return value
|
|
297
|
|
298 T = TypeVar("T", bound = Optional[Union[int, float]])
|
|
299 def computes(val1 :T, op :str, val2 :T, cn :bool) -> T:
|
|
300 """
|
|
301 Compute the RAS value between two value and an operator ('and' or 'or').
|
|
302
|
|
303 Args:
|
|
304 val1(Optional(Union[float, int])): First value.
|
|
305 op (str): Operator ('and' or 'or').
|
|
306 val2(Optional(Union[float, int])): Second value.
|
|
307 cn (bool): Control boolean value.
|
|
308
|
|
309 Returns:
|
|
310 Optional(Union[float, int]): Result of the computation.
|
|
311 """
|
|
312 if val1 != None and val2 != None:
|
|
313 if op == 'and':
|
|
314 return min(val1, val2)
|
|
315 else:
|
|
316 return val1 + val2
|
|
317 elif op == 'and':
|
|
318 if cn is True:
|
|
319 if val1 != None:
|
|
320 return val1
|
|
321 elif val2 != None:
|
|
322 return val2
|
|
323 else:
|
|
324 return None
|
|
325 else:
|
|
326 return None
|
|
327 else:
|
|
328 if val1 != None:
|
|
329 return val1
|
|
330 elif val2 != None:
|
|
331 return val2
|
|
332 else:
|
|
333 return None
|
|
334
|
|
335 # ris should be Literal[None] but Literal is not supported in Python 3.7
|
|
336 def control(ris, l :List[Union[int, float, list]], cn :bool) -> Union[bool, int, float]: #Union[Literal[False], int, float]:
|
|
337 """
|
|
338 Control the format of the expression.
|
|
339
|
|
340 Args:
|
|
341 ris: Intermediate result.
|
|
342 l (list): Expression to control.
|
|
343 cn (bool): Control boolean value.
|
|
344
|
|
345 Returns:
|
|
346 Union[Literal[False], int, float]: Result of the control.
|
|
347 """
|
|
348 if len(l) == 1:
|
|
349 if isinstance(l[0], (float, int)) or l[0] == None:
|
|
350 return l[0]
|
|
351 elif isinstance(l[0], list):
|
|
352 return control(None, l[0], cn)
|
|
353 else:
|
|
354 return False
|
|
355 elif len(l) > 2:
|
|
356 return control_list(ris, l, cn)
|
|
357 else:
|
|
358 return False
|
|
359
|
|
360 def control_list(ris, l :List[Optional[Union[float, int, list]]], cn :bool) -> Optional[bool]: #Optional[Literal[False]]:
|
|
361 """
|
|
362 Control the format of a list of expressions.
|
|
363
|
|
364 Args:
|
|
365 ris: Intermediate result.
|
|
366 l (list): List of expressions to control.
|
|
367 cn (bool): Control boolean value.
|
|
368
|
|
369 Returns:
|
|
370 Optional[Literal[False]]: Result of the control.
|
|
371 """
|
|
372 while l:
|
|
373 if len(l) == 1:
|
|
374 return False
|
|
375 elif (isinstance(l[0], (float, int)) or
|
|
376 l[0] == None) and l[1] in ['and', 'or']:
|
|
377 if isinstance(l[2], (float, int)) or l[2] == None:
|
|
378 ris = computes(l[0], l[1], l[2], cn)
|
|
379 elif isinstance(l[2], list):
|
|
380 tmp = control(None, l[2], cn)
|
|
381 if tmp is False:
|
|
382 return False
|
|
383 else:
|
|
384 ris = computes(l[0], l[1], tmp, cn)
|
|
385 else:
|
|
386 return False
|
|
387 l = l[3:]
|
|
388 elif l[0] in ['and', 'or']:
|
|
389 if isinstance(l[1], (float, int)) or l[1] == None:
|
|
390 ris = computes(ris, l[0], l[1], cn)
|
|
391 elif isinstance(l[1], list):
|
|
392 tmp = control(None,l[1], cn)
|
|
393 if tmp is False:
|
|
394 return False
|
|
395 else:
|
|
396 ris = computes(ris, l[0], tmp, cn)
|
|
397 else:
|
|
398 return False
|
|
399 l = l[2:]
|
|
400 elif isinstance(l[0], list) and l[1] in ['and', 'or']:
|
|
401 if isinstance(l[2], (float, int)) or l[2] == None:
|
|
402 tmp = control(None, l[0], cn)
|
|
403 if tmp is False:
|
|
404 return False
|
|
405 else:
|
|
406 ris = computes(tmp, l[1], l[2], cn)
|
|
407 elif isinstance(l[2], list):
|
|
408 tmp = control(None, l[0], cn)
|
|
409 tmp2 = control(None, l[2], cn)
|
|
410 if tmp is False or tmp2 is False:
|
|
411 return False
|
|
412 else:
|
|
413 ris = computes(tmp, l[1], tmp2, cn)
|
|
414 else:
|
|
415 return False
|
|
416 l = l[3:]
|
|
417 else:
|
|
418 return False
|
|
419 return ris
|
|
420
|
|
421 ResolvedRules = Dict[str, List[Optional[Union[float, int]]]]
|
|
422 def resolve(genes: Dict[str, str], rules: List[str], ids: List[str], resolve_none: bool, name: str) -> Tuple[Optional[ResolvedRules], Optional[list]]:
|
|
423 """
|
|
424 Resolve rules using gene data to compute scores for each rule.
|
|
425
|
|
426 Args:
|
|
427 genes (dict): Dictionary containing gene data with gene IDs as keys and corresponding values.
|
|
428 rules (list): List of rules to resolve.
|
|
429 ids (list): List of IDs corresponding to the rules.
|
|
430 resolve_none (bool): Flag indicating whether to resolve None values in the rules.
|
|
431 name (str): Name of the dataset.
|
|
432
|
|
433 Returns:
|
|
434 tuple: A tuple containing resolved rules as a dictionary and a list of gene IDs not found in the data.
|
|
435 """
|
|
436 resolve_rules = {}
|
|
437 not_found = []
|
|
438 flag = False
|
|
439 for key, value in genes.items():
|
|
440 tmp_resolve = []
|
|
441 for i in range(len(rules)):
|
|
442 tmp = rules[i]
|
|
443 if tmp:
|
|
444 tmp, err = replace_gene_value(tmp, value)
|
|
445 if err:
|
|
446 not_found.extend(err)
|
|
447 ris = control(None, tmp, resolve_none)
|
|
448 if ris is False or ris == None:
|
|
449 tmp_resolve.append(None)
|
|
450 else:
|
|
451 tmp_resolve.append(ris)
|
|
452 flag = True
|
|
453 else:
|
|
454 tmp_resolve.append(None)
|
|
455 resolve_rules[key] = tmp_resolve
|
|
456
|
|
457 if flag is False:
|
|
458 utils.logWarning(
|
|
459 f"Warning: no computable score (due to missing gene values) for class {name}, the class has been disregarded",
|
|
460 ARGS.out_log)
|
|
461
|
|
462 return (None, None)
|
|
463
|
|
464 return (resolve_rules, list(set(not_found)))
|
|
465 ############################ create_ras #######################################
|
|
466 def create_ras(resolve_rules: Optional[ResolvedRules], dataset_name: str, rules: List[str], ids: List[str], file: str) -> None:
|
|
467 """
|
|
468 Create a RAS (Reaction Activity Score) file from resolved rules.
|
|
469
|
|
470 Args:
|
|
471 resolve_rules (dict): Dictionary containing resolved rules.
|
|
472 dataset_name (str): Name of the dataset.
|
|
473 rules (list): List of rules.
|
|
474 file (str): Path to the output RAS file.
|
|
475
|
|
476 Returns:
|
|
477 None
|
|
478 """
|
|
479 if resolve_rules is None:
|
|
480 utils.logWarning(f"Couldn't generate RAS for current dataset: {dataset_name}", ARGS.out_log)
|
|
481
|
|
482 for geni in resolve_rules.values():
|
|
483 for i, valori in enumerate(geni):
|
|
484 if valori == None:
|
|
485 geni[i] = 'None'
|
|
486
|
|
487 output_ras = pd.DataFrame.from_dict(resolve_rules)
|
|
488
|
|
489 output_ras.insert(0, 'Reactions', ids)
|
|
490 output_to_csv = pd.DataFrame.to_csv(output_ras, sep = '\t', index = False)
|
|
491
|
|
492 text_file = open(file, "w")
|
|
493
|
|
494 text_file.write(output_to_csv)
|
|
495 text_file.close()
|
|
496
|
|
497 ################################- NEW RAS COMPUTATION -################################
|
|
498 Expr = Optional[Union[int, float]]
|
|
499 Ras = Expr
|
|
500 def ras_for_cell_lines(dataset: pd.DataFrame, rules: Dict[str, ruleUtils.OpList]) -> Dict[str, Dict[str, Ras]]:
|
|
501 """
|
|
502 Generates the RAS scores for each cell line found in the dataset.
|
|
503
|
|
504 Args:
|
|
505 dataset (pd.DataFrame): Dataset containing gene values.
|
|
506 rules (dict): The dict containing reaction ids as keys and rules as values.
|
|
507
|
|
508 Side effects:
|
|
509 dataset : mut
|
|
510
|
|
511 Returns:
|
|
512 dict: A dictionary where each key corresponds to a cell line name and each value is a dictionary
|
|
513 where each key corresponds to a reaction ID and each value is its computed RAS score.
|
|
514 """
|
|
515 ras_values_by_cell_line = {}
|
|
516 dataset.set_index(dataset.columns[0], inplace=True)
|
|
517 # Considera tutte le colonne tranne la prima in cui ci sono gli hugo quindi va scartata
|
|
518 for cell_line_name in dataset.columns[1:]:
|
|
519 cell_line = dataset[cell_line_name].to_dict()
|
|
520 ras_values_by_cell_line[cell_line_name]= get_ras_values(rules, cell_line)
|
|
521 return ras_values_by_cell_line
|
|
522
|
|
523 def get_ras_values(value_rules: Dict[str, ruleUtils.OpList], dataset: Dict[str, Expr]) -> Dict[str, Ras]:
|
|
524 """
|
|
525 Computes the RAS (Reaction Activity Score) values for each rule in the given dict.
|
|
526
|
|
527 Args:
|
|
528 value_rules (dict): A dictionary where keys are reaction ids and values are OpLists.
|
|
529 dataset : gene expression data of one cell line.
|
|
530
|
|
531 Returns:
|
|
532 dict: A dictionary where keys are reaction ids and values are the computed RAS values for each rule.
|
|
533 """
|
|
534 return {key: ras_op_list(op_list, dataset) for key, op_list in value_rules.items()}
|
|
535
|
|
536 def get_gene_expr(dataset :Dict[str, Expr], name :str) -> Expr:
|
|
537 """
|
|
538 Extracts the gene expression of the given gene from a cell line dataset.
|
|
539
|
|
540 Args:
|
|
541 dataset : gene expression data of one cell line.
|
|
542 name : gene name.
|
|
543
|
|
544 Returns:
|
|
545 Expr : the gene's expression value.
|
|
546 """
|
|
547 expr = dataset.get(name, None)
|
|
548 if expr is None: ERRORS.append(name)
|
|
549
|
|
550 return expr
|
|
551
|
|
552 def ras_op_list(op_list: ruleUtils.OpList, dataset: Dict[str, Expr]) -> Ras:
|
|
553 """
|
|
554 Computes recursively the RAS (Reaction Activity Score) value for the given OpList, considering the specified flag to control None behavior.
|
|
555
|
|
556 Args:
|
|
557 op_list (OpList): The OpList representing a rule with gene values.
|
|
558 dataset : gene expression data of one cell line.
|
|
559
|
|
560 Returns:
|
|
561 Ras: The computed RAS value for the given OpList.
|
|
562 """
|
|
563 op = op_list.op
|
|
564 ras_value :Ras = None
|
|
565 if not op: return get_gene_expr(dataset, op_list[0])
|
|
566 if op is ruleUtils.RuleOp.AND and not ARGS.none and None in op_list: return None
|
|
567
|
|
568 for i in range(len(op_list)):
|
|
569 item = op_list[i]
|
|
570 if isinstance(item, ruleUtils.OpList):
|
|
571 item = ras_op_list(item, dataset)
|
|
572
|
|
573 else:
|
|
574 item = get_gene_expr(dataset, item)
|
|
575
|
|
576 if item is None:
|
|
577 if op is ruleUtils.RuleOp.AND and not ARGS.none: return None
|
|
578 continue
|
|
579
|
|
580 if ras_value is None:
|
|
581 ras_value = item
|
|
582 else:
|
|
583 ras_value = ras_value + item if op is ruleUtils.RuleOp.OR else min(ras_value, item)
|
|
584
|
|
585 return ras_value
|
|
586
|
|
587 def save_as_tsv(rasScores: Dict[str, Dict[str, Ras]], reactions :List[str]) -> None:
|
|
588 """
|
|
589 Save computed ras scores to the given path, as a tsv file.
|
|
590
|
|
591 Args:
|
|
592 rasScores : the computed ras scores.
|
|
593 path : the output tsv file's path.
|
|
594
|
|
595 Returns:
|
|
596 None
|
|
597 """
|
|
598 for scores in rasScores.values(): # this is actually a lot faster than using the ootb dataframe metod, sadly
|
|
599 for reactId, score in scores.items():
|
|
600 if score is None: scores[reactId] = "None"
|
|
601
|
|
602 output_ras = pd.DataFrame.from_dict(rasScores)
|
|
603 output_ras.insert(0, 'Reactions', reactions)
|
|
604 output_ras.to_csv(ARGS.ras_output, sep = '\t', index = False)
|
|
605
|
|
606 ############################ MAIN #############################################
|
|
607 #TODO: not used but keep, it will be when the new translator dicts will be used.
|
|
608 def translateGene(geneName :str, encoding :str, geneTranslator :Dict[str, Dict[str, str]]) -> str:
|
|
609 """
|
|
610 Translate gene from any supported encoding to HugoID.
|
|
611
|
|
612 Args:
|
|
613 geneName (str): the name of the gene in its current encoding.
|
|
614 encoding (str): the encoding.
|
|
615 geneTranslator (Dict[str, Dict[str, str]]): the dict containing all supported gene names
|
|
616 and encodings in the current model, mapping each to the corresponding HugoID encoding.
|
|
617
|
|
618 Raises:
|
|
619 ValueError: When the gene isn't supported in the model.
|
|
620
|
|
621 Returns:
|
|
622 str: the gene in HugoID encoding.
|
|
623 """
|
|
624 supportedGenesInEncoding = geneTranslator[encoding]
|
|
625 if geneName in supportedGenesInEncoding: return supportedGenesInEncoding[geneName]
|
|
626 raise ValueError(f"Gene \"{geneName}\" non trovato, verifica di star utilizzando il modello corretto!")
|
|
627
|
|
628 def load_custom_rules() -> Dict[str, ruleUtils.OpList]:
|
|
629 """
|
|
630 Opens custom rules file and extracts the rules. If the file is in .csv format an additional parsing step will be
|
|
631 performed, significantly impacting the runtime.
|
|
632
|
|
633 Returns:
|
|
634 Dict[str, ruleUtils.OpList] : dict mapping reaction IDs to rules.
|
|
635 """
|
|
636 datFilePath = utils.FilePath.fromStrPath(ARGS.rule_list) # actual file, stored in galaxy as a .dat
|
|
637
|
|
638 try: filenamePath = utils.FilePath.fromStrPath(ARGS.rules_name) # file's name in input, to determine its original ext
|
|
639 except utils.PathErr as err:
|
|
640 raise utils.PathErr(filenamePath, f"Please make sure your file's name is a valid file path, {err.msg}")
|
|
641
|
|
642 if filenamePath.ext is utils.FileFormat.PICKLE: return utils.readPickle(datFilePath)
|
|
643
|
|
644 # csv rules need to be parsed, those in a pickle format are taken to be pre-parsed.
|
|
645 return { line[0] : ruleUtils.parseRuleToNestedList(line[1]) for line in utils.readCsv(datFilePath) }
|
|
646
|
|
647 def main() -> None:
|
|
648 """
|
|
649 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
650
|
|
651 Returns:
|
|
652 None
|
|
653 """
|
|
654 # get args from frontend (related xml)
|
|
655 global ARGS
|
|
656 ARGS = process_args()
|
44
|
657 print(ARGS.rules_selector)
|
4
|
658 # read dataset
|
|
659 dataset = read_dataset(ARGS.input, "dataset")
|
|
660 dataset.iloc[:, 0] = (dataset.iloc[:, 0]).astype(str)
|
|
661
|
|
662 # remove versioning from gene names
|
|
663 dataset.iloc[:, 0] = dataset.iloc[:, 0].str.split('.').str[0]
|
|
664
|
|
665 # handle custom models
|
|
666 model :utils.Model = ARGS.rules_selector
|
|
667 if model is utils.Model.Custom:
|
|
668 rules = load_custom_rules()
|
|
669 reactions = list(rules.keys())
|
|
670
|
|
671 save_as_tsv(ras_for_cell_lines(dataset, rules), reactions)
|
|
672 if ERRORS: utils.logWarning(
|
|
673 f"The following genes are mentioned in the rules but don't appear in the dataset: {ERRORS}",
|
|
674 ARGS.out_log)
|
|
675
|
|
676 return
|
|
677
|
|
678 # This is the standard flow of the ras_generator program, for non-custom models.
|
|
679 name = "RAS Dataset"
|
|
680 type_gene = gene_type(dataset.iloc[0, 0], name)
|
|
681
|
|
682 rules = model.getRules(ARGS.tool_dir)
|
|
683 genes = data_gene(dataset, type_gene, name, None)
|
|
684 ids, rules = load_id_rules(rules.get(type_gene))
|
|
685
|
|
686 resolve_rules, err = resolve(genes, rules, ids, ARGS.none, name)
|
|
687 create_ras(resolve_rules, name, rules, ids, ARGS.ras_output)
|
|
688
|
|
689 if err: utils.logWarning(
|
|
690 f"Warning: gene(s) {err} not found in class \"{name}\", " +
|
|
691 "the expression level for this gene will be considered NaN",
|
|
692 ARGS.out_log)
|
|
693
|
|
694 print("Execution succeded")
|
|
695
|
|
696 ###############################################################################
|
|
697 if __name__ == "__main__":
|
|
698 main() |