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