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