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