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 copy
|
|
16 import argparse
|
|
17 import pyvips
|
293
|
18 from PIL import Image
|
4
|
19 from typing import Tuple, Union, Optional, List, Dict
|
|
20 import matplotlib.pyplot as plt
|
|
21
|
|
22 ERRORS = []
|
|
23 ########################## argparse ##########################################
|
|
24 ARGS :argparse.Namespace
|
147
|
25 def process_args(args:List[str] = None) -> argparse.Namespace:
|
4
|
26 """
|
|
27 Interfaces the script of a module with its frontend, making the user's choices for various parameters available as values in code.
|
|
28
|
|
29 Args:
|
|
30 args : Always obtained (in file) from sys.argv
|
|
31
|
|
32 Returns:
|
|
33 Namespace : An object containing the parsed arguments
|
|
34 """
|
|
35 parser = argparse.ArgumentParser(
|
|
36 usage = "%(prog)s [options]",
|
|
37 description = "process some value's genes to create a comparison's map.")
|
|
38
|
|
39 #General:
|
|
40 parser.add_argument(
|
|
41 '-td', '--tool_dir',
|
|
42 type = str,
|
|
43 required = True,
|
|
44 help = 'your tool directory')
|
|
45
|
|
46 parser.add_argument('-on', '--control', type = str)
|
|
47 parser.add_argument('-ol', '--out_log', help = "Output log")
|
|
48
|
|
49 #Computation details:
|
|
50 parser.add_argument(
|
|
51 '-co', '--comparison',
|
|
52 type = str,
|
293
|
53 default = 'manyvsmany',
|
4
|
54 choices = ['manyvsmany', 'onevsrest', 'onevsmany'])
|
293
|
55
|
|
56 parser.add_argument(
|
|
57 '-te' ,'--test',
|
|
58 type = str,
|
|
59 default = 'ks',
|
|
60 choices = ['ks', 'ttest_p', 'ttest_ind', 'wilcoxon', 'mw'],
|
|
61 help = 'Statistical test to use (default: %(default)s)')
|
4
|
62
|
|
63 parser.add_argument(
|
|
64 '-pv' ,'--pValue',
|
|
65 type = float,
|
|
66 default = 0.1,
|
|
67 help = 'P-Value threshold (default: %(default)s)')
|
|
68
|
|
69 parser.add_argument(
|
|
70 '-fc', '--fChange',
|
|
71 type = float,
|
|
72 default = 1.5,
|
|
73 help = 'Fold-Change threshold (default: %(default)s)')
|
|
74
|
|
75
|
|
76 parser.add_argument(
|
|
77 '-op', '--option',
|
|
78 type = str,
|
|
79 choices = ['datasets', 'dataset_class'],
|
|
80 help='dataset or dataset and class')
|
|
81
|
|
82 parser.add_argument(
|
|
83 '-idf', '--input_data_fluxes',
|
|
84 type = str,
|
|
85 help = 'input dataset fluxes')
|
|
86
|
|
87 parser.add_argument(
|
|
88 '-icf', '--input_class_fluxes',
|
|
89 type = str,
|
|
90 help = 'sample group specification fluxes')
|
|
91
|
|
92 parser.add_argument(
|
|
93 '-idsf', '--input_datas_fluxes',
|
|
94 type = str,
|
|
95 nargs = '+',
|
|
96 help = 'input datasets fluxes')
|
|
97
|
|
98 parser.add_argument(
|
|
99 '-naf', '--names_fluxes',
|
|
100 type = str,
|
|
101 nargs = '+',
|
|
102 help = 'input names fluxes')
|
|
103
|
|
104 #Output:
|
|
105 parser.add_argument(
|
|
106 "-gs", "--generate_svg",
|
|
107 type = utils.Bool("generate_svg"), default = True,
|
|
108 help = "choose whether to generate svg")
|
|
109
|
|
110 parser.add_argument(
|
|
111 "-gp", "--generate_pdf",
|
|
112 type = utils.Bool("generate_pdf"), default = True,
|
|
113 help = "choose whether to generate pdf")
|
|
114
|
|
115 parser.add_argument(
|
|
116 '-cm', '--custom_map',
|
|
117 type = str,
|
|
118 help='custom map to use')
|
|
119
|
|
120 parser.add_argument(
|
|
121 '-mc', '--choice_map',
|
|
122 type = utils.Model, default = utils.Model.HMRcore,
|
|
123 choices = [utils.Model.HMRcore, utils.Model.ENGRO2, utils.Model.Custom])
|
|
124
|
|
125 parser.add_argument(
|
|
126 '-colorm', '--color_map',
|
|
127 type = str,
|
|
128 choices = ["jet", "viridis"])
|
147
|
129
|
|
130 parser.add_argument(
|
|
131 '-idop', '--output_path',
|
|
132 type = str,
|
|
133 default='result',
|
|
134 help = 'output path for maps')
|
4
|
135
|
147
|
136 args :argparse.Namespace = parser.parse_args(args)
|
185
|
137 args.net = True # TODO SICCOME I FLUSSI POSSONO ESSERE ANCHE NEGATIVI SONO SEMPRE CONSIDERATI NETTI
|
4
|
138
|
|
139 return args
|
293
|
140
|
4
|
141 ############################ dataset input ####################################
|
|
142 def read_dataset(data :str, name :str) -> pd.DataFrame:
|
|
143 """
|
|
144 Tries to read the dataset from its path (data) as a tsv and turns it into a DataFrame.
|
|
145
|
|
146 Args:
|
|
147 data : filepath of a dataset (from frontend input params or literals upon calling)
|
|
148 name : name associated with the dataset (from frontend input params or literals upon calling)
|
|
149
|
|
150 Returns:
|
|
151 pd.DataFrame : dataset in a runtime operable shape
|
|
152
|
|
153 Raises:
|
|
154 sys.exit : if there's no data (pd.errors.EmptyDataError) or if the dataset has less than 2 columns
|
|
155 """
|
|
156 try:
|
|
157 dataset = pd.read_csv(data, sep = '\t', header = 0, engine='python')
|
|
158 except pd.errors.EmptyDataError:
|
|
159 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
160 if len(dataset.columns) < 2:
|
|
161 sys.exit('Execution aborted: wrong format of ' + name + '\n')
|
|
162 return dataset
|
|
163
|
|
164 ############################ dataset name #####################################
|
|
165 def name_dataset(name_data :str, count :int) -> str:
|
|
166 """
|
|
167 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.
|
|
168
|
|
169 Args:
|
|
170 name_data : name associated with the dataset (from frontend input params)
|
|
171 count : counter from 1 to make these names unique (external)
|
|
172
|
|
173 Returns:
|
|
174 str : the name made unique
|
|
175 """
|
|
176 if str(name_data) == 'Dataset':
|
|
177 return str(name_data) + '_' + str(count)
|
|
178 else:
|
|
179 return str(name_data)
|
|
180
|
|
181 ############################ map_methods ######################################
|
|
182 FoldChange = Union[float, int, str] # Union[float, Literal[0, "-INF", "INF"]]
|
|
183 def fold_change(avg1 :float, avg2 :float) -> FoldChange:
|
|
184 """
|
|
185 Calculates the fold change between two gene expression values.
|
|
186
|
|
187 Args:
|
|
188 avg1 : average expression value from one dataset avg2 : average expression value from the other dataset
|
|
189
|
|
190 Returns:
|
|
191 FoldChange :
|
|
192 0 : when both input values are 0
|
|
193 "-INF" : when avg1 is 0
|
|
194 "INF" : when avg2 is 0
|
|
195 float : for any other combination of values
|
|
196 """
|
|
197 if avg1 == 0 and avg2 == 0:
|
|
198 return 0
|
|
199 elif avg1 == 0:
|
|
200 return '-INF'
|
|
201 elif avg2 == 0:
|
|
202 return 'INF'
|
|
203 else: # (threshold_F_C - 1) / (abs(threshold_F_C) + 1) con threshold_F_C > 1
|
|
204 return (avg1 - avg2) / (abs(avg1) + abs(avg2))
|
|
205
|
|
206 def getElementById(reactionId :str, metabMap :ET.ElementTree) -> utils.Result[ET.Element, utils.Result.ResultErr]:
|
|
207 """
|
|
208 Finds any element in the given map with the given ID. ID uniqueness in an svg file is recommended but
|
|
209 not enforced, if more than one element with the exact ID is found only the first will be returned.
|
|
210
|
|
211 Args:
|
|
212 reactionId (str): exact ID of the requested element.
|
|
213 metabMap (ET.ElementTree): metabolic map containing the element.
|
|
214
|
|
215 Returns:
|
|
216 utils.Result[ET.Element, ResultErr]: result of the search, either the first match found or a ResultErr.
|
|
217 """
|
|
218 return utils.Result.Ok(
|
|
219 f"//*[@id=\"{reactionId}\"]").map(
|
|
220 lambda xPath : metabMap.xpath(xPath)[0]).mapErr(
|
|
221 lambda _ : utils.Result.ResultErr(f"No elements with ID \"{reactionId}\" found in map"))
|
|
222 # ^^^ we shamelessly ignore the contents of the IndexError, it offers nothing to the user.
|
|
223
|
|
224 def styleMapElement(element :ET.Element, styleStr :str) -> None:
|
|
225 currentStyles :str = element.get("style", "")
|
|
226 if re.search(r";stroke:[^;]+;stroke-width:[^;]+;stroke-dasharray:[^;]+$", currentStyles):
|
|
227 currentStyles = ';'.join(currentStyles.split(';')[:-3])
|
|
228
|
|
229 element.set("style", currentStyles + styleStr)
|
|
230
|
|
231 class ReactionDirection(Enum):
|
|
232 Unknown = ""
|
|
233 Direct = "_F"
|
|
234 Inverse = "_B"
|
|
235
|
|
236 @classmethod
|
|
237 def fromDir(cls, s :str) -> "ReactionDirection":
|
|
238 # vvv as long as there's so few variants I actually condone the if spam:
|
|
239 if s == ReactionDirection.Direct.value: return ReactionDirection.Direct
|
|
240 if s == ReactionDirection.Inverse.value: return ReactionDirection.Inverse
|
|
241 return ReactionDirection.Unknown
|
|
242
|
|
243 @classmethod
|
|
244 def fromReactionId(cls, reactionId :str) -> "ReactionDirection":
|
|
245 return ReactionDirection.fromDir(reactionId[-2:])
|
|
246
|
|
247 def getArrowBodyElementId(reactionId :str) -> str:
|
|
248 if reactionId.endswith("_RV"): reactionId = reactionId[:-3] #TODO: standardize _RV
|
|
249 elif ReactionDirection.fromReactionId(reactionId) is not ReactionDirection.Unknown: reactionId = reactionId[:-2]
|
|
250 return f"R_{reactionId}"
|
|
251
|
|
252 def getArrowHeadElementId(reactionId :str) -> Tuple[str, str]:
|
|
253 """
|
|
254 We attempt extracting the direction information from the provided reaction ID, if unsuccessful we provide the IDs of both directions.
|
|
255
|
|
256 Args:
|
|
257 reactionId : the provided reaction ID.
|
|
258
|
|
259 Returns:
|
|
260 Tuple[str, str]: either a single str ID for the correct arrow head followed by an empty string or both options to try.
|
|
261 """
|
|
262 if reactionId.endswith("_RV"): reactionId = reactionId[:-3] #TODO: standardize _RV
|
|
263 elif ReactionDirection.fromReactionId(reactionId) is not ReactionDirection.Unknown: return reactionId[:-3:-1] + reactionId[:-2], ""
|
|
264 return f"F_{reactionId}", f"B_{reactionId}"
|
|
265
|
|
266 class ArrowColor(Enum):
|
|
267 """
|
|
268 Encodes possible arrow colors based on their meaning in the enrichment process.
|
|
269 """
|
|
270 Invalid = "#BEBEBE" # gray, fold-change under treshold
|
|
271 Transparent = "#ffffff00" # white, not significant p-value
|
|
272 UpRegulated = "#ecac68" # red, up-regulated reaction
|
|
273 DownRegulated = "#6495ed" # blue, down-regulated reaction
|
|
274
|
|
275 UpRegulatedInv = "#FF0000"
|
|
276 # ^^^ different shade of red (actually orange), up-regulated net value for a reversible reaction with
|
|
277 # conflicting enrichment in the two directions.
|
|
278
|
|
279 DownRegulatedInv = "#0000FF"
|
|
280 # ^^^ different shade of blue (actually purple), down-regulated net value for a reversible reaction with
|
|
281 # conflicting enrichment in the two directions.
|
|
282
|
|
283 @classmethod
|
|
284 def fromFoldChangeSign(cls, foldChange :float, *, useAltColor = False) -> "ArrowColor":
|
|
285 colors = (cls.DownRegulated, cls.DownRegulatedInv) if foldChange < 0 else (cls.UpRegulated, cls.UpRegulatedInv)
|
|
286 return colors[useAltColor]
|
|
287
|
|
288 def __str__(self) -> str: return self.value
|
|
289
|
|
290 class Arrow:
|
|
291 """
|
|
292 Models the properties of a reaction arrow that change based on enrichment.
|
|
293 """
|
|
294 MIN_W = 2
|
|
295 MAX_W = 12
|
|
296
|
|
297 def __init__(self, width :int, col: ArrowColor, *, isDashed = False) -> None:
|
|
298 """
|
|
299 (Private) Initializes an instance of Arrow.
|
|
300
|
|
301 Args:
|
|
302 width : width of the arrow, ideally to be kept within Arrow.MIN_W and Arrow.MAX_W (not enforced).
|
|
303 col : color of the arrow.
|
|
304 isDashed : whether the arrow should be dashed, meaning the associated pValue resulted not significant.
|
|
305
|
|
306 Returns:
|
|
307 None : practically, a Arrow instance.
|
|
308 """
|
|
309 self.w = width
|
|
310 self.col = col
|
|
311 self.dash = isDashed
|
|
312
|
|
313 def applyTo(self, reactionId :str, metabMap :ET.ElementTree, styleStr :str) -> None:
|
|
314 if getElementById(reactionId, metabMap).map(lambda el : styleMapElement(el, styleStr)).isErr:
|
|
315 ERRORS.append(reactionId)
|
|
316
|
|
317 def styleReactionElements(self, metabMap :ET.ElementTree, reactionId :str, *, mindReactionDir = True) -> None:
|
|
318 if not mindReactionDir:
|
|
319 return self.applyTo(getArrowBodyElementId(reactionId), metabMap, self.toStyleStr())
|
|
320
|
|
321 # Now we style the arrow head(s):
|
|
322 idOpt1, idOpt2 = getArrowHeadElementId(reactionId)
|
|
323 self.applyTo(idOpt1, metabMap, self.toStyleStr(downSizedForTips = True))
|
|
324 if idOpt2: self.applyTo(idOpt2, metabMap, self.toStyleStr(downSizedForTips = True))
|
|
325
|
|
326 def styleReactionElementsMeanMedian(self, metabMap :ET.ElementTree, reactionId :str, isNegative:bool) -> None:
|
|
327
|
|
328 self.applyTo(getArrowBodyElementId(reactionId), metabMap, self.toStyleStr())
|
|
329 idOpt1, idOpt2 = getArrowHeadElementId(reactionId)
|
|
330
|
|
331 if(isNegative):
|
|
332 self.applyTo(idOpt2, metabMap, self.toStyleStr(downSizedForTips = True))
|
|
333 self.col = ArrowColor.Transparent
|
|
334 self.applyTo(idOpt1, metabMap, self.toStyleStr(downSizedForTips = True)) #trasp
|
|
335 else:
|
|
336 self.applyTo(idOpt1, metabMap, self.toStyleStr(downSizedForTips = True))
|
|
337 self.col = ArrowColor.Transparent
|
|
338 self.applyTo(idOpt2, metabMap, self.toStyleStr(downSizedForTips = True)) #trasp
|
|
339
|
|
340
|
|
341
|
|
342 def getMapReactionId(self, reactionId :str, mindReactionDir :bool) -> str:
|
|
343 """
|
|
344 Computes the reaction ID as encoded in the map for a given reaction ID from the dataset.
|
|
345
|
|
346 Args:
|
|
347 reactionId: the reaction ID, as encoded in the dataset.
|
|
348 mindReactionDir: if True forward (F_) and backward (B_) directions will be encoded in the result.
|
|
349
|
|
350 Returns:
|
|
351 str : the ID of an arrow's body or tips in the map.
|
|
352 """
|
|
353 # we assume the reactionIds also don't encode reaction dir if they don't mind it when styling the map.
|
|
354 if not mindReactionDir: return "R_" + reactionId
|
|
355
|
|
356 #TODO: this is clearly something we need to make consistent in fluxes
|
|
357 return (reactionId[:-3:-1] + reactionId[:-2]) if reactionId[:-2] in ["_F", "_B"] else f"F_{reactionId}" # "Pyr_F" --> "F_Pyr"
|
|
358
|
|
359 def toStyleStr(self, *, downSizedForTips = False) -> str:
|
|
360 """
|
|
361 Collapses the styles of this Arrow into a str, ready to be applied as part of the "style" property on an svg element.
|
|
362
|
|
363 Returns:
|
|
364 str : the styles string.
|
|
365 """
|
|
366 width = self.w
|
|
367 if downSizedForTips: width *= 0.8
|
|
368 return f";stroke:{self.col};stroke-width:{width};stroke-dasharray:{'5,5' if self.dash else 'none'}"
|
|
369
|
|
370 # vvv These constants could be inside the class itself a static properties, but python
|
|
371 # was built by brainless organisms so here we are!
|
|
372 INVALID_ARROW = Arrow(Arrow.MIN_W, ArrowColor.Invalid)
|
|
373 INSIGNIFICANT_ARROW = Arrow(Arrow.MIN_W, ArrowColor.Invalid, isDashed = True)
|
|
374
|
|
375 def applyFluxesEnrichmentToMap(fluxesEnrichmentRes :Dict[str, Union[Tuple[float, FoldChange], Tuple[float, FoldChange, float, float]]], metabMap :ET.ElementTree, maxNumericZScore :float) -> None:
|
|
376 """
|
|
377 Applies fluxes enrichment results to the provided metabolic map.
|
|
378
|
|
379 Args:
|
|
380 fluxesEnrichmentRes : fluxes enrichment results.
|
|
381 metabMap : the metabolic map to edit.
|
|
382 maxNumericZScore : biggest finite z-score value found.
|
|
383
|
|
384 Side effects:
|
|
385 metabMap : mut
|
|
386
|
|
387 Returns:
|
|
388 None
|
|
389 """
|
|
390 for reactionId, values in fluxesEnrichmentRes.items():
|
|
391 pValue = values[0]
|
|
392 foldChange = values[1]
|
|
393 z_score = values[2]
|
|
394
|
275
|
395 if math.isnan(pValue) or (isinstance(foldChange, float) and math.isnan(foldChange)):
|
|
396 continue
|
|
397
|
4
|
398 if isinstance(foldChange, str): foldChange = float(foldChange)
|
|
399 if pValue >= ARGS.pValue: # pValue above tresh: dashed arrow
|
|
400 INSIGNIFICANT_ARROW.styleReactionElements(metabMap, reactionId)
|
|
401 INSIGNIFICANT_ARROW.styleReactionElements(metabMap, reactionId, mindReactionDir = False)
|
|
402
|
|
403 continue
|
|
404
|
|
405 if abs(foldChange) < (ARGS.fChange - 1) / (abs(ARGS.fChange) + 1):
|
|
406 INVALID_ARROW.styleReactionElements(metabMap, reactionId)
|
|
407 INVALID_ARROW.styleReactionElements(metabMap, reactionId, mindReactionDir = False)
|
|
408
|
|
409 continue
|
|
410
|
|
411 width = Arrow.MAX_W
|
293
|
412 if not math.isinf(z_score):
|
4
|
413 try:
|
293
|
414 width = min(
|
|
415 max(abs(z_score * Arrow.MAX_W) / maxNumericZScore, Arrow.MIN_W),
|
|
416 Arrow.MAX_W)
|
4
|
417
|
|
418 except ZeroDivisionError: pass
|
185
|
419 # TODO CHECK RV
|
4
|
420 #if not reactionId.endswith("_RV"): # RV stands for reversible reactions
|
197
|
421 # Arrow(width, ArrowColor.fromFoldChangeSign(foldChange)).styleReactionElements(metabMap, reactionId)
|
|
422 # continue
|
4
|
423
|
|
424 #reactionId = reactionId[:-3] # Remove "_RV"
|
|
425
|
|
426 inversionScore = (values[3] < 0) + (values[4] < 0) # Compacts the signs of averages into 1 easy to check score
|
|
427 if inversionScore == 2: foldChange *= -1
|
|
428 # ^^^ Style the inverse direction with the opposite sign netValue
|
|
429
|
|
430 # If the score is 1 (opposite signs) we use alternative colors vvv
|
|
431 arrow = Arrow(width, ArrowColor.fromFoldChangeSign(foldChange, useAltColor = inversionScore == 1))
|
|
432
|
|
433 # vvv These 2 if statements can both be true and can both happen
|
|
434 if ARGS.net: # style arrow head(s):
|
|
435 arrow.styleReactionElements(metabMap, reactionId + ("_B" if inversionScore == 2 else "_F"))
|
|
436 arrow.applyTo(("F_" if inversionScore == 2 else "B_") + reactionId, metabMap, f";stroke:{ArrowColor.Transparent};stroke-width:0;stroke-dasharray:None")
|
|
437
|
186
|
438 arrow.styleReactionElements(metabMap, reactionId, mindReactionDir = False)
|
4
|
439
|
|
440
|
|
441 ############################ split class ######################################
|
|
442 def split_class(classes :pd.DataFrame, resolve_rules :Dict[str, List[float]]) -> Dict[str, List[List[float]]]:
|
|
443 """
|
|
444 Generates a :dict that groups together data from a :DataFrame based on classes the data is related to.
|
|
445
|
|
446 Args:
|
|
447 classes : a :DataFrame of only string values, containing class information (rows) and keys to query the resolve_rules :dict
|
|
448 resolve_rules : a :dict containing :float data
|
|
449
|
|
450 Returns:
|
|
451 dict : the dict with data grouped by class
|
|
452
|
|
453 Side effects:
|
|
454 classes : mut
|
|
455 """
|
|
456 class_pat :Dict[str, List[List[float]]] = {}
|
|
457 for i in range(len(classes)):
|
|
458 classe :str = classes.iloc[i, 1]
|
|
459 if pd.isnull(classe): continue
|
|
460
|
|
461 l :List[List[float]] = []
|
|
462 for j in range(i, len(classes)):
|
|
463 if classes.iloc[j, 1] == classe:
|
|
464 pat_id :str = classes.iloc[j, 0]
|
|
465 tmp = resolve_rules.get(pat_id, None)
|
|
466 if tmp != None:
|
|
467 l.append(tmp)
|
|
468 classes.iloc[j, 1] = None
|
|
469
|
|
470 if l:
|
|
471 class_pat[classe] = list(map(list, zip(*l)))
|
|
472 continue
|
|
473
|
|
474 utils.logWarning(
|
|
475 f"Warning: no sample found in class \"{classe}\", the class has been disregarded", ARGS.out_log)
|
|
476
|
|
477 return class_pat
|
|
478
|
|
479 ############################ conversion ##############################################
|
|
480 #conversion from svg to png
|
|
481 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:
|
|
482 """
|
|
483 Internal utility to convert an SVG to PNG (forced opaque) to aid in PDF conversion.
|
|
484
|
|
485 Args:
|
|
486 svg_path : path to SVG file
|
|
487 png_path : path for new PNG file
|
|
488 dpi : dots per inch of the generated PNG
|
|
489 scale : scaling factor for the generated PNG, computed internally when a size is provided
|
|
490 size : final effective width of the generated PNG
|
|
491
|
|
492 Returns:
|
|
493 None
|
|
494 """
|
|
495 if size:
|
|
496 image = pyvips.Image.new_from_file(svg_path.show(), dpi=dpi, scale=1)
|
|
497 scale = size / image.width
|
|
498 image = image.resize(scale)
|
|
499 else:
|
|
500 image = pyvips.Image.new_from_file(svg_path.show(), dpi=dpi, scale=scale)
|
|
501
|
|
502 white_background = pyvips.Image.black(image.width, image.height).new_from_image([255, 255, 255])
|
|
503 white_background = white_background.affine([scale, 0, 0, scale])
|
|
504
|
|
505 if white_background.bands != image.bands:
|
|
506 white_background = white_background.extract_band(0)
|
|
507
|
|
508 composite_image = white_background.composite2(image, 'over')
|
|
509 composite_image.write_to_file(png_path.show())
|
|
510
|
|
511 #funzione unica, lascio fuori i file e li passo in input
|
|
512 #conversion from png to pdf
|
|
513 def convert_png_to_pdf(png_file :utils.FilePath, pdf_file :utils.FilePath) -> None:
|
|
514 """
|
|
515 Internal utility to convert a PNG to PDF to aid from SVG conversion.
|
|
516
|
|
517 Args:
|
|
518 png_file : path to PNG file
|
|
519 pdf_file : path to new PDF file
|
|
520
|
|
521 Returns:
|
|
522 None
|
|
523 """
|
|
524 image = Image.open(png_file.show())
|
|
525 image = image.convert("RGB")
|
|
526 image.save(pdf_file.show(), "PDF", resolution=100.0)
|
|
527
|
|
528 #function called to reduce redundancy in the code
|
|
529 def convert_to_pdf(file_svg :utils.FilePath, file_png :utils.FilePath, file_pdf :utils.FilePath) -> None:
|
|
530 """
|
|
531 Converts the SVG map at the provided path to PDF.
|
|
532
|
|
533 Args:
|
|
534 file_svg : path to SVG file
|
|
535 file_png : path to PNG file
|
|
536 file_pdf : path to new PDF file
|
|
537
|
|
538 Returns:
|
|
539 None
|
|
540 """
|
|
541 svg_to_png_with_background(file_svg, file_png)
|
|
542 try:
|
|
543 convert_png_to_pdf(file_png, file_pdf)
|
|
544 print(f'PDF file {file_pdf.filePath} successfully generated.')
|
|
545
|
|
546 except Exception as e:
|
|
547 raise utils.DataErr(file_pdf.show(), f'Error generating PDF file: {e}')
|
|
548
|
|
549 ############################ map ##############################################
|
|
550 def buildOutputPath(dataset1Name :str, dataset2Name = "rest", *, details = "", ext :utils.FileFormat) -> utils.FilePath:
|
|
551 """
|
|
552 Builds a FilePath instance from the names of confronted datasets ready to point to a location in the
|
|
553 "result/" folder, used by this tool for output files in collections.
|
|
554
|
|
555 Args:
|
|
556 dataset1Name : _description_
|
|
557 dataset2Name : _description_. Defaults to "rest".
|
|
558 details : _description_
|
|
559 ext : _description_
|
|
560
|
|
561 Returns:
|
|
562 utils.FilePath : _description_
|
|
563 """
|
|
564 # This function returns a util data structure but is extremely specific to this module.
|
|
565 # RAS also uses collections as output and as such might benefit from a method like this, but I'd wait
|
|
566 # TODO: until a third tool with multiple outputs appears before porting this to utils.
|
|
567 return utils.FilePath(
|
|
568 f"{dataset1Name}_vs_{dataset2Name}" + (f" ({details})" if details else ""),
|
|
569 # ^^^ yes this string is built every time even if the form is the same for the same 2 datasets in
|
|
570 # all output files: I don't care, this was never the performance bottleneck of the tool and
|
|
571 # there is no other net gain in saving and re-using the built string.
|
|
572 ext,
|
147
|
573 prefix = ARGS.output_path)
|
4
|
574
|
|
575 FIELD_NOT_AVAILABLE = '/'
|
|
576 def writeToCsv(rows: List[list], fieldNames :List[str], outPath :utils.FilePath) -> None:
|
|
577 fieldsAmt = len(fieldNames)
|
|
578 with open(outPath.show(), "w", newline = "") as fd:
|
|
579 writer = csv.DictWriter(fd, fieldnames = fieldNames, delimiter = '\t')
|
|
580 writer.writeheader()
|
|
581
|
|
582 for row in rows:
|
|
583 sizeMismatch = fieldsAmt - len(row)
|
|
584 if sizeMismatch > 0: row.extend([FIELD_NOT_AVAILABLE] * sizeMismatch)
|
|
585 writer.writerow({ field : data for field, data in zip(fieldNames, row) })
|
|
586
|
|
587 OldEnrichedScores = Dict[str, List[Union[float, FoldChange]]] #TODO: try to use Tuple whenever possible
|
|
588 def writeTabularResult(enrichedScores : OldEnrichedScores, outPath :utils.FilePath) -> None:
|
199
|
589 fieldNames = ["ids", "P_Value", "fold change", "z-score"]
|
4
|
590 fieldNames.extend(["average_1", "average_2"])
|
|
591
|
|
592 writeToCsv([ [reactId] + values for reactId, values in enrichedScores.items() ], fieldNames, outPath)
|
|
593
|
|
594 def temp_thingsInCommon(tmp :Dict[str, List[Union[float, FoldChange]]], core_map :ET.ElementTree, max_z_score :float, dataset1Name :str, dataset2Name = "rest") -> None:
|
|
595 # this function compiles the things always in common between comparison modes after enrichment.
|
|
596 # TODO: organize, name better.
|
|
597 writeTabularResult(tmp, buildOutputPath(dataset1Name, dataset2Name, details = "Tabular Result", ext = utils.FileFormat.TSV))
|
|
598 for reactId, enrichData in tmp.items(): tmp[reactId] = tuple(enrichData)
|
|
599 applyFluxesEnrichmentToMap(tmp, core_map, max_z_score)
|
|
600
|
|
601 def computePValue(dataset1Data: List[float], dataset2Data: List[float]) -> Tuple[float, float]:
|
|
602 """
|
|
603 Computes the statistical significance score (P-value) of the comparison between coherent data
|
|
604 from two datasets. The data is supposed to, in both datasets:
|
|
605 - be related to the same reaction ID;
|
|
606 - be ordered by sample, such that the item at position i in both lists is related to the
|
|
607 same sample or cell line.
|
|
608
|
|
609 Args:
|
|
610 dataset1Data : data from the 1st dataset.
|
|
611 dataset2Data : data from the 2nd dataset.
|
|
612
|
|
613 Returns:
|
|
614 tuple: (P-value, Z-score)
|
293
|
615 - P-value from the selected test on the provided data.
|
4
|
616 - Z-score of the difference between means of the two datasets.
|
|
617 """
|
293
|
618
|
|
619 match ARGS.test:
|
|
620 case "ks":
|
|
621 # Perform Kolmogorov-Smirnov test
|
|
622 _, p_value = st.ks_2samp(dataset1Data, dataset2Data)
|
|
623 case "ttest_p":
|
|
624 # Perform t-test for paired samples
|
|
625 _, p_value = st.ttest_rel(dataset1Data, dataset2Data)
|
|
626 case "ttest_ind":
|
|
627 # Perform t-test for independent samples
|
|
628 _, p_value = st.ttest_ind(dataset1Data, dataset2Data)
|
|
629 case "wilcoxon":
|
|
630 # Perform Wilcoxon signed-rank test
|
|
631 _, p_value = st.wilcoxon(dataset1Data, dataset2Data)
|
|
632 case "mw":
|
|
633 # Perform Mann-Whitney U test
|
|
634 _, p_value = st.mannwhitneyu(dataset1Data, dataset2Data)
|
4
|
635
|
|
636 # Calculate means and standard deviations
|
242
|
637 mean1 = np.nanmean(dataset1Data)
|
|
638 mean2 = np.nanmean(dataset2Data)
|
244
|
639 std1 = np.nanstd(dataset1Data, ddof=1)
|
|
640 std2 = np.nanstd(dataset2Data, ddof=1)
|
4
|
641
|
|
642 n1 = len(dataset1Data)
|
|
643 n2 = len(dataset2Data)
|
|
644
|
|
645 # Calculate Z-score
|
|
646 z_score = (mean1 - mean2) / np.sqrt((std1**2 / n1) + (std2**2 / n2))
|
|
647
|
|
648 return p_value, z_score
|
|
649
|
|
650 def compareDatasetPair(dataset1Data :List[List[float]], dataset2Data :List[List[float]], ids :List[str]) -> Tuple[Dict[str, List[Union[float, FoldChange]]], float]:
|
|
651 #TODO: the following code still suffers from "dumbvarnames-osis"
|
|
652 tmp :Dict[str, List[Union[float, FoldChange]]] = {}
|
|
653 count = 0
|
|
654 max_z_score = 0
|
|
655 for l1, l2 in zip(dataset1Data, dataset2Data):
|
|
656 reactId = ids[count]
|
|
657 count += 1
|
|
658 if not reactId: continue # we skip ids that have already been processed
|
|
659
|
|
660 try:
|
|
661 p_value, z_score = computePValue(l1, l2)
|
|
662 avg1 = sum(l1) / len(l1)
|
|
663 avg2 = sum(l2) / len(l2)
|
197
|
664 f_c = fold_change(avg1, avg2)
|
293
|
665 if np.isfinite(z_score) and max_z_score < abs(z_score): max_z_score = abs(z_score)
|
211
|
666
|
197
|
667 tmp[reactId] = [float(p_value), f_c, z_score, avg1, avg2]
|
4
|
668 except (TypeError, ZeroDivisionError): continue
|
|
669
|
|
670 return tmp, max_z_score
|
|
671
|
151
|
672 def computeEnrichment(class_pat :Dict[str, List[List[float]]], ids :List[str]) -> List[Tuple[str, str, dict, float]]:
|
4
|
673 """
|
|
674 Compares clustered data based on a given comparison mode and applies enrichment-based styling on the
|
|
675 provided metabolic map.
|
|
676
|
|
677 Args:
|
|
678 class_pat : the clustered data.
|
|
679 ids : ids for data association.
|
|
680
|
|
681
|
|
682 Returns:
|
148
|
683 List[Tuple[str, str, dict, float]]: List of tuples with pairs of dataset names, comparison dictionary, and max z-score.
|
4
|
684
|
|
685 Raises:
|
|
686 sys.exit : if there are less than 2 classes for comparison
|
151
|
687
|
4
|
688 """
|
|
689 class_pat = { k.strip() : v for k, v in class_pat.items() }
|
|
690 #TODO: simplfy this stuff vvv and stop using sys.exit (raise the correct utils error)
|
|
691 if (not class_pat) or (len(class_pat.keys()) < 2): sys.exit('Execution aborted: classes provided for comparisons are less than two\n')
|
|
692
|
148
|
693 enrichment_results = []
|
|
694
|
|
695
|
4
|
696 if ARGS.comparison == "manyvsmany":
|
|
697 for i, j in it.combinations(class_pat.keys(), 2):
|
|
698 comparisonDict, max_z_score = compareDatasetPair(class_pat.get(i), class_pat.get(j), ids)
|
148
|
699 enrichment_results.append((i, j, comparisonDict, max_z_score))
|
4
|
700
|
|
701 elif ARGS.comparison == "onevsrest":
|
|
702 for single_cluster in class_pat.keys():
|
148
|
703 rest = [item for k, v in class_pat.items() if k != single_cluster for item in v]
|
211
|
704
|
4
|
705 comparisonDict, max_z_score = compareDatasetPair(class_pat.get(single_cluster), rest, ids)
|
148
|
706 enrichment_results.append((single_cluster, "rest", comparisonDict, max_z_score))
|
4
|
707
|
|
708 elif ARGS.comparison == "onevsmany":
|
|
709 controlItems = class_pat.get(ARGS.control)
|
|
710 for otherDataset in class_pat.keys():
|
148
|
711 if otherDataset == ARGS.control:
|
|
712 continue
|
4
|
713 comparisonDict, max_z_score = compareDatasetPair(controlItems, class_pat.get(otherDataset), ids)
|
148
|
714 enrichment_results.append((ARGS.control, otherDataset, comparisonDict, max_z_score))
|
|
715 return enrichment_results
|
4
|
716
|
|
717 def createOutputMaps(dataset1Name :str, dataset2Name :str, core_map :ET.ElementTree) -> None:
|
148
|
718 svgFilePath = buildOutputPath(dataset1Name, dataset2Name, details="SVG Map", ext=utils.FileFormat.SVG)
|
4
|
719 utils.writeSvg(svgFilePath, core_map)
|
|
720
|
|
721 if ARGS.generate_pdf:
|
148
|
722 pngPath = buildOutputPath(dataset1Name, dataset2Name, details="PNG Map", ext=utils.FileFormat.PNG)
|
|
723 pdfPath = buildOutputPath(dataset1Name, dataset2Name, details="PDF Map", ext=utils.FileFormat.PDF)
|
|
724 convert_to_pdf(svgFilePath, pngPath, pdfPath)
|
4
|
725
|
148
|
726 if not ARGS.generate_svg:
|
|
727 os.remove(svgFilePath.show())
|
4
|
728
|
|
729 ClassPat = Dict[str, List[List[float]]]
|
|
730 def getClassesAndIdsFromDatasets(datasetsPaths :List[str], datasetPath :str, classPath :str, names :List[str]) -> Tuple[List[str], ClassPat]:
|
|
731 # TODO: I suggest creating dicts with ids as keys instead of keeping class_pat and ids separate,
|
|
732 # for the sake of everyone's sanity.
|
|
733 class_pat :ClassPat = {}
|
|
734 if ARGS.option == 'datasets':
|
|
735 num = 1 #TODO: the dataset naming function could be a generator
|
|
736 for path, name in zip(datasetsPaths, names):
|
|
737 name = name_dataset(name, num)
|
|
738 resolve_rules_float, ids = getDatasetValues(path, name)
|
|
739 if resolve_rules_float != None:
|
|
740 class_pat[name] = list(map(list, zip(*resolve_rules_float.values())))
|
|
741
|
|
742 num += 1
|
|
743
|
|
744 elif ARGS.option == "dataset_class":
|
|
745 classes = read_dataset(classPath, "class")
|
|
746 classes = classes.astype(str)
|
235
|
747 resolve_rules_float, ids = getDatasetValues(datasetPath, "Dataset Class (not actual name)")
|
293
|
748 #check if classes have match on ids
|
234
|
749 if not all(classes.iloc[:, 0].isin(ids)):
|
|
750 utils.logWarning(
|
|
751 "No match between classes and sample IDs", ARGS.out_log)
|
4
|
752 if resolve_rules_float != None: class_pat = split_class(classes, resolve_rules_float)
|
|
753
|
|
754 return ids, class_pat
|
|
755 #^^^ 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)
|
|
756
|
|
757 #TODO: create these damn args as FilePath objects
|
|
758 def getDatasetValues(datasetPath :str, datasetName :str) -> Tuple[ClassPat, List[str]]:
|
|
759 """
|
|
760 Opens the dataset at the given path and extracts the values (expected nullable numerics) and the IDs.
|
|
761
|
|
762 Args:
|
|
763 datasetPath : path to the dataset
|
|
764 datasetName (str): dataset name, used in error reporting
|
|
765
|
|
766 Returns:
|
|
767 Tuple[ClassPat, List[str]]: values and IDs extracted from the dataset
|
|
768 """
|
|
769 dataset = read_dataset(datasetPath, datasetName)
|
240
|
770
|
|
771 # Ensure the first column is treated as the reaction name
|
|
772 dataset = dataset.set_index(dataset.columns[0])
|
|
773
|
|
774 # Check if required reactions exist in the dataset
|
|
775 required_reactions = ['EX_lac__L_e', 'EX_glc__D_e', 'EX_gln__L_e', 'EX_glu__L_e']
|
|
776 missing_reactions = [reaction for reaction in required_reactions if reaction not in dataset.index]
|
|
777
|
|
778 if missing_reactions:
|
|
779 sys.exit(f'Execution aborted: Missing required reactions {missing_reactions} in {datasetName}\n')
|
|
780
|
|
781 # Calculate new rows using safe division
|
|
782 lact_glc = np.divide(
|
241
|
783 np.clip(dataset.loc['EX_lac__L_e'].to_numpy(), a_min=0, a_max=None),
|
|
784 np.clip(dataset.loc['EX_glc__D_e'].to_numpy(), a_min=None, a_max=0),
|
|
785 out=np.full_like(dataset.loc['EX_lac__L_e'].to_numpy(), np.nan), # Prepara un array con NaN come output di default
|
|
786 where=dataset.loc['EX_glc__D_e'].to_numpy() != 0 # Condizione per evitare la divisione per zero
|
240
|
787 )
|
|
788 lact_gln = np.divide(
|
241
|
789 np.clip(dataset.loc['EX_lac__L_e'].to_numpy(), a_min=0, a_max=None),
|
|
790 np.clip(dataset.loc['EX_gln__L_e'].to_numpy(), a_min=None, a_max=0),
|
|
791 out=np.full_like(dataset.loc['EX_lac__L_e'].to_numpy(), np.nan),
|
|
792 where=dataset.loc['EX_gln__L_e'].to_numpy() != 0
|
|
793 )
|
|
794 lact_o2 = np.divide(
|
|
795 np.clip(dataset.loc['EX_lac__L_e'].to_numpy(), a_min=0, a_max=None),
|
|
796 np.clip(dataset.loc['EX_o2_e'].to_numpy(), a_min=None, a_max=0),
|
|
797 out=np.full_like(dataset.loc['EX_lac__L_e'].to_numpy(), np.nan),
|
|
798 where=dataset.loc['EX_o2_e'].to_numpy() != 0
|
240
|
799 )
|
|
800 glu_gln = np.divide(
|
241
|
801 dataset.loc['EX_glu__L_e'].to_numpy(),
|
|
802 np.clip(dataset.loc['EX_gln__L_e'].to_numpy(), a_min=None, a_max=0),
|
|
803 out=np.full_like(dataset.loc['EX_lac__L_e'].to_numpy(), np.nan),
|
|
804 where=dataset.loc['EX_gln__L_e'].to_numpy() != 0
|
240
|
805 )
|
|
806
|
253
|
807
|
246
|
808 values = {'lact_glc': lact_glc, 'lact_gln': lact_gln, 'lact_o2': lact_o2, 'glu_gln': glu_gln}
|
|
809
|
|
810 # Sostituzione di inf e NaN con 0 se necessario
|
253
|
811 for key in values:
|
|
812 values[key] = np.nan_to_num(values[key], nan=0.0, posinf=0.0, neginf=0.0)
|
245
|
813
|
246
|
814 # Creazione delle nuove righe da aggiungere al dataset
|
240
|
815 new_rows = pd.DataFrame({
|
246
|
816 dataset.index.name: ['LactGlc', 'LactGln', 'LactO2', 'GluGln'],
|
|
817 **{col: [values['lact_glc'][i], values['lact_gln'][i], values['lact_o2'][i], values['glu_gln'][i]]
|
|
818 for i, col in enumerate(dataset.columns)}
|
240
|
819 })
|
|
820
|
293
|
821 #print(new_rows)
|
254
|
822
|
246
|
823 # Ritorna il dataset originale con le nuove righe
|
240
|
824 dataset.reset_index(inplace=True)
|
|
825 dataset = pd.concat([dataset, new_rows], ignore_index=True)
|
|
826
|
4
|
827 IDs = pd.Series.tolist(dataset.iloc[:, 0].astype(str))
|
|
828
|
|
829 dataset = dataset.drop(dataset.columns[0], axis = "columns").to_dict("list")
|
|
830 return { id : list(map(utils.Float("Dataset values, not an argument"), values)) for id, values in dataset.items() }, IDs
|
|
831
|
|
832 def rgb_to_hex(rgb):
|
|
833 """
|
|
834 Convert RGB values (0-1 range) to hexadecimal color format.
|
|
835
|
|
836 Args:
|
|
837 rgb (numpy.ndarray): An array of RGB color components (in the range [0, 1]).
|
|
838
|
|
839 Returns:
|
|
840 str: The color in hexadecimal format (e.g., '#ff0000' for red).
|
|
841 """
|
|
842 # Convert RGB values (0-1 range) to hexadecimal format
|
|
843 rgb = (np.array(rgb) * 255).astype(int)
|
|
844 return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2])
|
|
845
|
|
846 def save_colormap_image(min_value: float, max_value: float, path: utils.FilePath, colorMap:str="viridis"):
|
|
847 """
|
|
848 Create and save an image of the colormap showing the gradient and its range.
|
|
849
|
|
850 Args:
|
|
851 min_value (float): The minimum value of the colormap range.
|
|
852 max_value (float): The maximum value of the colormap range.
|
|
853 filename (str): The filename for saving the image.
|
|
854 """
|
|
855
|
|
856 # Create a colormap using matplotlib
|
|
857 cmap = plt.get_cmap(colorMap)
|
|
858
|
|
859 # Create a figure and axis
|
|
860 fig, ax = plt.subplots(figsize=(6, 1))
|
|
861 fig.subplots_adjust(bottom=0.5)
|
|
862
|
|
863 # Create a gradient image
|
|
864 gradient = np.linspace(0, 1, 256)
|
|
865 gradient = np.vstack((gradient, gradient))
|
|
866
|
|
867 # Add min and max value annotations
|
|
868 ax.text(0, 0.5, f'{np.round(min_value, 3)}', va='center', ha='right', transform=ax.transAxes, fontsize=12, color='black')
|
|
869 ax.text(1, 0.5, f'{np.round(max_value, 3)}', va='center', ha='left', transform=ax.transAxes, fontsize=12, color='black')
|
|
870
|
|
871
|
|
872 # Display the gradient image
|
|
873 ax.imshow(gradient, aspect='auto', cmap=cmap)
|
|
874 ax.set_axis_off()
|
|
875
|
|
876 # Save the image
|
|
877 plt.savefig(path.show(), bbox_inches='tight', pad_inches=0)
|
|
878 plt.close()
|
|
879 pass
|
|
880
|
|
881 def min_nonzero_abs(arr):
|
|
882 # Flatten the array and filter out zeros, then find the minimum of the remaining values
|
|
883 non_zero_elements = np.abs(arr)[np.abs(arr) > 0]
|
|
884 return np.min(non_zero_elements) if non_zero_elements.size > 0 else None
|
|
885
|
|
886 def computeEnrichmentMeanMedian(metabMap: ET.ElementTree, class_pat: Dict[str, List[List[float]]], ids: List[str], colormap:str) -> None:
|
|
887 """
|
|
888 Compute and visualize the metabolic map based on mean and median of the input fluxes.
|
168
|
889 The fluxes are normalised across classes/datasets and visualised using the given colormap.
|
4
|
890
|
|
891 Args:
|
|
892 metabMap (ET.ElementTree): An XML tree representing the metabolic map.
|
|
893 class_pat (Dict[str, List[List[float]]]): A dictionary where keys are class names and values are lists of enrichment values.
|
|
894 ids (List[str]): A list of reaction IDs to be used for coloring arrows.
|
|
895
|
|
896 Returns:
|
|
897 None
|
|
898 """
|
|
899 # Create copies only if they are needed
|
|
900 metabMap_mean = copy.deepcopy(metabMap)
|
|
901 metabMap_median = copy.deepcopy(metabMap)
|
|
902
|
|
903 # Compute medians and means
|
242
|
904 medians = {key: np.round(np.nanmedian(np.array(value), axis=1), 6) for key, value in class_pat.items()}
|
|
905 means = {key: np.round(np.nanmean(np.array(value), axis=1),6) for key, value in class_pat.items()}
|
4
|
906
|
|
907 # Normalize medians and means
|
|
908 max_flux_medians = max(np.max(np.abs(arr)) for arr in medians.values())
|
|
909 max_flux_means = max(np.max(np.abs(arr)) for arr in means.values())
|
|
910
|
168
|
911 min_flux_medians = min(min_nonzero_abs(arr) for arr in medians.values())
|
|
912 min_flux_means = min(min_nonzero_abs(arr) for arr in means.values())
|
4
|
913
|
168
|
914 medians = {key: median/max_flux_medians for key, median in medians.items()}
|
|
915 means = {key: mean/max_flux_means for key, mean in means.items()}
|
4
|
916
|
147
|
917 save_colormap_image(min_flux_medians, max_flux_medians, utils.FilePath("Color map median", ext=utils.FileFormat.PNG, prefix=ARGS.output_path), colormap)
|
|
918 save_colormap_image(min_flux_means, max_flux_means, utils.FilePath("Color map mean", ext=utils.FileFormat.PNG, prefix=ARGS.output_path), colormap)
|
4
|
919
|
|
920 cmap = plt.get_cmap(colormap)
|
|
921
|
240
|
922 min_width = 2.0 # Minimum arrow width
|
|
923 max_width = 15.0 # Maximum arrow width
|
|
924
|
4
|
925 for key in class_pat:
|
|
926 # Create color mappings for median and mean
|
|
927 colors_median = {
|
168
|
928 rxn_id: rgb_to_hex(cmap(abs(medians[key][i]))) if medians[key][i] != 0 else '#bebebe' #grey blocked
|
4
|
929 for i, rxn_id in enumerate(ids)
|
|
930 }
|
|
931
|
|
932 colors_mean = {
|
168
|
933 rxn_id: rgb_to_hex(cmap(abs(means[key][i]))) if means[key][i] != 0 else '#bebebe' #grey blocked
|
4
|
934 for i, rxn_id in enumerate(ids)
|
|
935 }
|
|
936
|
|
937 for i, rxn_id in enumerate(ids):
|
240
|
938 # Calculate arrow width for median
|
|
939 width_median = np.interp(abs(medians[key][i]), [0, 1], [min_width, max_width])
|
4
|
940 isNegative = medians[key][i] < 0
|
240
|
941 apply_arrow(metabMap_median, rxn_id, colors_median[rxn_id], isNegative, width_median)
|
4
|
942
|
240
|
943 # Calculate arrow width for mean
|
|
944 width_mean = np.interp(abs(means[key][i]), [0, 1], [min_width, max_width])
|
4
|
945 isNegative = means[key][i] < 0
|
240
|
946 apply_arrow(metabMap_mean, rxn_id, colors_mean[rxn_id], isNegative, width_mean)
|
4
|
947
|
|
948 # Save and convert the SVG files
|
|
949 save_and_convert(metabMap_mean, "mean", key)
|
|
950 save_and_convert(metabMap_median, "median", key)
|
|
951
|
240
|
952 def apply_arrow(metabMap, rxn_id, color, isNegative, width=5):
|
4
|
953 """
|
|
954 Apply an arrow to a specific reaction in the metabolic map with a given color.
|
|
955
|
|
956 Args:
|
|
957 metabMap (ET.ElementTree): An XML tree representing the metabolic map.
|
|
958 rxn_id (str): The ID of the reaction to which the arrow will be applied.
|
|
959 color (str): The color of the arrow in hexadecimal format.
|
240
|
960 isNegative (bool): A boolean indicating if the arrow represents a negative value.
|
|
961 width (int): The width of the arrow.
|
4
|
962
|
|
963 Returns:
|
|
964 None
|
|
965 """
|
240
|
966 arrow = Arrow(width=width, col=color)
|
4
|
967 arrow.styleReactionElementsMeanMedian(metabMap, rxn_id, isNegative)
|
|
968 pass
|
|
969
|
|
970 def save_and_convert(metabMap, map_type, key):
|
|
971 """
|
|
972 Save the metabolic map as an SVG file and optionally convert it to PNG and PDF formats.
|
|
973
|
|
974 Args:
|
|
975 metabMap (ET.ElementTree): An XML tree representing the metabolic map.
|
|
976 map_type (str): The type of map ('mean' or 'median').
|
|
977 key (str): The key identifying the specific map.
|
|
978
|
|
979 Returns:
|
|
980 None
|
|
981 """
|
147
|
982 svgFilePath = utils.FilePath(f"SVG Map {map_type} - {key}", ext=utils.FileFormat.SVG, prefix=ARGS.output_path)
|
4
|
983 utils.writeSvg(svgFilePath, metabMap)
|
|
984 if ARGS.generate_pdf:
|
147
|
985 pngPath = utils.FilePath(f"PNG Map {map_type} - {key}", ext=utils.FileFormat.PNG, prefix=ARGS.output_path)
|
|
986 pdfPath = utils.FilePath(f"PDF Map {map_type} - {key}", ext=utils.FileFormat.PDF, prefix=ARGS.output_path)
|
4
|
987 convert_to_pdf(svgFilePath, pngPath, pdfPath)
|
|
988 if not ARGS.generate_svg:
|
|
989 os.remove(svgFilePath.show())
|
|
990
|
|
991 ############################ MAIN #############################################
|
147
|
992 def main(args:List[str] = None) -> None:
|
4
|
993 """
|
|
994 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
995
|
|
996 Returns:
|
|
997 None
|
|
998
|
|
999 Raises:
|
|
1000 sys.exit : if a user-provided custom map is in the wrong format (ET.XMLSyntaxError, ET.XMLSchemaParseError)
|
|
1001 """
|
|
1002
|
|
1003 global ARGS
|
147
|
1004 ARGS = process_args(args)
|
4
|
1005
|
240
|
1006 if ARGS.custom_map == 'None':
|
|
1007 ARGS.custom_map = None
|
|
1008
|
147
|
1009 if os.path.isdir(ARGS.output_path) == False: os.makedirs(ARGS.output_path)
|
4
|
1010
|
|
1011 core_map :ET.ElementTree = ARGS.choice_map.getMap(
|
|
1012 ARGS.tool_dir,
|
|
1013 utils.FilePath.fromStrPath(ARGS.custom_map) if ARGS.custom_map else None)
|
|
1014 # TODO: ^^^ ugly but fine for now, the argument is None if the model isn't custom because no file was given.
|
|
1015 # getMap will None-check the customPath and panic when the model IS custom but there's no file (good). A cleaner
|
|
1016 # solution can be derived from my comment in FilePath.fromStrPath
|
|
1017
|
|
1018 ids, class_pat = getClassesAndIdsFromDatasets(ARGS.input_datas_fluxes, ARGS.input_data_fluxes, ARGS.input_class_fluxes, ARGS.names_fluxes)
|
|
1019
|
|
1020 if(ARGS.choice_map == utils.Model.HMRcore):
|
|
1021 temp_map = utils.Model.HMRcore_no_legend
|
|
1022 computeEnrichmentMeanMedian(temp_map.getMap(ARGS.tool_dir), class_pat, ids, ARGS.color_map)
|
|
1023 elif(ARGS.choice_map == utils.Model.ENGRO2):
|
|
1024 temp_map = utils.Model.ENGRO2_no_legend
|
|
1025 computeEnrichmentMeanMedian(temp_map.getMap(ARGS.tool_dir), class_pat, ids, ARGS.color_map)
|
|
1026 else:
|
|
1027 computeEnrichmentMeanMedian(core_map, class_pat, ids, ARGS.color_map)
|
148
|
1028
|
4
|
1029
|
151
|
1030 enrichment_results = computeEnrichment(class_pat, ids)
|
148
|
1031 for i, j, comparisonDict, max_z_score in enrichment_results:
|
|
1032 map_copy = copy.deepcopy(core_map)
|
|
1033 temp_thingsInCommon(comparisonDict, map_copy, max_z_score, i, j)
|
|
1034 createOutputMaps(i, j, map_copy)
|
4
|
1035
|
|
1036 if not ERRORS: return
|
|
1037 utils.logWarning(
|
|
1038 f"The following reaction IDs were mentioned in the dataset but weren't found in the map: {ERRORS}",
|
|
1039 ARGS.out_log)
|
|
1040
|
|
1041 print('Execution succeded')
|
|
1042
|
|
1043 ###############################################################################
|
|
1044 if __name__ == "__main__":
|
148
|
1045 main()
|
|
1046
|