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