| 4 | 1 from __future__ import division | 
|  | 2 import csv | 
|  | 3 from enum import Enum | 
|  | 4 import re | 
|  | 5 import sys | 
|  | 6 import numpy as np | 
|  | 7 import pandas as pd | 
|  | 8 import itertools as it | 
|  | 9 import scipy.stats as st | 
|  | 10 import lxml.etree as ET | 
|  | 11 import math | 
|  | 12 import utils.general_utils as utils | 
|  | 13 from PIL import Image | 
|  | 14 import os | 
|  | 15 import argparse | 
|  | 16 import pyvips | 
|  | 17 from typing import Tuple, Union, Optional, List, Dict | 
| 143 | 18 import copy | 
| 4 | 19 | 
| 300 | 20 from pydeseq2.dds import DeseqDataSet | 
|  | 21 from pydeseq2.default_inference import DefaultInference | 
|  | 22 from pydeseq2.ds import DeseqStats | 
|  | 23 | 
| 4 | 24 ERRORS = [] | 
|  | 25 ########################## argparse ########################################## | 
|  | 26 ARGS :argparse.Namespace | 
| 147 | 27 def process_args(args:List[str] = None) -> argparse.Namespace: | 
| 4 | 28     """ | 
|  | 29     Interfaces the script of a module with its frontend, making the user's choices for various parameters available as values in code. | 
|  | 30 | 
|  | 31     Args: | 
|  | 32         args : Always obtained (in file) from sys.argv | 
|  | 33 | 
|  | 34     Returns: | 
|  | 35         Namespace : An object containing the parsed arguments | 
|  | 36     """ | 
|  | 37     parser = argparse.ArgumentParser( | 
|  | 38         usage = "%(prog)s [options]", | 
|  | 39         description = "process some value's genes to create a comparison's map.") | 
|  | 40 | 
|  | 41     #General: | 
|  | 42     parser.add_argument( | 
|  | 43         '-td', '--tool_dir', | 
|  | 44         type = str, | 
|  | 45         required = True, | 
|  | 46         help = 'your tool directory') | 
|  | 47 | 
|  | 48     parser.add_argument('-on', '--control', type = str) | 
|  | 49     parser.add_argument('-ol', '--out_log', help = "Output log") | 
|  | 50 | 
|  | 51     #Computation details: | 
|  | 52     parser.add_argument( | 
|  | 53         '-co', '--comparison', | 
|  | 54         type = str, | 
| 291 | 55         default = 'manyvsmany', | 
| 4 | 56         choices = ['manyvsmany', 'onevsrest', 'onevsmany']) | 
| 293 | 57 | 
|  | 58     parser.add_argument( | 
|  | 59         '-te' ,'--test', | 
|  | 60         type = str, | 
|  | 61         default = 'ks', | 
| 300 | 62         choices = ['ks', 'ttest_p', 'ttest_ind', 'wilcoxon', 'mw', 'DESeq'], | 
| 293 | 63         help = 'Statistical test to use (default: %(default)s)') | 
| 4 | 64 | 
|  | 65     parser.add_argument( | 
|  | 66         '-pv' ,'--pValue', | 
|  | 67         type = float, | 
|  | 68         default = 0.1, | 
|  | 69         help = 'P-Value threshold (default: %(default)s)') | 
| 297 | 70 | 
|  | 71     parser.add_argument( | 
|  | 72         '-adj' ,'--adjusted', | 
|  | 73         type = utils.Bool("adjusted"), default = False, | 
|  | 74         help = 'Apply the FDR (Benjamini-Hochberg) correction (default: %(default)s)') | 
| 4 | 75 | 
|  | 76     parser.add_argument( | 
|  | 77         '-fc', '--fChange', | 
|  | 78         type = float, | 
|  | 79         default = 1.5, | 
|  | 80         help = 'Fold-Change threshold (default: %(default)s)') | 
|  | 81 | 
|  | 82     parser.add_argument( | 
|  | 83         "-ne", "--net", | 
|  | 84         type = utils.Bool("net"), default = False, | 
|  | 85         help = "choose if you want net enrichment for RPS") | 
|  | 86 | 
|  | 87     parser.add_argument( | 
|  | 88         '-op', '--option', | 
|  | 89         type = str, | 
|  | 90         choices = ['datasets', 'dataset_class'], | 
|  | 91         help='dataset or dataset and class') | 
|  | 92 | 
|  | 93     #RAS: | 
|  | 94     parser.add_argument( | 
|  | 95         "-ra", "--using_RAS", | 
|  | 96         type = utils.Bool("using_RAS"), default = True, | 
|  | 97         help = "choose whether to use RAS datasets.") | 
|  | 98 | 
|  | 99     parser.add_argument( | 
|  | 100         '-id', '--input_data', | 
|  | 101         type = str, | 
|  | 102         help = 'input dataset') | 
|  | 103 | 
|  | 104     parser.add_argument( | 
|  | 105         '-ic', '--input_class', | 
|  | 106         type = str, | 
|  | 107         help = 'sample group specification') | 
|  | 108 | 
|  | 109     parser.add_argument( | 
|  | 110         '-ids', '--input_datas', | 
|  | 111         type = str, | 
|  | 112         nargs = '+', | 
|  | 113         help = 'input datasets') | 
|  | 114 | 
|  | 115     parser.add_argument( | 
|  | 116         '-na', '--names', | 
|  | 117         type = str, | 
|  | 118         nargs = '+', | 
|  | 119         help = 'input names') | 
|  | 120 | 
|  | 121     #RPS: | 
|  | 122     parser.add_argument( | 
|  | 123         "-rp", "--using_RPS", | 
|  | 124         type = utils.Bool("using_RPS"), default = False, | 
|  | 125         help = "choose whether to use RPS datasets.") | 
|  | 126 | 
|  | 127     parser.add_argument( | 
|  | 128         '-idr', '--input_data_rps', | 
|  | 129         type = str, | 
|  | 130         help = 'input dataset rps') | 
|  | 131 | 
|  | 132     parser.add_argument( | 
|  | 133         '-icr', '--input_class_rps', | 
|  | 134         type = str, | 
|  | 135         help = 'sample group specification rps') | 
|  | 136 | 
|  | 137     parser.add_argument( | 
|  | 138         '-idsr', '--input_datas_rps', | 
|  | 139         type = str, | 
|  | 140         nargs = '+', | 
|  | 141         help = 'input datasets rps') | 
|  | 142 | 
|  | 143     parser.add_argument( | 
|  | 144         '-nar', '--names_rps', | 
|  | 145         type = str, | 
|  | 146         nargs = '+', | 
|  | 147         help = 'input names rps') | 
|  | 148 | 
|  | 149     #Output: | 
|  | 150     parser.add_argument( | 
|  | 151         "-gs", "--generate_svg", | 
|  | 152         type = utils.Bool("generate_svg"), default = True, | 
|  | 153         help = "choose whether to use RAS datasets.") | 
|  | 154 | 
|  | 155     parser.add_argument( | 
|  | 156         "-gp", "--generate_pdf", | 
|  | 157         type = utils.Bool("generate_pdf"), default = True, | 
|  | 158         help = "choose whether to use RAS datasets.") | 
|  | 159 | 
|  | 160     parser.add_argument( | 
|  | 161         '-cm', '--custom_map', | 
|  | 162         type = str, | 
|  | 163         help='custom map to use') | 
|  | 164 | 
|  | 165     parser.add_argument( | 
| 146 | 166         '-idop', '--output_path', | 
|  | 167         type = str, | 
|  | 168         default='result', | 
|  | 169         help = 'output path for maps') | 
|  | 170 | 
|  | 171     parser.add_argument( | 
| 4 | 172         '-mc',  '--choice_map', | 
|  | 173         type = utils.Model, default = utils.Model.HMRcore, | 
|  | 174         choices = [utils.Model.HMRcore, utils.Model.ENGRO2, utils.Model.Custom]) | 
|  | 175 | 
| 146 | 176     args :argparse.Namespace = parser.parse_args(args) | 
| 4 | 177     if args.using_RAS and not args.using_RPS: args.net = False | 
|  | 178 | 
|  | 179     return args | 
|  | 180 | 
|  | 181 ############################ dataset input #################################### | 
|  | 182 def read_dataset(data :str, name :str) -> pd.DataFrame: | 
|  | 183     """ | 
|  | 184     Tries to read the dataset from its path (data) as a tsv and turns it into a DataFrame. | 
|  | 185 | 
|  | 186     Args: | 
|  | 187         data : filepath of a dataset (from frontend input params or literals upon calling) | 
|  | 188         name : name associated with the dataset (from frontend input params or literals upon calling) | 
|  | 189 | 
|  | 190     Returns: | 
|  | 191         pd.DataFrame : dataset in a runtime operable shape | 
|  | 192 | 
|  | 193     Raises: | 
|  | 194         sys.exit : if there's no data (pd.errors.EmptyDataError) or if the dataset has less than 2 columns | 
|  | 195     """ | 
|  | 196     try: | 
|  | 197         dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python') | 
|  | 198     except pd.errors.EmptyDataError: | 
|  | 199         sys.exit('Execution aborted: wrong format of ' + name + '\n') | 
|  | 200     if len(dataset.columns) < 2: | 
|  | 201         sys.exit('Execution aborted: wrong format of ' + name + '\n') | 
|  | 202     return dataset | 
|  | 203 | 
|  | 204 ############################ map_methods ###################################### | 
|  | 205 FoldChange = Union[float, int, str] # Union[float, Literal[0, "-INF", "INF"]] | 
|  | 206 def fold_change(avg1 :float, avg2 :float) -> FoldChange: | 
|  | 207     """ | 
|  | 208     Calculates the fold change between two gene expression values. | 
|  | 209 | 
|  | 210     Args: | 
|  | 211         avg1 : average expression value from one dataset avg2 : average expression value from the other dataset | 
|  | 212 | 
|  | 213     Returns: | 
|  | 214         FoldChange : | 
|  | 215             0 : when both input values are 0 | 
|  | 216             "-INF" : when avg1 is 0 | 
|  | 217             "INF" : when avg2 is 0 | 
|  | 218             float : for any other combination of values | 
|  | 219     """ | 
|  | 220     if avg1 == 0 and avg2 == 0: | 
|  | 221         return 0 | 
| 291 | 222 | 
|  | 223     if avg1 == 0: | 
|  | 224         return '-INF' # TODO: maybe fix | 
|  | 225 | 
|  | 226     if avg2 == 0: | 
| 4 | 227         return 'INF' | 
|  | 228 | 
| 291 | 229     # (threshold_F_C - 1) / (abs(threshold_F_C) + 1) con threshold_F_C > 1 | 
|  | 230     return (avg1 - avg2) / (abs(avg1) + abs(avg2)) | 
|  | 231 | 
|  | 232 # TODO: I would really like for this one to get the Thanos treatment | 
| 4 | 233 def fix_style(l :str, col :Optional[str], width :str, dash :str) -> str: | 
|  | 234     """ | 
|  | 235     Produces a "fixed" style string to assign to a reaction arrow in the SVG map, assigning style properties to the corresponding values passed as input params. | 
|  | 236 | 
|  | 237     Args: | 
|  | 238         l : current style string of an SVG element | 
|  | 239         col : new value for the "stroke" style property | 
|  | 240         width : new value for the "stroke-width" style property | 
|  | 241         dash : new value for the "stroke-dasharray" style property | 
|  | 242 | 
|  | 243     Returns: | 
|  | 244         str : the fixed style string | 
|  | 245     """ | 
|  | 246     tmp = l.split(';') | 
|  | 247     flag_col = False | 
|  | 248     flag_width = False | 
|  | 249     flag_dash = False | 
|  | 250     for i in range(len(tmp)): | 
|  | 251         if tmp[i].startswith('stroke:'): | 
|  | 252             tmp[i] = 'stroke:' + col | 
|  | 253             flag_col = True | 
|  | 254         if tmp[i].startswith('stroke-width:'): | 
|  | 255             tmp[i] = 'stroke-width:' + width | 
|  | 256             flag_width = True | 
|  | 257         if tmp[i].startswith('stroke-dasharray:'): | 
|  | 258             tmp[i] = 'stroke-dasharray:' + dash | 
|  | 259             flag_dash = True | 
|  | 260     if not flag_col: | 
|  | 261         tmp.append('stroke:' + col) | 
|  | 262     if not flag_width: | 
|  | 263         tmp.append('stroke-width:' + width) | 
|  | 264     if not flag_dash: | 
|  | 265         tmp.append('stroke-dasharray:' + dash) | 
|  | 266     return ';'.join(tmp) | 
|  | 267 | 
| 291 | 268 # TODO: remove, there's applyRPS whatever | 
| 4 | 269 # The type of d values is collapsed, losing precision, because the dict containst lists instead of tuples, please fix! | 
|  | 270 def fix_map(d :Dict[str, List[Union[float, FoldChange]]], core_map :ET.ElementTree, threshold_P_V :float, threshold_F_C :float, max_z_score :float) -> ET.ElementTree: | 
|  | 271     """ | 
|  | 272     Edits the selected SVG map based on the p-value and fold change data (d) and some significance thresholds also passed as inputs. | 
|  | 273 | 
|  | 274     Args: | 
|  | 275         d : dictionary mapping a p-value and a fold-change value (values) to each reaction ID as encoded in the SVG map (keys) | 
|  | 276         core_map : SVG map to modify | 
|  | 277         threshold_P_V : threshold for a p-value to be considered significant | 
|  | 278         threshold_F_C : threshold for a fold change value to be considered significant | 
|  | 279         max_z_score : highest z-score (absolute value) | 
|  | 280 | 
|  | 281     Returns: | 
|  | 282         ET.ElementTree : the modified core_map | 
|  | 283 | 
|  | 284     Side effects: | 
|  | 285         core_map : mut | 
|  | 286     """ | 
|  | 287     maxT = 12 | 
|  | 288     minT = 2 | 
|  | 289     grey = '#BEBEBE' | 
|  | 290     blue = '#6495ed' | 
|  | 291     red = '#ecac68' | 
|  | 292     for el in core_map.iter(): | 
|  | 293         el_id = str(el.get('id')) | 
|  | 294         if el_id.startswith('R_'): | 
|  | 295             tmp = d.get(el_id[2:]) | 
|  | 296             if tmp != None: | 
| 291 | 297                 p_val, f_c, z_score, avg1, avg2 = tmp | 
| 276 | 298 | 
|  | 299                 if math.isnan(p_val) or (isinstance(f_c, float) and math.isnan(f_c)): continue | 
|  | 300 | 
| 291 | 301                 if p_val <= threshold_P_V: # p-value is OK | 
|  | 302                     if not isinstance(f_c, str): # FC is finite | 
|  | 303                         if abs(f_c) < ((threshold_F_C - 1) / (abs(threshold_F_C) + 1)): # FC is not OK | 
| 4 | 304                             col = grey | 
|  | 305                             width = str(minT) | 
| 291 | 306                         else: # FC is OK | 
| 4 | 307                             if f_c < 0: | 
|  | 308                                 col = blue | 
|  | 309                             elif f_c > 0: | 
|  | 310                                 col = red | 
| 291 | 311                             width = str( | 
|  | 312                                 min( | 
|  | 313                                     max(abs(z_score * maxT) / max_z_score, minT), | 
|  | 314                                     maxT)) | 
|  | 315 | 
|  | 316                     else: # FC is infinite | 
| 4 | 317                         if f_c == '-INF': | 
|  | 318                             col = blue | 
|  | 319                         elif f_c == 'INF': | 
|  | 320                             col = red | 
|  | 321                         width = str(maxT) | 
|  | 322                     dash = 'none' | 
| 291 | 323                 else: # p-value is not OK | 
| 4 | 324                     dash = '5,5' | 
|  | 325                     col = grey | 
|  | 326                     width = str(minT) | 
|  | 327                 el.set('style', fix_style(el.get('style', ""), col, width, dash)) | 
|  | 328     return core_map | 
|  | 329 | 
|  | 330 def getElementById(reactionId :str, metabMap :ET.ElementTree) -> utils.Result[ET.Element, utils.Result.ResultErr]: | 
|  | 331     """ | 
|  | 332     Finds any element in the given map with the given ID. ID uniqueness in an svg file is recommended but | 
|  | 333     not enforced, if more than one element with the exact ID is found only the first will be returned. | 
|  | 334 | 
|  | 335     Args: | 
|  | 336         reactionId (str): exact ID of the requested element. | 
|  | 337         metabMap (ET.ElementTree): metabolic map containing the element. | 
|  | 338 | 
|  | 339     Returns: | 
|  | 340         utils.Result[ET.Element, ResultErr]: result of the search, either the first match found or a ResultErr. | 
|  | 341     """ | 
|  | 342     return utils.Result.Ok( | 
| 290 | 343         f"//*[@id=\"{reactionId}\"]").map( | 
|  | 344         lambda xPath : metabMap.xpath(xPath)[0]).mapErr( | 
| 4 | 345         lambda _ : utils.Result.ResultErr(f"No elements with ID \"{reactionId}\" found in map")) | 
|  | 346         # ^^^ we shamelessly ignore the contents of the IndexError, it offers nothing to the user. | 
|  | 347 | 
|  | 348 def styleMapElement(element :ET.Element, styleStr :str) -> None: | 
|  | 349     currentStyles :str = element.get("style", "") | 
|  | 350     if re.search(r";stroke:[^;]+;stroke-width:[^;]+;stroke-dasharray:[^;]+$", currentStyles): | 
| 291 | 351         currentStyles = ';'.join(currentStyles.split(';')[:-3]) # TODO: why the last 3? Are we sure? | 
|  | 352 | 
|  | 353     #TODO: this is attempting to solve the styling override problem, not sure it does tho | 
| 4 | 354 | 
|  | 355     element.set("style", currentStyles + styleStr) | 
|  | 356 | 
| 291 | 357 # TODO: maybe remove vvv | 
| 4 | 358 class ReactionDirection(Enum): | 
|  | 359     Unknown = "" | 
|  | 360     Direct  = "_F" | 
|  | 361     Inverse = "_B" | 
|  | 362 | 
|  | 363     @classmethod | 
|  | 364     def fromDir(cls, s :str) -> "ReactionDirection": | 
|  | 365         # vvv as long as there's so few variants I actually condone the if spam: | 
|  | 366         if s == ReactionDirection.Direct.value:  return ReactionDirection.Direct | 
|  | 367         if s == ReactionDirection.Inverse.value: return ReactionDirection.Inverse | 
|  | 368         return ReactionDirection.Unknown | 
|  | 369 | 
|  | 370     @classmethod | 
|  | 371     def fromReactionId(cls, reactionId :str) -> "ReactionDirection": | 
|  | 372         return ReactionDirection.fromDir(reactionId[-2:]) | 
|  | 373 | 
|  | 374 def getArrowBodyElementId(reactionId :str) -> str: | 
|  | 375     if reactionId.endswith("_RV"): reactionId = reactionId[:-3] #TODO: standardize _RV | 
|  | 376     elif ReactionDirection.fromReactionId(reactionId) is not ReactionDirection.Unknown: reactionId = reactionId[:-2] | 
|  | 377     return f"R_{reactionId}" | 
|  | 378 | 
|  | 379 def getArrowHeadElementId(reactionId :str) -> Tuple[str, str]: | 
|  | 380     """ | 
|  | 381     We attempt extracting the direction information from the provided reaction ID, if unsuccessful we provide the IDs of both directions. | 
|  | 382 | 
|  | 383     Args: | 
|  | 384         reactionId : the provided reaction ID. | 
|  | 385 | 
|  | 386     Returns: | 
|  | 387         Tuple[str, str]: either a single str ID for the correct arrow head followed by an empty string or both options to try. | 
|  | 388     """ | 
|  | 389     if reactionId.endswith("_RV"): reactionId = reactionId[:-3] #TODO: standardize _RV | 
| 291 | 390     elif ReactionDirection.fromReactionId(reactionId) is not ReactionDirection.Unknown: | 
|  | 391         return reactionId[:-3:-1] + reactionId[:-2], "" # ^^^ Invert _F to F_ | 
|  | 392 | 
| 4 | 393     return f"F_{reactionId}", f"B_{reactionId}" | 
|  | 394 | 
|  | 395 class ArrowColor(Enum): | 
|  | 396     """ | 
|  | 397     Encodes possible arrow colors based on their meaning in the enrichment process. | 
|  | 398     """ | 
| 299 | 399     Invalid       = "#BEBEBE" # gray, fold-change under treshold or not significant p-value | 
|  | 400     Transparent   = "#ffffff00" # transparent, to make some arrow segments disappear | 
| 291 | 401     UpRegulated   = "#ecac68" # orange, up-regulated reaction | 
|  | 402     DownRegulated = "#6495ed" # lightblue, down-regulated reaction | 
| 4 | 403 | 
|  | 404     UpRegulatedInv = "#FF0000" | 
| 291 | 405     # ^^^ bright red, up-regulated net value for a reversible reaction with | 
| 4 | 406     # conflicting enrichment in the two directions. | 
|  | 407 | 
|  | 408     DownRegulatedInv = "#0000FF" | 
| 291 | 409     # ^^^ bright blue, down-regulated net value for a reversible reaction with | 
| 4 | 410     # conflicting enrichment in the two directions. | 
|  | 411 | 
|  | 412     @classmethod | 
|  | 413     def fromFoldChangeSign(cls, foldChange :float, *, useAltColor = False) -> "ArrowColor": | 
|  | 414         colors = (cls.DownRegulated, cls.DownRegulatedInv) if foldChange < 0 else (cls.UpRegulated, cls.UpRegulatedInv) | 
|  | 415         return colors[useAltColor] | 
|  | 416 | 
|  | 417     def __str__(self) -> str: return self.value | 
|  | 418 | 
|  | 419 class Arrow: | 
|  | 420     """ | 
|  | 421     Models the properties of a reaction arrow that change based on enrichment. | 
|  | 422     """ | 
|  | 423     MIN_W = 2 | 
|  | 424     MAX_W = 12 | 
|  | 425 | 
|  | 426     def __init__(self, width :int, col: ArrowColor, *, isDashed = False) -> None: | 
|  | 427         """ | 
|  | 428         (Private) Initializes an instance of Arrow. | 
|  | 429 | 
|  | 430         Args: | 
|  | 431             width : width of the arrow, ideally to be kept within Arrow.MIN_W and Arrow.MAX_W (not enforced). | 
|  | 432             col : color of the arrow. | 
|  | 433             isDashed : whether the arrow should be dashed, meaning the associated pValue resulted not significant. | 
|  | 434 | 
|  | 435         Returns: | 
|  | 436             None : practically, a Arrow instance. | 
|  | 437         """ | 
|  | 438         self.w    = width | 
|  | 439         self.col  = col | 
|  | 440         self.dash = isDashed | 
|  | 441 | 
|  | 442     def applyTo(self, reactionId :str, metabMap :ET.ElementTree, styleStr :str) -> None: | 
| 289 | 443         if getElementById(reactionId, metabMap).map(lambda el : styleMapElement(el, styleStr)).isErr: | 
|  | 444             ERRORS.append(reactionId) | 
| 4 | 445 | 
|  | 446     def styleReactionElements(self, metabMap :ET.ElementTree, reactionId :str, *, mindReactionDir = True) -> None: | 
|  | 447         # If We're dealing with RAS data or in general don't care about the direction of the reaction we only style the arrow body | 
|  | 448         if not mindReactionDir: | 
|  | 449             return self.applyTo(getArrowBodyElementId(reactionId), metabMap, self.toStyleStr()) | 
| 284 | 450 | 
| 4 | 451         # Now we style the arrow head(s): | 
|  | 452         idOpt1, idOpt2 = getArrowHeadElementId(reactionId) | 
|  | 453         self.applyTo(idOpt1, metabMap, self.toStyleStr(downSizedForTips = True)) | 
|  | 454         if idOpt2: self.applyTo(idOpt2, metabMap, self.toStyleStr(downSizedForTips = True)) | 
|  | 455 | 
| 291 | 456     # TODO: this seems to be unused, remove | 
| 4 | 457     def getMapReactionId(self, reactionId :str, mindReactionDir :bool) -> str: | 
|  | 458         """ | 
|  | 459         Computes the reaction ID as encoded in the map for a given reaction ID from the dataset. | 
|  | 460 | 
|  | 461         Args: | 
|  | 462             reactionId: the reaction ID, as encoded in the dataset. | 
|  | 463             mindReactionDir: if True forward (F_) and backward (B_) directions will be encoded in the result. | 
|  | 464 | 
|  | 465         Returns: | 
|  | 466             str : the ID of an arrow's body or tips in the map. | 
|  | 467         """ | 
|  | 468         # we assume the reactionIds also don't encode reaction dir if they don't mind it when styling the map. | 
|  | 469         if not mindReactionDir: return "R_" + reactionId | 
|  | 470 | 
|  | 471         #TODO: this is clearly something we need to make consistent in RPS | 
|  | 472         return (reactionId[:-3:-1] + reactionId[:-2]) if reactionId[:-2] in ["_F", "_B"] else f"F_{reactionId}" # "Pyr_F" --> "F_Pyr" | 
|  | 473 | 
|  | 474     def toStyleStr(self, *, downSizedForTips = False) -> str: | 
|  | 475         """ | 
|  | 476         Collapses the styles of this Arrow into a str, ready to be applied as part of the "style" property on an svg element. | 
|  | 477 | 
|  | 478         Returns: | 
|  | 479             str : the styles string. | 
|  | 480         """ | 
|  | 481         width = self.w | 
|  | 482         if downSizedForTips: width *= 0.8 | 
|  | 483         return f";stroke:{self.col};stroke-width:{width};stroke-dasharray:{'5,5' if self.dash else 'none'}" | 
|  | 484 | 
|  | 485 # vvv These constants could be inside the class itself a static properties, but python | 
|  | 486 # was built by brainless organisms so here we are! | 
| 299 | 487 INVALID_ARROW       = Arrow(Arrow.MIN_W, ArrowColor.Invalid) | 
| 4 | 488 INSIGNIFICANT_ARROW = Arrow(Arrow.MIN_W, ArrowColor.Invalid, isDashed = True) | 
| 299 | 489 TRANSPARENT_ARROW   = Arrow(Arrow.MIN_W, ArrowColor.Transparent) # Who cares how big it is if it's transparent | 
| 4 | 490 | 
| 291 | 491 # TODO: A more general version of this can be used for RAS as well, we don't need "fix map" or whatever | 
| 4 | 492 def applyRpsEnrichmentToMap(rpsEnrichmentRes :Dict[str, Union[Tuple[float, FoldChange], Tuple[float, FoldChange, float, float]]], metabMap :ET.ElementTree, maxNumericZScore :float) -> None: | 
|  | 493     """ | 
|  | 494     Applies RPS enrichment results to the provided metabolic map. | 
|  | 495 | 
|  | 496     Args: | 
|  | 497         rpsEnrichmentRes : RPS enrichment results. | 
|  | 498         metabMap : the metabolic map to edit. | 
|  | 499         maxNumericZScore : biggest finite z-score value found. | 
|  | 500 | 
|  | 501     Side effects: | 
|  | 502         metabMap : mut | 
|  | 503 | 
|  | 504     Returns: | 
|  | 505         None | 
|  | 506     """ | 
|  | 507     for reactionId, values in rpsEnrichmentRes.items(): | 
|  | 508         pValue = values[0] | 
|  | 509         foldChange = values[1] | 
|  | 510         z_score = values[2] | 
|  | 511 | 
| 276 | 512         if math.isnan(pValue) or (isinstance(foldChange, float) and math.isnan(foldChange)): continue | 
|  | 513 | 
| 4 | 514         if isinstance(foldChange, str): foldChange = float(foldChange) | 
|  | 515         if pValue >= ARGS.pValue: # pValue above tresh: dashed arrow | 
|  | 516             INSIGNIFICANT_ARROW.styleReactionElements(metabMap, reactionId) | 
|  | 517             continue | 
|  | 518 | 
| 291 | 519         if abs(foldChange) < (ARGS.fChange - 1) / (abs(ARGS.fChange) + 1): | 
| 4 | 520             INVALID_ARROW.styleReactionElements(metabMap, reactionId) | 
|  | 521             continue | 
|  | 522 | 
|  | 523         width = Arrow.MAX_W | 
| 293 | 524         if not math.isinf(z_score): | 
| 291 | 525             try: width = min( | 
|  | 526                 max(abs(z_score * Arrow.MAX_W) / maxNumericZScore, Arrow.MIN_W), | 
|  | 527                 Arrow.MAX_W) | 
|  | 528 | 
| 4 | 529             except ZeroDivisionError: pass | 
|  | 530 | 
|  | 531         if not reactionId.endswith("_RV"): # RV stands for reversible reactions | 
|  | 532             Arrow(width, ArrowColor.fromFoldChangeSign(foldChange)).styleReactionElements(metabMap, reactionId) | 
|  | 533             continue | 
|  | 534 | 
|  | 535         reactionId = reactionId[:-3] # Remove "_RV" | 
|  | 536 | 
|  | 537         inversionScore = (values[3] < 0) + (values[4] < 0) # Compacts the signs of averages into 1 easy to check score | 
| 290 | 538         if inversionScore == 2: foldChange *= -1 | 
| 4 | 539 | 
|  | 540         # If the score is 1 (opposite signs) we use alternative colors vvv | 
|  | 541         arrow = Arrow(width, ArrowColor.fromFoldChangeSign(foldChange, useAltColor = inversionScore == 1)) | 
|  | 542 | 
|  | 543         # vvv These 2 if statements can both be true and can both happen | 
|  | 544         if ARGS.net: # style arrow head(s): | 
|  | 545             arrow.styleReactionElements(metabMap, reactionId + ("_B" if inversionScore == 2 else "_F")) | 
|  | 546 | 
|  | 547         if not ARGS.using_RAS: # style arrow body | 
|  | 548             arrow.styleReactionElements(metabMap, reactionId, mindReactionDir = False) | 
|  | 549 | 
|  | 550 ############################ split class ###################################### | 
| 291 | 551 def split_class(classes :pd.DataFrame, dataset_values :Dict[str, List[float]]) -> Dict[str, List[List[float]]]: | 
| 4 | 552     """ | 
|  | 553     Generates a :dict that groups together data from a :DataFrame based on classes the data is related to. | 
|  | 554 | 
|  | 555     Args: | 
|  | 556         classes : a :DataFrame of only string values, containing class information (rows) and keys to query the resolve_rules :dict | 
| 291 | 557         dataset_values : a :dict containing :float data | 
| 4 | 558 | 
|  | 559     Returns: | 
|  | 560         dict : the dict with data grouped by class | 
|  | 561 | 
|  | 562     Side effects: | 
|  | 563         classes : mut | 
|  | 564     """ | 
|  | 565     class_pat :Dict[str, List[List[float]]] = {} | 
|  | 566     for i in range(len(classes)): | 
|  | 567         classe :str = classes.iloc[i, 1] | 
|  | 568         if pd.isnull(classe): continue | 
|  | 569 | 
|  | 570         l :List[List[float]] = [] | 
| 309 | 571         sample_ids: List[str] = [] | 
|  | 572 | 
| 4 | 573         for j in range(i, len(classes)): | 
|  | 574             if classes.iloc[j, 1] == classe: | 
| 291 | 575                 pat_id :str = classes.iloc[j, 0] # sample name | 
|  | 576                 values = dataset_values.get(pat_id, None) # the column of values for that sample | 
|  | 577                 if values != None: | 
|  | 578                     l.append(values) | 
| 309 | 579                     sample_ids.append(pat_id) | 
| 291 | 580                 classes.iloc[j, 1] = None # TODO: problems? | 
| 4 | 581 | 
|  | 582         if l: | 
| 309 | 583             class_pat[classe] = { | 
|  | 584                 "values": list(map(list, zip(*l))),  # trasposta | 
|  | 585                 "samples": sample_ids | 
|  | 586             } | 
| 4 | 587             continue | 
|  | 588 | 
|  | 589         utils.logWarning( | 
|  | 590             f"Warning: no sample found in class \"{classe}\", the class has been disregarded", ARGS.out_log) | 
|  | 591 | 
|  | 592     return class_pat | 
|  | 593 | 
|  | 594 ############################ conversion ############################################## | 
|  | 595 #conversion from svg to png | 
|  | 596 def svg_to_png_with_background(svg_path :utils.FilePath, png_path :utils.FilePath, dpi :int = 72, scale :int = 1, size :Optional[float] = None) -> None: | 
|  | 597     """ | 
|  | 598     Internal utility to convert an SVG to PNG (forced opaque) to aid in PDF conversion. | 
|  | 599 | 
|  | 600     Args: | 
|  | 601         svg_path : path to SVG file | 
|  | 602         png_path : path for new PNG file | 
|  | 603         dpi : dots per inch of the generated PNG | 
|  | 604         scale : scaling factor for the generated PNG, computed internally when a size is provided | 
|  | 605         size : final effective width of the generated PNG | 
|  | 606 | 
|  | 607     Returns: | 
|  | 608         None | 
|  | 609     """ | 
|  | 610     if size: | 
|  | 611         image = pyvips.Image.new_from_file(svg_path.show(), dpi=dpi, scale=1) | 
|  | 612         scale = size / image.width | 
|  | 613         image = image.resize(scale) | 
|  | 614     else: | 
|  | 615         image = pyvips.Image.new_from_file(svg_path.show(), dpi=dpi, scale=scale) | 
|  | 616 | 
|  | 617     white_background = pyvips.Image.black(image.width, image.height).new_from_image([255, 255, 255]) | 
|  | 618     white_background = white_background.affine([scale, 0, 0, scale]) | 
|  | 619 | 
|  | 620     if white_background.bands != image.bands: | 
|  | 621         white_background = white_background.extract_band(0) | 
|  | 622 | 
|  | 623     composite_image = white_background.composite2(image, 'over') | 
|  | 624     composite_image.write_to_file(png_path.show()) | 
|  | 625 | 
|  | 626 def convert_to_pdf(file_svg :utils.FilePath, file_png :utils.FilePath, file_pdf :utils.FilePath) -> None: | 
|  | 627     """ | 
|  | 628     Converts the SVG map at the provided path to PDF. | 
|  | 629 | 
|  | 630     Args: | 
|  | 631         file_svg : path to SVG file | 
|  | 632         file_png : path to PNG file | 
|  | 633         file_pdf : path to new PDF file | 
|  | 634 | 
|  | 635     Returns: | 
|  | 636         None | 
|  | 637     """ | 
|  | 638     svg_to_png_with_background(file_svg, file_png) | 
|  | 639     try: | 
| 291 | 640         image = Image.open(file_png.show()) | 
|  | 641         image = image.convert("RGB") | 
|  | 642         image.save(file_pdf.show(), "PDF", resolution=100.0) | 
| 4 | 643         print(f'PDF file {file_pdf.filePath} successfully generated.') | 
|  | 644 | 
|  | 645     except Exception as e: | 
|  | 646         raise utils.DataErr(file_pdf.show(), f'Error generating PDF file: {e}') | 
|  | 647 | 
|  | 648 ############################ map ############################################## | 
|  | 649 def buildOutputPath(dataset1Name :str, dataset2Name = "rest", *, details = "", ext :utils.FileFormat) -> utils.FilePath: | 
|  | 650     """ | 
|  | 651     Builds a FilePath instance from the names of confronted datasets ready to point to a location in the | 
|  | 652     "result/" folder, used by this tool for output files in collections. | 
|  | 653 | 
|  | 654     Args: | 
|  | 655         dataset1Name : _description_ | 
|  | 656         dataset2Name : _description_. Defaults to "rest". | 
|  | 657         details : _description_ | 
|  | 658         ext : _description_ | 
|  | 659 | 
|  | 660     Returns: | 
|  | 661         utils.FilePath : _description_ | 
|  | 662     """ | 
|  | 663     # This function returns a util data structure but is extremely specific to this module. | 
|  | 664     # RAS also uses collections as output and as such might benefit from a method like this, but I'd wait | 
|  | 665     # TODO: until a third tool with multiple outputs appears before porting this to utils. | 
|  | 666     return utils.FilePath( | 
|  | 667         f"{dataset1Name}_vs_{dataset2Name}" + (f" ({details})" if details else ""), | 
|  | 668         # ^^^ yes this string is built every time even if the form is the same for the same 2 datasets in | 
|  | 669         # all output files: I don't care, this was never the performance bottleneck of the tool and | 
|  | 670         # there is no other net gain in saving and re-using the built string. | 
|  | 671         ext, | 
| 146 | 672         prefix = ARGS.output_path) | 
| 4 | 673 | 
|  | 674 FIELD_NOT_AVAILABLE = '/' | 
|  | 675 def writeToCsv(rows: List[list], fieldNames :List[str], outPath :utils.FilePath) -> None: | 
|  | 676     fieldsAmt = len(fieldNames) | 
|  | 677     with open(outPath.show(), "w", newline = "") as fd: | 
|  | 678         writer = csv.DictWriter(fd, fieldnames = fieldNames, delimiter = '\t') | 
|  | 679         writer.writeheader() | 
|  | 680 | 
|  | 681         for row in rows: | 
|  | 682             sizeMismatch = fieldsAmt - len(row) | 
|  | 683             if sizeMismatch > 0: row.extend([FIELD_NOT_AVAILABLE] * sizeMismatch) | 
|  | 684             writer.writerow({ field : data for field, data in zip(fieldNames, row) }) | 
|  | 685 | 
|  | 686 OldEnrichedScores = Dict[str, List[Union[float, FoldChange]]] #TODO: try to use Tuple whenever possible | 
| 291 | 687 def temp_thingsInCommon(tmp :OldEnrichedScores, core_map :ET.ElementTree, max_z_score :float, dataset1Name :str, dataset2Name = "rest", ras_enrichment = True) -> None: | 
| 4 | 688     # this function compiles the things always in common between comparison modes after enrichment. | 
|  | 689     # TODO: organize, name better. | 
| 278 | 690     suffix = "RAS" if ras_enrichment else "RPS" | 
| 291 | 691     writeToCsv( | 
|  | 692         [ [reactId] + values for reactId, values in tmp.items() ], | 
| 319 | 693         ["ids", "P_Value", "fold change", "z-score", "average_1", "average_2"], | 
| 291 | 694         buildOutputPath(dataset1Name, dataset2Name, details = f"Tabular Result ({suffix})", ext = utils.FileFormat.TSV)) | 
| 4 | 695 | 
|  | 696     if ras_enrichment: | 
|  | 697         fix_map(tmp, core_map, ARGS.pValue, ARGS.fChange, max_z_score) | 
|  | 698         return | 
|  | 699 | 
|  | 700     for reactId, enrichData in tmp.items(): tmp[reactId] = tuple(enrichData) | 
|  | 701     applyRpsEnrichmentToMap(tmp, core_map, max_z_score) | 
|  | 702 | 
|  | 703 def computePValue(dataset1Data: List[float], dataset2Data: List[float]) -> Tuple[float, float]: | 
|  | 704     """ | 
|  | 705     Computes the statistical significance score (P-value) of the comparison between coherent data | 
|  | 706     from two datasets. The data is supposed to, in both datasets: | 
|  | 707     - be related to the same reaction ID; | 
|  | 708     - be ordered by sample, such that the item at position i in both lists is related to the | 
|  | 709       same sample or cell line. | 
|  | 710 | 
|  | 711     Args: | 
|  | 712         dataset1Data : data from the 1st dataset. | 
|  | 713         dataset2Data : data from the 2nd dataset. | 
|  | 714 | 
|  | 715     Returns: | 
|  | 716         tuple: (P-value, Z-score) | 
| 293 | 717             - P-value from the selected test on the provided data. | 
| 4 | 718             - Z-score of the difference between means of the two datasets. | 
|  | 719     """ | 
| 293 | 720     match ARGS.test: | 
|  | 721         case "ks": | 
|  | 722             # Perform Kolmogorov-Smirnov test | 
|  | 723             _, p_value = st.ks_2samp(dataset1Data, dataset2Data) | 
|  | 724         case "ttest_p": | 
| 299 | 725             # Datasets should have same size | 
|  | 726             if len(dataset1Data) != len(dataset2Data): | 
|  | 727                 raise ValueError("Datasets must have the same size for paired t-test.") | 
| 293 | 728             # Perform t-test for paired samples | 
|  | 729             _, p_value = st.ttest_rel(dataset1Data, dataset2Data) | 
|  | 730         case "ttest_ind": | 
|  | 731             # Perform t-test for independent samples | 
|  | 732             _, p_value = st.ttest_ind(dataset1Data, dataset2Data) | 
|  | 733         case "wilcoxon": | 
| 299 | 734             # Datasets should have same size | 
|  | 735             if len(dataset1Data) != len(dataset2Data): | 
|  | 736                 raise ValueError("Datasets must have the same size for Wilcoxon signed-rank test.") | 
| 293 | 737             # Perform Wilcoxon signed-rank test | 
| 320 | 738             np.random.seed(42) # Ensure reproducibility since zsplit method is used | 
|  | 739             _, p_value = st.wilcoxon(dataset1Data, dataset2Data, zero_method='zsplit') | 
| 293 | 740         case "mw": | 
|  | 741             # Perform Mann-Whitney U test | 
|  | 742             _, p_value = st.mannwhitneyu(dataset1Data, dataset2Data) | 
| 300 | 743         case _: | 
|  | 744             p_value = np.nan # Default value if no valid test is selected | 
| 4 | 745 | 
|  | 746     # Calculate means and standard deviations | 
|  | 747     mean1 = np.mean(dataset1Data) | 
|  | 748     mean2 = np.mean(dataset2Data) | 
|  | 749     std1 = np.std(dataset1Data, ddof=1) | 
|  | 750     std2 = np.std(dataset2Data, ddof=1) | 
|  | 751 | 
|  | 752     n1 = len(dataset1Data) | 
|  | 753     n2 = len(dataset2Data) | 
|  | 754 | 
|  | 755     # Calculate Z-score | 
|  | 756     z_score = (mean1 - mean2) / np.sqrt((std1**2 / n1) + (std2**2 / n2)) | 
|  | 757 | 
|  | 758     return p_value, z_score | 
|  | 759 | 
| 300 | 760 | 
|  | 761 def DESeqPValue(comparisonResult :Dict[str, List[Union[float, FoldChange]]], dataset1Data :List[List[float]], dataset2Data :List[List[float]], ids :List[str]) -> None: | 
|  | 762     """ | 
|  | 763     Computes the p-value for each reaction in the comparisonResult dictionary using DESeq2. | 
|  | 764 | 
|  | 765     Args: | 
|  | 766         comparisonResult : dictionary mapping a p-value and a fold-change value (values) to each reaction ID as encoded in the SVG map (keys) | 
|  | 767         dataset1Data : data from the 1st dataset. | 
|  | 768         dataset2Data : data from the 2nd dataset. | 
|  | 769         ids : list of reaction IDs. | 
|  | 770 | 
|  | 771     Returns: | 
|  | 772         None : mutates the comparisonResult dictionary in place with the p-values. | 
|  | 773     """ | 
|  | 774 | 
| 313 | 775     # pyDESeq2 needs at least 2 replicates per sample so I check this | 
|  | 776     if len(dataset1Data[0]) < 2 or len(dataset2Data[0]) < 2: | 
|  | 777         raise ValueError("Datasets must have at least 2 replicates each") | 
|  | 778 | 
| 300 | 779     # pyDESeq2 is based on pandas, so we need to convert the data into a DataFrame and clean it from NaN values | 
|  | 780     dataframe1 = pd.DataFrame(dataset1Data, index=ids) | 
|  | 781     dataframe2 = pd.DataFrame(dataset2Data, index=ids) | 
| 313 | 782 | 
|  | 783     # pyDESeq2 requires datasets to be samples x reactions and integer values | 
| 300 | 784     dataframe1_clean = dataframe1.dropna(axis=0, how="any").T.astype(int) | 
|  | 785     dataframe2_clean = dataframe2.dropna(axis=0, how="any").T.astype(int) | 
| 313 | 786     dataframe1_clean.index = [f"ds1_rep{i+1}" for i in range(dataframe1_clean.shape[0])] | 
|  | 787     dataframe2_clean.index = [f"ds2_rep{j+1}" for j in range(dataframe2_clean.shape[0])] | 
| 300 | 788 | 
| 313 | 789     # pyDESeq2 works on a DataFrame with values and another with infos about how samples are split (like dataset class) | 
| 300 | 790     dataframe = pd.concat([dataframe1_clean, dataframe2_clean], axis=0) | 
| 313 | 791     metadata = pd.DataFrame({"dataset": (["dataset1"]*dataframe1_clean.shape[0] + ["dataset2"]*dataframe2_clean.shape[0])}, index=dataframe.index) | 
|  | 792 | 
|  | 793     # Ensure the index of the metadata matches the index of the dataframe | 
|  | 794     if not dataframe.index.equals(metadata.index): | 
|  | 795         raise ValueError("The index of the metadata DataFrame must match the index of the counts DataFrame.") | 
| 300 | 796 | 
|  | 797     # Prepare and run pyDESeq2 | 
|  | 798     inference = DefaultInference() | 
|  | 799     dds = DeseqDataSet(counts=dataframe, metadata=metadata, design="~dataset", inference=inference, quiet=True, low_memory=True) | 
|  | 800     dds.deseq2() | 
|  | 801     ds = DeseqStats(dds, contrast=["dataset", "dataset1", "dataset2"], inference=inference, quiet=True) | 
|  | 802     ds.summary() | 
|  | 803 | 
|  | 804     # Retrieve the p-values from the DESeq2 results | 
|  | 805     for reactId in ds.results_df.index: | 
|  | 806         comparisonResult[reactId][0] = ds.results_df["pvalue"][reactId] | 
|  | 807 | 
|  | 808 | 
| 299 | 809 # TODO: the net RPS computation should be done in the RPS module | 
|  | 810 def compareDatasetPair(dataset1Data :List[List[float]], dataset2Data :List[List[float]], ids :List[str]) -> Tuple[Dict[str, List[Union[float, FoldChange]]], float, Dict[str, Tuple[np.ndarray, np.ndarray]]]: | 
| 300 | 811 | 
| 4 | 812     #TODO: the following code still suffers from "dumbvarnames-osis" | 
| 299 | 813     netRPS :Dict[str, Tuple[np.ndarray, np.ndarray]] = {} | 
| 291 | 814     comparisonResult :Dict[str, List[Union[float, FoldChange]]] = {} | 
| 4 | 815     count   = 0 | 
|  | 816     max_z_score = 0 | 
|  | 817 | 
|  | 818     for l1, l2 in zip(dataset1Data, dataset2Data): | 
|  | 819         reactId = ids[count] | 
|  | 820         count += 1 | 
|  | 821         if not reactId: continue # we skip ids that have already been processed | 
|  | 822 | 
|  | 823         try: #TODO: identify the source of these errors and minimize code in the try block | 
|  | 824             reactDir = ReactionDirection.fromReactionId(reactId) | 
|  | 825             # Net score is computed only for reversible reactions when user wants it on arrow tips or when RAS datasets aren't used | 
|  | 826             if (ARGS.net or not ARGS.using_RAS) and reactDir is not ReactionDirection.Unknown: | 
|  | 827                 try: position = ids.index(reactId[:-1] + ('B' if reactDir is ReactionDirection.Direct else 'F')) | 
|  | 828                 except ValueError: continue # we look for the complementary id, if not found we skip | 
|  | 829 | 
|  | 830                 nets1 = np.subtract(l1, dataset1Data[position]) | 
|  | 831                 nets2 = np.subtract(l2, dataset2Data[position]) | 
| 299 | 832                 netRPS[reactId] = (nets1, nets2) | 
| 4 | 833 | 
| 300 | 834                 # Compute p-value and z-score for the RPS scores, if the pyDESeq option is set, p-values will be computed after and this function will return p_value = 0 | 
| 4 | 835                 p_value, z_score = computePValue(nets1, nets2) | 
|  | 836                 avg1 = sum(nets1)   / len(nets1) | 
|  | 837                 avg2 = sum(nets2)   / len(nets2) | 
|  | 838                 net = fold_change(avg1, avg2) | 
|  | 839 | 
|  | 840                 if math.isnan(net): continue | 
| 291 | 841                 comparisonResult[reactId[:-1] + "RV"] = [p_value, net, z_score, avg1, avg2] | 
| 4 | 842 | 
|  | 843                 # vvv complementary directional ids are set to None once processed if net is to be applied to tips | 
| 291 | 844                 if ARGS.net: # If only using RPS, we cannot delete the inverse, as it's needed to color the arrows | 
| 4 | 845                     ids[position] = None | 
|  | 846                     continue | 
|  | 847 | 
|  | 848             # fallthrough is intended, regular scores need to be computed when tips aren't net but RAS datasets aren't used | 
| 300 | 849             # Compute p-value and z-score for the RAS scores, if the pyDESeq option is set, p-values will be computed after and this function will return p_value = 0 | 
| 4 | 850             p_value, z_score = computePValue(l1, l2) | 
|  | 851             avg = fold_change(sum(l1) / len(l1), sum(l2) / len(l2)) | 
| 291 | 852             # vvv TODO: Check numpy version compatibility | 
|  | 853             if np.isfinite(z_score) and max_z_score < abs(z_score): max_z_score = abs(z_score) | 
|  | 854             comparisonResult[reactId] = [float(p_value), avg, z_score, sum(l1) / len(l1), sum(l2) / len(l2)] | 
| 4 | 855 | 
|  | 856         except (TypeError, ZeroDivisionError): continue | 
|  | 857 | 
| 300 | 858     if ARGS.test == "DESeq": | 
|  | 859         # Compute p-values using DESeq2 | 
|  | 860         DESeqPValue(comparisonResult, dataset1Data, dataset2Data, ids) | 
|  | 861 | 
| 297 | 862     # Apply multiple testing correction if set by the user | 
|  | 863     if ARGS.adjusted: | 
| 300 | 864 | 
|  | 865         # Retrieve the p-values from the comparisonResult dictionary, they have to be different from NaN | 
|  | 866         validPValues = [(reactId, result[0]) for reactId, result in comparisonResult.items() if not np.isnan(result[0])] | 
|  | 867         # Unpack the valid p-values | 
|  | 868         reactIds, pValues = zip(*validPValues) | 
|  | 869         # Adjust the p-values using the Benjamini-Hochberg method | 
|  | 870         adjustedPValues = st.false_discovery_control(pValues) | 
|  | 871         # Update the comparisonResult dictionary with the adjusted p-values | 
|  | 872         for reactId , adjustedPValue in zip(reactIds, adjustedPValues): | 
|  | 873             comparisonResult[reactId][0] = adjustedPValue | 
| 297 | 874 | 
| 299 | 875     return comparisonResult, max_z_score, netRPS | 
| 4 | 876 | 
| 299 | 877 def computeEnrichment(class_pat: Dict[str, List[List[float]]], ids: List[str], *, fromRAS=True) -> Tuple[List[Tuple[str, str, dict, float]], dict]: | 
| 4 | 878     """ | 
|  | 879     Compares clustered data based on a given comparison mode and applies enrichment-based styling on the | 
|  | 880     provided metabolic map. | 
|  | 881 | 
|  | 882     Args: | 
|  | 883         class_pat : the clustered data. | 
|  | 884         ids : ids for data association. | 
|  | 885         fromRAS : whether the data to enrich consists of RAS scores. | 
|  | 886 | 
|  | 887     Returns: | 
| 299 | 888         tuple: A tuple containing: | 
|  | 889         - List[Tuple[str, str, dict, float]]: List of tuples with pairs of dataset names, comparison dictionary and max z-score. | 
|  | 890         - dict : net RPS values for each dataset's reactions | 
|  | 891 | 
| 4 | 892     Raises: | 
|  | 893         sys.exit : if there are less than 2 classes for comparison | 
|  | 894     """ | 
| 143 | 895     class_pat = {k.strip(): v for k, v in class_pat.items()} | 
|  | 896     if (not class_pat) or (len(class_pat.keys()) < 2): | 
|  | 897         sys.exit('Execution aborted: classes provided for comparisons are less than two\n') | 
|  | 898 | 
| 299 | 899     # { datasetName : { reactId : netRPS, ... }, ... } | 
|  | 900     netRPSResults :Dict[str, Dict[str, np.ndarray]] = {} | 
| 143 | 901     enrichment_results = [] | 
| 4 | 902 | 
|  | 903     if ARGS.comparison == "manyvsmany": | 
|  | 904         for i, j in it.combinations(class_pat.keys(), 2): | 
| 299 | 905             comparisonDict, max_z_score, netRPS = compareDatasetPair(class_pat.get(i), class_pat.get(j), ids) | 
| 143 | 906             enrichment_results.append((i, j, comparisonDict, max_z_score)) | 
| 299 | 907             netRPSResults[i] = { reactId : net[0] for reactId, net in netRPS.items() } | 
|  | 908             netRPSResults[j] = { reactId : net[1] for reactId, net in netRPS.items() } | 
| 4 | 909 | 
|  | 910     elif ARGS.comparison == "onevsrest": | 
|  | 911         for single_cluster in class_pat.keys(): | 
| 143 | 912             rest = [item for k, v in class_pat.items() if k != single_cluster for item in v] | 
| 299 | 913             comparisonDict, max_z_score, netRPS = compareDatasetPair(class_pat.get(single_cluster), rest, ids) | 
| 143 | 914             enrichment_results.append((single_cluster, "rest", comparisonDict, max_z_score)) | 
| 299 | 915             netRPSResults[single_cluster] = { reactId : net[0] for reactId, net in netRPS.items() } | 
|  | 916             netRPSResults["rest"]         = { reactId : net[1] for reactId, net in netRPS.items() } | 
| 4 | 917 | 
|  | 918     elif ARGS.comparison == "onevsmany": | 
|  | 919         controlItems = class_pat.get(ARGS.control) | 
|  | 920         for otherDataset in class_pat.keys(): | 
| 143 | 921             if otherDataset == ARGS.control: | 
|  | 922                 continue | 
| 299 | 923 | 
| 322 | 924             #comparisonDict, max_z_score, netRPS = compareDatasetPair(controlItems, class_pat.get(otherDataset), ids) | 
|  | 925             comparisonDict, max_z_score, netRPS = compareDatasetPair(class_pat.get(otherDataset),controlItems, ids) | 
|  | 926             #enrichment_results.append((ARGS.control, otherDataset, comparisonDict, max_z_score)) | 
|  | 927             enrichment_results.append(( otherDataset,ARGS.control, comparisonDict, max_z_score)) | 
|  | 928             netRPSResults[otherDataset] = { reactId : net[0] for reactId, net in netRPS.items() } | 
|  | 929             netRPSResults[ARGS.control] = { reactId : net[1] for reactId, net in netRPS.items() } | 
| 143 | 930 | 
| 299 | 931     return enrichment_results, netRPSResults | 
| 4 | 932 | 
| 143 | 933 def createOutputMaps(dataset1Name: str, dataset2Name: str, core_map: ET.ElementTree) -> None: | 
|  | 934     svgFilePath = buildOutputPath(dataset1Name, dataset2Name, details="SVG Map", ext=utils.FileFormat.SVG) | 
| 4 | 935     utils.writeSvg(svgFilePath, core_map) | 
|  | 936 | 
|  | 937     if ARGS.generate_pdf: | 
| 143 | 938         pngPath = buildOutputPath(dataset1Name, dataset2Name, details="PNG Map", ext=utils.FileFormat.PNG) | 
|  | 939         pdfPath = buildOutputPath(dataset1Name, dataset2Name, details="PDF Map", ext=utils.FileFormat.PDF) | 
| 291 | 940         svg_to_png_with_background(svgFilePath, pngPath) | 
|  | 941         try: | 
|  | 942             image = Image.open(pngPath.show()) | 
|  | 943             image = image.convert("RGB") | 
|  | 944             image.save(pdfPath.show(), "PDF", resolution=100.0) | 
|  | 945             print(f'PDF file {pdfPath.filePath} successfully generated.') | 
|  | 946 | 
|  | 947         except Exception as e: | 
|  | 948             raise utils.DataErr(pdfPath.show(), f'Error generating PDF file: {e}') | 
| 4 | 949 | 
| 291 | 950     if not ARGS.generate_svg: # This argument is useless, who cares if the user wants the svg or not | 
| 145 | 951         os.remove(svgFilePath.show()) | 
| 4 | 952 | 
|  | 953 ClassPat = Dict[str, List[List[float]]] | 
| 299 | 954 def getClassesAndIdsFromDatasets(datasetsPaths :List[str], datasetPath :str, classPath :str, names :List[str]) -> Tuple[List[str], ClassPat, Dict[str, List[str]]]: | 
| 4 | 955     # TODO: I suggest creating dicts with ids as keys instead of keeping class_pat and ids separate, | 
|  | 956     # for the sake of everyone's sanity. | 
| 299 | 957     columnNames :Dict[str, List[str]] = {} # { datasetName : [ columnName, ... ], ... } | 
| 4 | 958     class_pat :ClassPat = {} | 
|  | 959     if ARGS.option == 'datasets': | 
| 291 | 960         num = 1 | 
| 4 | 961         for path, name in zip(datasetsPaths, names): | 
| 291 | 962             name = str(name) | 
|  | 963             if name == 'Dataset': | 
|  | 964                 name += '_' + str(num) | 
|  | 965 | 
|  | 966             values, ids = getDatasetValues(path, name) | 
|  | 967             if values != None: | 
| 299 | 968                 class_pat[name]   = list(map(list, zip(*values.values()))) # TODO: ??? | 
| 318 | 969                 columnNames[name] = ["Reactions", *values.keys()] | 
| 291 | 970 | 
| 4 | 971             num += 1 | 
|  | 972 | 
|  | 973     elif ARGS.option == "dataset_class": | 
|  | 974         classes = read_dataset(classPath, "class") | 
|  | 975         classes = classes.astype(str) | 
|  | 976 | 
| 291 | 977         values, ids = getDatasetValues(datasetPath, "Dataset Class (not actual name)") | 
| 299 | 978         if values != None: | 
| 309 | 979             class_pat_with_samples_id = split_class(classes, values) | 
|  | 980 | 
|  | 981             for clas, values_and_samples_id in class_pat_with_samples_id.items(): | 
|  | 982                 class_pat[clas] = values_and_samples_id["values"] | 
| 318 | 983                 columnNames[clas] = ["Reactions", *values_and_samples_id["samples"]] | 
| 4 | 984 | 
| 299 | 985     return ids, class_pat, columnNames | 
| 4 | 986     #^^^ TODO: this could be a match statement over an enum, make it happen future marea dev with python 3.12! (it's why I kept the ifs) | 
|  | 987 | 
|  | 988 #TODO: create these damn args as FilePath objects | 
|  | 989 def getDatasetValues(datasetPath :str, datasetName :str) -> Tuple[ClassPat, List[str]]: | 
|  | 990     """ | 
|  | 991     Opens the dataset at the given path and extracts the values (expected nullable numerics) and the IDs. | 
|  | 992 | 
|  | 993     Args: | 
|  | 994         datasetPath : path to the dataset | 
|  | 995         datasetName (str): dataset name, used in error reporting | 
|  | 996 | 
|  | 997     Returns: | 
|  | 998         Tuple[ClassPat, List[str]]: values and IDs extracted from the dataset | 
|  | 999     """ | 
|  | 1000     dataset = read_dataset(datasetPath, datasetName) | 
|  | 1001     IDs = pd.Series.tolist(dataset.iloc[:, 0].astype(str)) | 
|  | 1002 | 
|  | 1003     dataset = dataset.drop(dataset.columns[0], axis = "columns").to_dict("list") | 
|  | 1004     return { id : list(map(utils.Float("Dataset values, not an argument"), values)) for id, values in dataset.items() }, IDs | 
|  | 1005 | 
|  | 1006 ############################ MAIN ############################################# | 
| 147 | 1007 def main(args:List[str] = None) -> None: | 
| 4 | 1008     """ | 
|  | 1009     Initializes everything and sets the program in motion based on the fronted input arguments. | 
|  | 1010 | 
|  | 1011     Returns: | 
|  | 1012         None | 
|  | 1013 | 
|  | 1014     Raises: | 
|  | 1015         sys.exit : if a user-provided custom map is in the wrong format (ET.XMLSyntaxError, ET.XMLSchemaParseError) | 
|  | 1016     """ | 
|  | 1017     global ARGS | 
| 146 | 1018     ARGS = process_args(args) | 
| 4 | 1019 | 
| 291 | 1020     # Create output folder | 
| 146 | 1021     if not os.path.isdir(ARGS.output_path): | 
| 286 | 1022         os.makedirs(ARGS.output_path, exist_ok=True) | 
| 4 | 1023 | 
| 143 | 1024     core_map: ET.ElementTree = ARGS.choice_map.getMap( | 
| 4 | 1025         ARGS.tool_dir, | 
|  | 1026         utils.FilePath.fromStrPath(ARGS.custom_map) if ARGS.custom_map else None) | 
| 143 | 1027 | 
| 291 | 1028     # TODO: in the future keep the indices WITH the data and fix the code below. | 
|  | 1029 | 
| 286 | 1030     # Prepare enrichment results containers | 
| 284 | 1031     ras_results = [] | 
|  | 1032     rps_results = [] | 
|  | 1033 | 
|  | 1034     # Compute RAS enrichment if requested | 
| 299 | 1035     if ARGS.using_RAS: #       vvv columnNames only matter with RPS data | 
|  | 1036         ids_ras, class_pat_ras, _ = getClassesAndIdsFromDatasets( | 
| 284 | 1037             ARGS.input_datas, ARGS.input_data, ARGS.input_class, ARGS.names) | 
| 299 | 1038         ras_results, _ = computeEnrichment(class_pat_ras, ids_ras, fromRAS=True) | 
|  | 1039         #           ^^^ netRPS only matter with RPS data | 
| 284 | 1040 | 
|  | 1041     # Compute RPS enrichment if requested | 
| 4 | 1042     if ARGS.using_RPS: | 
| 299 | 1043         ids_rps, class_pat_rps, columnNames = getClassesAndIdsFromDatasets( | 
| 284 | 1044             ARGS.input_datas_rps, ARGS.input_data_rps, ARGS.input_class_rps, ARGS.names_rps) | 
| 299 | 1045 | 
|  | 1046         rps_results, netRPS = computeEnrichment(class_pat_rps, ids_rps, fromRAS=False) | 
| 284 | 1047 | 
|  | 1048     # Organize by comparison pairs | 
|  | 1049     comparisons: Dict[Tuple[str, str], Dict[str, Tuple]] = {} | 
| 291 | 1050     for i, j, comparison_data, max_z_score in ras_results: | 
|  | 1051         comparisons[(i, j)] = {'ras': (comparison_data, max_z_score), 'rps': None} | 
| 299 | 1052 | 
|  | 1053     for i, j, comparison_data, max_z_score,  in rps_results: | 
| 291 | 1054         comparisons.setdefault((i, j), {}).update({'rps': (comparison_data, max_z_score)}) | 
| 4 | 1055 | 
| 284 | 1056     # For each comparison, create a styled map with RAS bodies and RPS heads | 
|  | 1057     for (i, j), res in comparisons.items(): | 
|  | 1058         map_copy = copy.deepcopy(core_map) | 
|  | 1059 | 
|  | 1060         # Apply RAS styling to arrow bodies | 
|  | 1061         if res.get('ras'): | 
|  | 1062             tmp_ras, max_z_ras = res['ras'] | 
|  | 1063             temp_thingsInCommon(tmp_ras, map_copy, max_z_ras, i, j, ras_enrichment=True) | 
|  | 1064 | 
|  | 1065         # Apply RPS styling to arrow heads | 
|  | 1066         if res.get('rps'): | 
|  | 1067             tmp_rps, max_z_rps = res['rps'] | 
| 291 | 1068             # applyRpsEnrichmentToMap styles only heads unless only RPS are used | 
| 285 | 1069             temp_thingsInCommon(tmp_rps, map_copy, max_z_rps, i, j, ras_enrichment=False) | 
| 284 | 1070 | 
|  | 1071         # Output both SVG and PDF/PNG as configured | 
|  | 1072         createOutputMaps(i, j, map_copy) | 
| 299 | 1073 | 
|  | 1074     # Add net RPS output file | 
|  | 1075     if ARGS.net or not ARGS.using_RAS: | 
|  | 1076         for datasetName, rows in netRPS.items(): | 
|  | 1077             writeToCsv( | 
|  | 1078                 [[reactId, *netValues] for reactId, netValues in rows.items()], | 
|  | 1079                 # vvv In weird comparison modes the dataset names are not recorded properly.. | 
| 300 | 1080                 columnNames.get(datasetName, ["Reactions"]), | 
| 299 | 1081                 utils.FilePath( | 
| 300 | 1082                     "Net_RPS_" + datasetName, | 
|  | 1083                     ext = utils.FileFormat.CSV, | 
|  | 1084                     prefix = ARGS.output_path)) | 
| 299 | 1085 | 
| 143 | 1086     print('Execution succeeded') | 
| 4 | 1087 ############################################################################### | 
|  | 1088 if __name__ == "__main__": | 
| 309 | 1089     main() |