annotate marea_2/flux_to_map.py @ 247:6c3e7c338b93 draft

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