annotate marea.py @ 176:13f8d4a8b015 draft

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