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