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