annotate cobraxy-9688ad27287b/COBRAxy/flux_to_map.py @ 92:fdf713bb5772 draft

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