annotate COBRAxy/flux_to_map.py @ 148:5683406a8cfd draft

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