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