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