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