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