-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyMultiThreading.py
More file actions
2807 lines (2310 loc) · 117 KB
/
Copy pathMyMultiThreading.py
File metadata and controls
2807 lines (2310 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import config module for environmental variability
from operator import index
import config
#import my utility class and function
import MyUtility
# Import dictionary from file COG_name.py
from COG_name import get_dictionary
# Get dictionary
COG_dict = get_dictionary()
#import threading
from threading import Thread
#pandas import
import pandas as pd
#numpy import
import numpy as np
#tkinter import
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from tkinter.filedialog import askopenfile
from tkinter.messagebox import showinfo
from tkinter.ttk import Separator, Style
from collections import defaultdict
# Standard library packages
import io
import os
import sys
import openpyxl
import csv
import time
import re
# Import Biopython modules to interact with KEGG
#from Bio import SeqIO
#from Bio.KEGG import REST
#from Bio.KEGG.KGML import KGML_parser
#from Bio.Graphics.KGML_vis import KGMLCanvas
#Import module to request
from urllib.request import urlopen
import ssl
#utility for load image
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def resource_path_2(relative_path):
base_path = getattr(
sys,
'_MEIPASS',
os.path.dirname(os.path.abspath(__file__)) )
return os.path.join(base_path, relative_path)
#Request for KEGG data
def _q(op, arg1, arg2=None, arg3=None):
URL = "https://rest.kegg.jp/%s"
if arg2 and arg3:
args = f"{op}/{arg1}/{arg2}/{arg3}"
elif arg2:
args = f"{op}/{arg1}/{arg2}"
else:
args = f"{op}/{arg1}"
#original request
#resp = urlopen(URL % (args))
#edit request to avoid certificate request
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
resp=urlopen(URL % (args), context=ctx)
if "image" == arg2:
return resp
handle = io.TextIOWrapper(resp, encoding="UTF-8")
handle.url = resp.url
return handle
#query for KEGG list
def kegg_list(database, org=None):
"""KEGG list - Entry list for database, or specified database entries.
db - database or organism (string)
org - optional organism (string), see below.
For the pathway and module databases the optional organism can be
used to restrict the results.
"""
# TODO - split into two functions (dbentries seems separate)?
#
# https://rest.kegg.jp/list/<database>/<org>
#
# <database> = pathway | module
# <org> = KEGG organism code
if database in ("pathway", "module") and org:
resp = _q("list", database, org)
elif isinstance(database, str) and database and org:
raise ValueError("Invalid database arg for kegg list request.")
# https://rest.kegg.jp/list/<database>
#
# <database> = pathway | brite | module | disease | drug | environ |
# ko | genome | <org> | compound | glycan | reaction |
# rpair | rclass | enzyme | organism
# <org> = KEGG organism code or T number
#
#
# https://rest.kegg.jp/list/<dbentries>
#
# <dbentries> = KEGG database entries involving the following <database>
# <database> = pathway | brite | module | disease | drug | environ |
# ko | genome | <org> | compound | glycan | reaction |
# rpair | rclass | enzyme
# <org> = KEGG organism code or T number
else:
if isinstance(database, list):
if len(database) > 100:
raise ValueError(
"Maximum number of databases is 100 for kegg list query"
)
database = ("+").join(database)
resp = _q("list", database)
return resp
#Some code to return a Pandas dataframe, given tabular text
def to_df(result):
#
return pd.read_table(io.StringIO(result), header=None)
#Manage KEGG data
def manage_kegg_query(self):
if( hasattr(self, 'query_ko') ): #category_to_search['KEGG_ko']):
#preapre df
self.df_ko = pd.DataFrame()
#get online information from kegg.com and convert into dataframe
self.df_ko = to_df(self.query_ko)
#take information about ko codes from originale df
need_df = (self.df.assign(KEGG_ko=self.df['KEGG_ko'].str.split('[,;]')).explode('KEGG_ko'))
tmp_list = need_df['KEGG_ko'].dropna().unique().tolist()
#delete everything is not on the list
self.df_ko = self.df_ko[self.df_ko[0].isin(tmp_list)]
#edit ko name to remove unuseless information
# Rimuovi il carattere ";" e tutto quello che lo precede
self.df_ko[1] = self.df_ko[1].str.replace('.*; ', '', regex=True)
# Rimuovi il testo "[EC" e quello che lo segue
self.df_ko[1] = self.df_ko[1].str.replace(' \[EC.*\]', '', regex=True)
if( hasattr(self, 'query_pathway') ): #category_to_search['KEGG_Pathway']):
#preapre df
self.df_pathway = pd.DataFrame()
#get online information from kegg.com and convert into dataframe
self.df_pathway = to_df(self.query_pathway)
#take information about pathway codes from originale df
need_df = (self.df.assign(KEGG_Pathway=self.df['KEGG_Pathway'].str.split('[,;]')).explode('KEGG_Pathway'))
tmp_list = need_df['KEGG_Pathway'].dropna().unique().tolist()
#delete everything is not on the list
self.df_pathway = self.df_pathway[self.df_pathway[0].isin(tmp_list)]
if( hasattr(self, 'query_module') ): #category_to_search['KEGG_Module']):
#preapre df
self.df_module = pd.DataFrame()
#get online information from kegg.com and convert into dataframe
self.df_module = to_df(self.query_module)
#take information about module codes from originale df
need_df = (self.df.assign(KEGG_Module=self.df['KEGG_Module'].str.split('[,;]')).explode('KEGG_Module'))
tmp_list = need_df['KEGG_Module'].dropna().unique().tolist()
#delete everything is not on the list
self.df_module = self.df_module[self.df_module[0].isin(tmp_list)]
if( hasattr(self, 'query_reaction') ): #category_to_search['KEGG_Reaction']):
#preapre df
self.df_reaction = pd.DataFrame()
#get online information from kegg.com and convert into dataframe
self.df_reaction = to_df(self.query_reaction)
#take information about reactions codes from originale df
need_df = (self.df.assign(KEGG_Reaction=self.df['KEGG_Reaction'].str.split('[,;]')).explode('KEGG_Reaction'))
tmp_list = need_df['KEGG_Reaction'].dropna().unique().tolist()
#delete everything is not on the list
self.df_reaction = self.df_reaction[self.df_reaction[0].isin(tmp_list)]
#class to upload file
class AsyncUpload(Thread):
def __init__(self, filepath, index=""):
super().__init__()
self.filepath = filepath
self.index = index
def run(self):
#variable to check if file will be open
self.fileOpen = True
#open file with pandas
try:
#save file with pandas
file_extension = self.filepath.split(".")[-1]
if file_extension == "xlsx":
if(self.index==""):
self.df = pd.read_excel(self.filepath)
else:
self.df = pd.read_excel(self.filepath, index_col=self.index)
else:
if(self.index==""):
self.df = pd.read_csv(self.filepath, sep='\t', low_memory=False)
else:
self.df = pd.read_csv(self.filepath, index_col=self.index, sep='\t', low_memory=False)
except Exception as e:
#print("===>>" + str(e))
self.fileOpen = False
#class to upload file mzTab
class AsyncUpload_mzTab(Thread):
def __init__(self, filepath, headerName, row_name):
super().__init__()
self.filepath = filepath
self.headerName = headerName
self.row_name = row_name
def run(self):
#variable to check if file will be open
self.fileOpen = True
try:
# Apri il file .mzTab
with open(self.filepath, 'r') as f:
# Inizializza le liste per le righe headerName e row_name
ppp_rows = []
mmm_rows = []
# Scorri il file riga per riga
for line in f:
# Estra le righe che iniziano con headerName e row_name
if line.startswith(self.headerName):
ppp_rows.append(line.strip().split('\t'))
elif line.startswith(self.row_name):
mmm_rows.append(line.strip().split('\t'))
#verifico se posso creare il dataframe
if(len(ppp_rows) == 0):
self.badFile = True
else:
# Crea il dataframe con i nomi delle colonne
self.df = pd.DataFrame(mmm_rows, columns=ppp_rows[0])
except Exception as e:
#print("===>>" + str(e))
self.fileOpen = False
#class to upload file exluding some start and end line
class AsyncUpload_2(Thread):
def __init__(self, filepath):
super().__init__()
self.filepath = filepath
def run(self):
#variable to check if file will be open
self.fileOpen = True
#open file with pandas
try:
#save file with pandas
file_extension = self.filepath.split(".")[-1]
if file_extension == "xlsx":
#open file
wb = openpyxl.load_workbook(self.filepath)
ws = wb.active
#count initial and final '#'
count_start = 0
count_end = 0
#count initial '#'
for row in ws.iter_rows():
if row[0].value is not None and str(row[0].value).startswith("#"):
count_start += 1
else:
break
#count final '#'
for row in reversed(list(ws.iter_rows())):
if row[0].value is not None and str(row[0].value).startswith("#"):
count_end += 1
else:
break
#read removing first and last row that start with '#' because are not used
self.df = pd.read_excel(self.filepath, skiprows=count_start, skipfooter = count_end)
else:
# apri il file csv in lettura e crea un reader csv
with open(self.filepath, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
# inizializza la variabile per l'intestazione
header = None
found_header = False
# crea una lista contenente tutte le righe che non iniziano per '#' (tranne '#query' se è l'intestazione)
rows = []
for row in reader:
if row[0].startswith('#query') and not found_header:
header = row
found_header = True
elif not row[0].startswith('#'):
rows.append(row)
# crea un dataframe pandas dal file csv, usando l'intestazione corretta (se trovata) o la prima riga dei dati
if header is not None:
self.df = pd.DataFrame(rows, columns=header)
# Estrae il nome completo delle colonne che iniziano con '#query'
query_columns = self.df.filter(regex='#query').columns
query_columns_names = [col for col in query_columns]
#rename the column
if(len(query_columns_names) == 1):
self.df = self.df.rename(columns={query_columns_names[0]: 'query'})
else:
self.df = pd.DataFrame(rows[1:], columns=rows[0])
except Exception as e:
#print("===>>" + str(e))
self.fileOpen = False
#class to download file
class AsyncDownload(Thread):
def __init__(self, df_tmp, file_path):
super().__init__()
self.df_tmp = df_tmp
self.file_path = file_path
def run(self):
#variable to check if file will be saved
self.fileSaved = True
#open file with pandas
try:
#save file with pandas
file_extension = self.file_path.split(".")[-1]
#file_path_without_extension, file_extension = self.file.name.rsplit(".", 1)
if file_extension == "xlsx":
self.df_tmp.to_excel(self.file_path, index=False)
else:
self.df_tmp.to_csv(self.file_path, sep='\t', index=False, header=True,)
except Exception as e:
#print("===>>" + str(e))
self.fileSaved = False
#class to downalod Summary Metrics file for input
class ManageSummaryMetricsPre(Thread):
def __init__(self, window):
super().__init__()
#take window data
self.window = window
def run(self):
#take a copy of window to do controls
window = self.window
#get abundance colums name
#abundance_set = list(window.df.filter(regex=r'F\d+'))
abundance_set = [c for c in window.df.columns if c.startswith("Abundance ")]
#Remove all rows that have unassigned in all abundance
condizione_colonne = window.df[abundance_set] == 'unassigned'
# Verifica se tutte le colonne soddisfano la condizione (tutte True lungo l'asse 1)
condizione_generale = condizione_colonne.all(axis=1)
# Seleziona solo le righe che soddisfano la condizione generale
df_filtrato = window.df.loc[~condizione_generale]
# Convertire le colonne in numerico
window.df[abundance_set] = window.df[abundance_set].apply(pd.to_numeric, errors='coerce')
#Remove all rows that have NaN in all abundance
condizione_colonne = window.df[abundance_set].isna() # Utilizza .isna() o .isnull()
# Verifica se tutte le colonne soddisfano la condizione (tutte True lungo l'asse 1)
condizione_generale = condizione_colonne.all(axis=1)
# Seleziona solo le righe che soddisfano la condizione generale
df_filtrato = window.df.loc[~condizione_generale]
#create new df with the name of aboundances
new_df = pd.DataFrame(columns=["Metrics"] + abundance_set + ["Whole dataset"])
# Creare una lista vuota per contenere i DataFrame da concatenare
dfs_to_concat_count = []
dfs_to_concat_sum = []
##get correct input type
column_count_text = ""
column_total_text = ""
if(MyUtility.workDict["mode"] == "Proteins"):
if(MyUtility.workDict["quantitative"] == "Spectral Count"):
column_count_text = "Identified proteins"
column_total_text = "Total spectral counts"
else:
column_count_text = "Quantified proteins"
column_total_text = "Total abundance"
elif(MyUtility.workDict["mode"] == "Peptides"):
if(MyUtility.workDict["quantitative"] == "Spectral Count"):
column_count_text = "Identified peptides"
column_total_text = "Total spectral counts"
else:
column_count_text = "Quantified peptides"
column_total_text = "Total abundance"
else:
column_count_text = "Identified peptides"
column_total_text = "Total PSMs"
##### Quantified proteins #####
whole_count_tot = len(window.df)
### Count ###
# Calcolo il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x'
count_vals = window.df[abundance_set].gt(0).sum()
# Creo un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_count_text}
new_row.update(count_vals.to_dict())
new_row.update({'Whole dataset': whole_count_tot})
# Aggiungo la nuova riga al DataFrame 'new_df'
tmp_df = pd.DataFrame(new_row, index=[0])
#aggiungo al vettore dei risultati
dfs_to_concat_count.append(tmp_df)
### Sum ###
# Calcolo la somma di valori > 0 e diversi da NaN per ogni colonna 'val_x'
count_vals = window.df[abundance_set].sum()
# Creo un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_total_text}
new_row.update(count_vals.to_dict())
#new_row.update({'Whole dataset': whole_count_tot})
# Aggiungo la nuova riga al DataFrame 'new_df'
tmp_df = pd.DataFrame(new_row, index=[0])
#aggiungo al vettore dei risultati
dfs_to_concat_sum.append(tmp_df)
##### Marked as #####
if 'Marked as' in window.df.columns:
# Ottenere un array degli elementi unici nella colonna 'maked as'
window.df['Marked as'] = window.df['Marked as'].astype(str)
unique_markedas = sorted(window.df['Marked as'].unique())
# Iterare sugli elementi unici
for element in unique_markedas:
# Filtrare il DataFrame per includere solo le righe in cui 'Marked as' è uguale a 'element' e non ci sono spazi vuoti
filtered_df = window.df[(window.df['Marked as'] == element) & (window.df['Marked as'] != '') & (window.df['Marked as'].notna()) & (window.df['Marked as'] != 'unassigned')]
#conto il totale delle righe che contengono il valore del quale conto le metriche
whole_count = filtered_df['Marked as'].count()
### Count ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].gt(0).sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_count_text+' - ' + element}
new_row.update(count_vals.to_dict())
new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_count.append(tmp_df)
### Sum ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_total_text+' - ' + element}
new_row.update(count_vals.to_dict())
#new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_sum.append(tmp_df)
##### Database #####
if 'Database' in window.df.columns:
# Ottenere un array degli elementi unici nella colonna 'maked as'
window.df['Database'] = window.df['Database'].astype(str)
unique_database = sorted(window.df['Database'].unique())
# Iterare sugli elementi unici
for element in unique_database:
# Filtrare il DataFrame per includere solo le righe in cui 'Database' è uguale a 'element' e non ci sono spazi vuoti
filtered_df = window.df[(window.df['Database'] == element) & (window.df['Database'].notna()) & (window.df['Database'] != 'unassigned')]
#conto il totale delle righe che contengono il valore del quale conto le metriche
whole_count = filtered_df['Database'].count()
### Count ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].gt(0).sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_count_text+' - ' + element}
new_row.update(count_vals.to_dict())
new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_count.append(tmp_df)
### Sum ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_total_text+' - ' + element}
new_row.update(count_vals.to_dict())
#new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_sum.append(tmp_df)
#Creation of the taxonomic_table and addition of values saved in the session.
MyUtility.workDict['taxonomic_table'] = []
if 'taxonomic_table1' in MyUtility.workDict:
MyUtility.workDict['taxonomic_table'].extend(MyUtility.workDict['taxonomic_table1'])
if 'taxonomic_table2' in MyUtility.workDict:
MyUtility.workDict['taxonomic_table'].extend(MyUtility.workDict['taxonomic_table2'])
if 'taxonomic_table' in MyUtility.workDict:
for column in MyUtility.workDict['taxonomic_table']:
if column in window.df:
# Filtrare il DataFrame per includere solo le righe in cui nella colonna selezionata è presente un valore
filtered_df = window.df[(window.df[column] != '') & (window.df[column].notna()) & (window.df[column] != 'unassigned')]
#conto il totale delle righe che contengono il valore del quale conto le metriche
whole_count = filtered_df[column].count()
### Count ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].gt(0).sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_count_text+' - ' + column}
new_row.update(count_vals.to_dict())
new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_count.append(tmp_df)
### Sum ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_total_text+' - ' + column}
new_row.update(count_vals.to_dict())
#new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_sum.append(tmp_df)
#Creation of the functional_table and functional_to_display and addition of values saved in the session.
MyUtility.workDict['functional_table'] = []
MyUtility.workDict['functional_to_display'] = []
if 'functional_table1' in MyUtility.workDict:
MyUtility.workDict['functional_table'].extend(MyUtility.workDict['functional_table1'])
MyUtility.workDict['functional_to_display'].extend(MyUtility.workDict['functional_to_display1'])
if 'functional_table2' in MyUtility.workDict:
MyUtility.workDict['functional_table'].extend(MyUtility.workDict['functional_table2'])
MyUtility.workDict['functional_to_display'].extend(MyUtility.workDict['functional_to_display2'])
if 'functional_table' in MyUtility.workDict:
for column in MyUtility.workDict['functional_table']:
if column in window.df:
# Filtrare il DataFrame per includere solo le righe in cui nella colonna selezionata è presente un valore
filtered_df = window.df[(window.df[column] != '') & (window.df[column].notna()) & (window.df[column] != 'unassigned')]
#conto il totale delle righe che contengono il valore del quale conto le metriche
whole_count = filtered_df[column].count()
### Count ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].gt(0).sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_count_text+' - ' + column}
new_row.update(count_vals.to_dict())
new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_count.append(tmp_df)
### Sum ###
# Calcolare il numero di valori > 0 e diversi da NaN per ogni colonna 'val_x' solo nelle righe filtrate
count_vals = filtered_df[abundance_set].sum()
# Creare un dizionario con la nuova riga contenente i nomi delle colonne e i relativi conteggi
new_row = {'Metrics': column_total_text+' - ' + column}
new_row.update(count_vals.to_dict())
#new_row.update({'Whole dataset': whole_count})
# Creare un DataFrame con la riga corrente
tmp_df = pd.DataFrame(new_row, index=[0])
# Aggiungere il DataFrame corrente alla lista di DataFrame da concatenare
dfs_to_concat_sum.append(tmp_df)
##### Add all row in new_df #####
# Concatenare tutti i DataFrame nella lista in un unico DataFrame
new_df = pd.concat(dfs_to_concat_count + dfs_to_concat_sum, ignore_index=True)
#save df tmp in the window
window.df_tmp = new_df
#class to download aggregation files
class AsyncDownload_Aggregation(Thread):
def __init__(self, window, df, my_list, params, file_path):
super().__init__()
#take a copy of window to do controls
self.window = window
#save the df recived
self.df = df
#save the list recived
self.my_list = my_list
#params to work
self.params = params
#save file_path
self.file_path = file_path
#variable to know if user want replace all existing file with the same path
#2=to ask; 1=positive answer; 0=negative answer
self.replaceAll = 2;
def run(self):
### only for Summary metrics ###
# Creare una lista vuota per contenere i DataFrame da concatenare
dfs_to_concat = []
skip_columns = {"Description", "Master Protein Descriptions", "Lineage"}
#get abundance colums name
#abundance_set = list(self.df.filter(regex=r'F\d+'))
abundance_set = [c for c in self.df.columns if c.startswith("Abundance ")]
# Convertire le colonne in numerico
self.df[abundance_set] = self.df[abundance_set].apply(pd.to_numeric, errors='coerce')
#create new df with the name of aboundances
metrics_df = pd.DataFrame(columns=["Metrics"] + abundance_set + ["Whole dataset"])
#variable to check if file will be saved
self.fileSaved = True
#dictionary to kegg values
category_to_search = {'KEGG_ko':False, 'KEGG_Pathway':False, 'KEGG_Module':False, 'KEGG_Reaction':False}
#variable to check connection
self.internetWork = True
#list of COG category
try:
self.df_cog = self.df.groupby(["COG_category", "COG name"]).size().reset_index(name="count")
except:
self.df_cog = []
#only if online search is request
if(self.params["keggOnline"]):
#first of all check for what kegg value is need to search
for element in self.my_list:
#by default i put the first element
value = element[0]
#if the element is a aggregation kegg can be only in the second so i put it
if(len(element) == 2):
value = element[1]
#check if the value in the list are one of this to search
if(value == 'KEGG_ko'):
category_to_search['KEGG_ko'] = True
elif(value == 'KEGG_Pathway'):
category_to_search['KEGG_Pathway'] = True
elif(value == 'KEGG_Module'):
category_to_search['KEGG_Module'] = True
elif(value == 'KEGG_Reaction'):
category_to_search['KEGG_Reaction'] = True
#check if is possible get online value of kegg value
try:
#try all download here
if(category_to_search['KEGG_ko']):
#get online value of KEGG_ko
self.query_ko = kegg_list("orthology").read()
if(category_to_search['KEGG_Pathway']):
#get online value of KEGG_pathway
self.query_pathway = kegg_list("pathway").read()
if(category_to_search['KEGG_Module']):
#get online value of KEGG_module
self.query_module = kegg_list("module").read()
if(category_to_search['KEGG_Reaction']):
#get online value of KEGG_reaction
self.query_reaction = kegg_list("reaction").read()
except Exception as e:
#print("===>>" + str(e))
self.internetWork = False
return
#Manage the online results
manage_kegg_query(self)
#for every list element create a file
for element in self.my_list:
#get all F cols
#cols = list(self.df.filter(regex=r'F\d+'))
cols = [c for c in self.df.columns if c.startswith("Abundance ")]
#add in first place the col_name of column that i want aggragate
cols.extend(element)
#add Sequence column to avoid a problem with drop duplicate during the aggregation phase
#that could remove two row with the same values but of two different sequence
# Note that this problem is present only in peptide and PSMs, not in Protein(Obviously)
# for this reason before adding "Sequence" we need to check if it exist in df (protein not contain that)
if "Sequence" in self.df.columns:
cols.extend(["Sequence"])
#create a tmp df
df_tmp = self.df[cols]
#First replace empty strings in all columns to mising values:
df_tmp = df_tmp.replace('', np.nan)
#prepare filename to save file
final_path = ""
#create a tmp df for supplementary tables
df_tmp_sup = df_tmp.copy()
#prepare filename to save supplementary tables
final_path_sup = ""
#check if there are 1 or 2 name
if(len(element) == 1):
#take col name
col_name = element[0]
#get abundace colums
#aboundance_cols = list(df_tmp.filter(regex=r'F\d+'))
aboundance_cols = [c for c in df_tmp.columns if c.startswith("Abundance ")]
#re put nan in empty cells
df_tmp[aboundance_cols] = df_tmp[aboundance_cols].replace({0:np.nan})
#controls for supplementary tables
if(self.params["sup_tab"] or self.params["extra_counts_col"] or self.params["counts_col"]):
#re put nan in empty cells
df_tmp_sup[aboundance_cols] = df_tmp_sup[aboundance_cols].replace({0:np.nan})
#drop unuseless row
df_tmp_sup = df_tmp_sup.dropna(subset=[col_name])
#For the safe I convert this column to a string before split
df_tmp_sup = df_tmp_sup.astype({col_name: 'str'})
if(self.params["mode"] == "PSMs"):
#skips the columns that should not be split
if col_name not in skip_columns:
df_tmp_sup = (df_tmp_sup.assign(new_col=df_tmp_sup[col_name].str.split('[,;]'))
.explode('new_col')
.groupby('new_col', as_index=False)
.count())
else:
df_tmp_sup = (df_tmp_sup
.assign(new_col=df_tmp_sup[col_name])
.groupby('new_col', as_index=False)
.count())
else: #Proteins/Peptides
#skips the columns that should not be split
if col_name not in skip_columns:
df_tmp_sup = (df_tmp_sup.assign(new_col=df_tmp_sup[col_name].str.split('[,;]'))
.explode('new_col')
.drop_duplicates()
.groupby('new_col', as_index=False)
.count())
else:
df_tmp_sup = (df_tmp_sup
.assign(new_col=df_tmp_sup[col_name])
.drop_duplicates()
.groupby('new_col', as_index=False)
.count())
#edit final_path_sup
exstension = ""
col_count = ""
if(self.params["mode"] == "Proteins"):
exstension = "-protcounts"
col_count = "Total protein count"
elif( (self.params["mode"] == 'Peptides') or (self.params["mode"] == 'PSMs') ):
exstension = "-peptcounts"
col_count = "Total peptide count"
else:
exstension = "-count"
col_count = "Total count"
#raname previus column name to tot
df_tmp_sup.rename(columns = {col_name:col_count}, inplace = True)
#rename the tmp col use to explode
df_tmp_sup.rename(columns = {'new_col':col_name}, inplace = True)
#remove the new empty values
df_tmp_sup = df_tmp_sup.replace('', np.nan)
df_tmp_sup = df_tmp_sup.dropna(subset=[col_name])
#edit final_path_sup
final_path_sup = self.params["prefix"] + col_name + exstension + self.params["suffix"]
#drop unuseless row
df_tmp = df_tmp.dropna(subset=[col_name])
#For the safe I convert this column to a string before split
df_tmp = df_tmp.astype({col_name: 'str'})
#create the new file with the sum of aboundances
if(self.params["mode"] == "PSMs"):
#skips the columns that should not be split
if col_name not in skip_columns:
df_tmp = (df_tmp.assign(new_col=df_tmp[col_name].str.split('[,;]'))
.explode('new_col')
.groupby('new_col', as_index=False)
.sum(min_count=1))
else:
df_tmp = (df_tmp
.assign(new_col=df_tmp[col_name])
.groupby('new_col', as_index=False)
.sum(min_count=1))
else: #Proteins/Peptides
#skips the columns that should not be split
if col_name not in skip_columns:
df_tmp = (df_tmp.assign(new_col=df_tmp[col_name].str.split('[,;]'))
.explode('new_col')
.drop_duplicates()
.groupby('new_col', as_index=False)
.sum(min_count=1))
else:
df_tmp = (df_tmp
.assign(new_col=df_tmp[col_name])
.drop_duplicates()
.groupby('new_col', as_index=False)
.sum(min_count=1))
#rename the tmp col use to explode
df_tmp.rename(columns = {col_name:'old_col'}, inplace = True)
df_tmp.rename(columns = {'new_col':col_name}, inplace = True)
#remove the new empty values
df_tmp = df_tmp.replace('', np.nan)
df_tmp = df_tmp.dropna(subset=[col_name])
#edit final_path
final_path = self.params["prefix"] + col_name + self.params["suffix"]
## for df_tmp and df_tmp_sup ##
#add extra column with description of kegg or cog name
if( col_name == "COG_category" ):
#get position for new column
position_to_insert = df_tmp.columns.get_loc("COG_category")+1
#crearte a new empty column
df_tmp.insert(loc=position_to_insert, column="COG name", value=['' for i in range(df_tmp.shape[0])])
#it looks for all the values cog and associates them with the correct description
for i, row in self.df_cog.iterrows():
df_tmp["COG name"].where(df_tmp["COG_category"] != row[0], row[1], inplace=True)
#check for add description also in df_tmp_sup
if(self.params["sup_tab"]):
df_tmp_sup.insert(loc=position_to_insert, column="COG name", value=df_tmp["COG name"])
elif( (col_name == "KEGG_ko") and (category_to_search['KEGG_ko']) ):
#get position for new column
position_to_insert = df_tmp.columns.get_loc("KEGG_ko")+1
#crearte a new empty column
df_tmp.insert(loc=position_to_insert, column="KO name", value=['' for i in range(df_tmp.shape[0])])
#it looks for all the values of kegg and associates them with the correct description
for i, row in self.df_ko.iterrows():
df_tmp["KO name"].where(df_tmp["KEGG_ko"] != row[0], row[1], inplace=True)
#check for add description also in df_tmp_sup
if(self.params["sup_tab"]):
df_tmp_sup.insert(loc=position_to_insert, column="KO name", value=df_tmp["KO name"])
elif( (col_name == "KEGG_Pathway") and (category_to_search['KEGG_Pathway']) ):
#get position for new column
position_to_insert = df_tmp.columns.get_loc("KEGG_Pathway")+1
#crearte a new empty column
df_tmp.insert(loc=position_to_insert, column="Pathway name", value=['' for i in range(df_tmp.shape[0])])
#it looks for all the values of kegg and associates them with the correct description
for i, row in self.df_pathway.iterrows():
df_tmp["Pathway name"].where(df_tmp["KEGG_Pathway"] != row[0], row[1], inplace=True)
#check for add description also in df_tmp_sup
if(self.params["sup_tab"]):
df_tmp_sup.insert(loc=position_to_insert, column="Pathway name", value=df_tmp["Pathway name"])
elif( (col_name == "KEGG_Module") and (category_to_search['KEGG_Module']) ):
#get position for new column
position_to_insert = df_tmp.columns.get_loc("KEGG_Module")+1
#crearte a new empty column
df_tmp.insert(loc=position_to_insert, column="Module name", value=['' for i in range(df_tmp.shape[0])])
#it looks for all the values of kegg and associates them with the correct description
for i, row in self.df_module.iterrows():
df_tmp["Module name"].where(df_tmp["KEGG_Module"] != row[0], row[1], inplace=True)
#check for add description also in df_tmp_sup
if(self.params["sup_tab"]):
df_tmp_sup.insert(loc=position_to_insert, column="Module name", value=df_tmp["Module name"])
elif( (col_name == "KEGG_Reaction") and (category_to_search['KEGG_Reaction']) ):
#get position for new column
position_to_insert = df_tmp.columns.get_loc("KEGG_Reaction")+1
#crearte a new empty column
df_tmp.insert(loc=position_to_insert, column="Reaction name", value=['' for i in range(df_tmp.shape[0])])
#it looks for all the values of kegg and associates them with the correct description
for i, row in self.df_reaction.iterrows():
df_tmp["Reaction name"].where(df_tmp["KEGG_Reaction"] != row[0], row[1], inplace=True)
#check for add description also in df_tmp_sup
if(self.params["sup_tab"]):
df_tmp_sup.insert(loc=position_to_insert, column="Reaction name", value=df_tmp["Reaction name"])
#delete the old_col
df_tmp = df_tmp.drop(columns=["old_col"])
else:
#take cols name
col_name_1 = element[0]
col_name_2 = element[1]
#get abundace colums
aboundance_cols = [c for c in df_tmp.columns if c.startswith("Abundance ")]
#re put nan in empty cells
df_tmp[aboundance_cols] = df_tmp[aboundance_cols].replace({0:np.nan})
#controls for supplementary tables
if(self.params["sup_tab"] or self.params["extra_counts_col"] or self.params["counts_col"]):
#re put nan in empty cells
df_tmp_sup[aboundance_cols] = df_tmp_sup[aboundance_cols].replace({0:np.nan})
#drop unuseless row
df_tmp_sup = df_tmp_sup.dropna(subset=[col_name_1, col_name_2])
#For the safe I convert this column to a string before split
df_tmp_sup = df_tmp_sup.astype({col_name_2: 'str'})
if(self.params["mode"] == "PSMs"):
#skips the columns that should not be split
if col_name_2 not in skip_columns:
df_tmp_sup = (df_tmp_sup.assign(new_col=df_tmp_sup[col_name_2].str.split('[,;]'))
.explode('new_col')
.groupby([col_name_1, 'new_col'], as_index=False)
.count())
else:
df_tmp_sup = (df_tmp_sup
.assign(new_col=df_tmp_sup[col_name_2])
.groupby([col_name_1, 'new_col'], as_index=False)
.count())
else: #Proteins/Peptides
#skips the columns that should not be split
if col_name_2 not in skip_columns:
df_tmp_sup = (df_tmp_sup.assign(new_col=df_tmp_sup[col_name_2].str.split('[,;]'))
.explode('new_col')
.drop_duplicates()
.groupby([col_name_1, 'new_col'], as_index=False)
.count())
else:
df_tmp_sup = (df_tmp_sup
.assign(new_col=df_tmp_sup[col_name_2])
.drop_duplicates()
.groupby([col_name_1, 'new_col'], as_index=False)
.count())
#edit final_path_sup
exstension = ""
col_count = ""
if(self.params["mode"] == "Proteins"):
exstension = "-protcounts"
col_count = "Total protein count"
elif( (self.params["mode"] == 'Peptides') or (self.params["mode"] == 'PSMs') ):
exstension = "-peptcounts"