forked from AAnzel/MOVIS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
2009 lines (1531 loc) · 70.3 KB
/
common.py
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 os
import math
import random
import shutil
import visualize
import pandas as pd
import numpy as np
import altair as alt
import altair_saver
import datetime as dt
import streamlit as st
from tempfile import NamedTemporaryFile
from gensim.models import Word2Vec
from sklearn.cluster import KMeans, OPTICS
from sklearn import preprocessing
from sklearn import metrics
from Bio import SeqIO
from Bio.SeqUtils.ProtParam import ProteinAnalysis
from scipy.spatial.distance import jaccard, pdist, squareform
__author__ = 'Aleksandar Anžel'
__copyright__ = ''
__credits__ = ['Aleksandar Anžel', 'Georges Hattab']
__license__ = 'GNU General Public License v3.0'
__version__ = '1.0'
__maintainer__ = 'Aleksandar Anžel'
__email__ = '[email protected]'
__status__ = 'Dev'
SEED = 42
MAX_ROWS = 15000
EPOCHS = 10
NUM_OF_WORKERS = (os.cpu_count()-2) if os.cpu_count() is not None else 2
VECTOR_SIZE = 100
EX_1 = 1
EX_2 = 2
random.seed(SEED)
np.random.seed(SEED)
# Important if you want to visualize datasets with >5000 samples
alt.data_transformers.enable("default", max_rows=MAX_ROWS)
# Issue: https://github.com/altair-viz/altair/issues/2398
def fix_float64_error(df):
for column in df.select_dtypes(include=[np.float]).columns:
df[column] = df[column].astype(np.float32)
return df
def remove_everthing_from_dir(path_dir):
for file_name in os.listdir(path_dir):
if 'gitkeep' in file_name:
continue
else:
file_path = os.path.join(path_dir, file_name)
try:
if os.path.isfile(file_path) or\
os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except OSError as e:
print('Failed to delete ' + file_path + '. Reason: ' + e)
print('Successfully removed everything from ' + path_dir)
return None
# Functions below are shared among different omics.
def save_chart(chart, folder_path, key):
charts_folder_path = os.path.join(folder_path)
remove_everthing_from_dir(charts_folder_path)
results_folder_path = os.path.join(charts_folder_path, 'results_' + key)
os.mkdir(results_folder_path)
chart_file_path = os.path.join(results_folder_path, 'chart')
chart.save(chart_file_path + '.json')
for extension in ['.png', '.svg', '.pdf']:
altair_saver.save(chart, chart_file_path + extension)
zipped_file_path = os.path.join(charts_folder_path, 'chart_zipped')
shutil.make_archive(zipped_file_path, 'zip', results_folder_path)
with open(zipped_file_path + '.zip', 'rb') as zipped_file:
st.download_button(label='Download visualization', data=zipped_file,
file_name='movis_visualization.zip',
mime='application/zip')
return None
# This function creates new dataframe with column that represent season
# according to date It also concatenates important types with metabolite names
def season_data(data, temporal_column):
new_df = data
new_df["season"] = new_df[temporal_column].dt.month % 12 // 3 + 1
# important_types = [metabolite_column] + important_types
# new_df['new_name'] = df[important_types].agg('\n'.join, axis=1)
return new_df
def calculate_genomics_properties(end, path_fasta):
experimental_calculations_dict = {
'Hydrogen bond': {
'AA': -5.44,
'AC': -7.14,
'AG': -6.27,
'AT': -5.35,
'CA': -7.01,
'CC': -8.48,
'CG': -8.05,
'CT': -6.27,
'GA': -7.80,
'GC': -8.72,
'GG': -8.48,
'GT': -7.14,
'TA': -5.83,
'TC': -7.80,
'TG': -7.01,
'TT': -5.44
},
'Stacking energy': {
'AA': -26.71,
'AC': -27.73,
'AG': -26.89,
'AT': -27.20,
'CA': -27.15,
'CC': -26.28,
'CG': -27.93,
'CT': -26.89,
'GA': -26.78,
'GC': -28.13,
'GG': -26.28,
'GT': -27.73,
'TA': -26.90,
'TC': -26.78,
'TG': -27.15,
'TT': -26.71
},
'Solvation': {
'AA': -171.84,
'AC': -171.11,
'AG': -174.93,
'AT': -173.70,
'CA': -179.01,
'CC': -166.76,
'CG': -176.88,
'CT': -174.93,
'GA': -167.60,
'GC': -165.58,
'GG': -166.76,
'GT': -171.11,
'TA': -174.35,
'TC': -167.60,
'TG': -179.01,
'TT': -171.84
}
}
properties_list = ['Hydrogen bond', 'Stacking energy', 'Solvation']
fasta_files = os.listdir(path_fasta)
fasta_files.sort()
final_result_dict = {
'Hydrogen bond': [],
'Stacking energy': [],
'Solvation': []
}
for i, fasta_file_name in enumerate(fasta_files):
if i == end:
break
else:
one_fasta_result = {
'Hydrogen bond': 0,
'Stacking energy': 0,
'Solvation': 0
}
sequence_count = 0
with open(os.path.join(path_fasta, fasta_file_name), "r")\
as input_file:
for fasta_string in SeqIO.parse(input_file, "fasta"):
sequence_count += 1
one_sequence_result = {
'Hydrogen bond': 0,
'Stacking energy': 0,
'Solvation': 0
}
sequence = str(fasta_string.seq)
# Skipping any sequence that contains unknown nucleotide
if any(i in sequence for i in ["*", "-"]):
continue
n = len(sequence)
for i in range(n-1):
for phy_property in properties_list:
one_sequence_result[phy_property] +=\
experimental_calculations_dict[phy_property][
sequence[i:i+2]]
# Taking an average values
for phy_property in properties_list:
one_sequence_result[phy_property] /= (n-1)
# After taking care of one sequence, we update the
# result for the whole file
for phy_property in properties_list:
one_fasta_result[phy_property] +=\
one_sequence_result[phy_property]
# When we finish the whole FASTA file, we just average values
for phy_property in properties_list:
one_fasta_result[phy_property] /= sequence_count
# We then update the final dict with this value
for phy_property in properties_list:
final_result_dict[phy_property].append(
one_fasta_result[phy_property])
# Here we create a dataframe from that final dict
return pd.DataFrame.from_dict(final_result_dict)
def calculate_proteomics_properties(end, path_proteomics):
print("Importing proteomics data")
fasta_files = os.listdir(path_proteomics)
fasta_files.sort()
tmp_all = []
# This was done so that I could work with first 100 FASTA files only.
# Otherwise, I should just remove: i, and enumerate
for i, fasta_file_name in enumerate(fasta_files):
if i == end:
break
else:
with open(os.path.join(path_proteomics, fasta_file_name), "r")\
as input_file:
one_mag_list = []
for fasta_string in SeqIO.parse(input_file, "fasta"):
# Analyzing protein (peptide) and creating list of values
# for one MAG
sequence = str(fasta_string.seq)
if "*" in sequence:
continue
else:
sequence_analysis = ProteinAnalysis(sequence)
tmp_list = [
sequence_analysis.molecular_weight(),
sequence_analysis.gravy(),
sequence_analysis.aromaticity(),
sequence_analysis.instability_index(),
sequence_analysis.isoelectric_point(),
]
tmp_sec_str =\
sequence_analysis.secondary_structure_fraction()
tmp_list += [tmp_sec_str[0], tmp_sec_str[1],
tmp_sec_str[2]]
tmp_list.append(
sequence.count("K")
+ sequence.count("R")
- sequence.count("D")
- sequence.count("E")
) # Electricity
amino_acid_perc =\
sequence_analysis.get_amino_acids_percent()
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"AGILPV"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"STNQ"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"QNHSTYCMW"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"AGILPVF"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"HKR"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"CM"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"DE"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"NQ"]))
tmp_list.append(sum([amino_acid_perc[aa] for aa in
"ST"]))
# Now I put all these values in one_mag_list as a numpy
# arrays
one_mag_list.append(np.asarray(tmp_list))
# Now I put one mag values, aggregated by mean, into the all
# mag list
tmp_all.append(np.asarray(one_mag_list).mean(axis=0))
COLUMN_LIST = [
"Molecular weight",
"Gravy",
"Aromaticity",
"Instability index",
"Isoelectric point",
"Secondary structure fraction 0",
"Secondary structure fraction 1",
"Secondary structure fraction 2",
"Electricity",
"Fraction aliphatic",
"Fraction uncharged polar",
"Fraction polar",
"Fraction hydrophobic",
"Fraction positive",
"Fraction sulfur",
"Fraction negative",
"Fraction amide",
"Fraction alcohol",
]
all_mag_df = pd.DataFrame(tmp_all, columns=COLUMN_LIST)
print("Finished importing")
return all_mag_df
# Everything below is used for genomics data set exclusively
# Function that splits each genome into k-mers thus creating even longer
# sentence (MAG) It returns tokenized genome i.e. [kmer, kmer,...]
def split_genome(genome, k=5):
new_genome = []
n = len(genome)
if n - k <= 0:
return genome
else:
for i in range(n - k):
new_genome.append(genome[i: i + k])
return new_genome
def vectorize_one_mag(one_mag, w2v_model):
# We have to generate vectors for each word in one MAG and then create
# vector representation of that MAG by averaging vectors of its words
zero_vector = np.zeros(w2v_model.vector_size)
word_vectors = []
one_mag_vector = []
for sentence in one_mag:
for word in sentence:
if word in w2v_model.wv:
try:
word_vectors.append(w2v_model.wv[word])
except KeyError:
print("Key Error")
continue
if word_vectors:
word_vectors = np.asarray(word_vectors)
one_mag_vector = word_vectors.mean(axis=0)
else:
one_mag_vector = zero_vector
return one_mag_vector
# Function that vectorizes a MAG (document) with a pretrained word2vec model.
# It returns vector representation of a given MAG Vectorization is done by
# averaging word (k-mer) vectors for the whole document (MAG)
def vectorize_mags(w2v_model, path_fasta, end):
print("Vectorizing MAGs")
fasta_files = os.listdir(path_fasta)
fasta_files.sort()
list_of_mag_vectors = []
# This was done so that I could work with first 'end' FASTA files only.
# Otherwise, I should just remove: i, and enumerate
for i, fasta_file_name in enumerate(fasta_files):
if i == end:
break
else:
with open(os.path.join(path_fasta, fasta_file_name), "r")\
as input_file:
one_mag = []
for fasta_string in SeqIO.parse(input_file, "fasta"):
# Get kmers of a genome and create a sentence (list of
# words)
temp_kmers = split_genome(str(fasta_string.seq))
# Create a document (list of sentences)
one_mag.append(temp_kmers)
# Vectorizing MAGs one by one
list_of_mag_vectors.append(vectorize_one_mag(one_mag,
w2v_model))
print("Finished vectorizing")
return list_of_mag_vectors
# If one wants to import MAGs to train word2vec model, one should use only end
# argument, so that first 'end' MAGs are used for training
def import_mags_and_build_model(end, path_fasta):
print("Importing MAGs and building model")
# There are 1364 MAGs enclosed in FASTA files of the first dataset I have
# to traverse every FASTA file, and in each file every sequence
fasta_files = os.listdir(path_fasta)
fasta_files.sort()
# This was done so that I could work with first 100 FASTA files only.
# Otherwise, I should just remove: i, and enumerate
for i, fasta_file_name in enumerate(fasta_files):
if i == end:
break
else:
with open(os.path.join(path_fasta, fasta_file_name), "r")\
as input_file:
one_mag = []
for fasta_string in SeqIO.parse(input_file, "fasta"):
# Get kmers of a genome and create a sentence (list of
# words)
temp_kmers = split_genome(str(fasta_string.seq))
# Create a document (list of sentences)
one_mag.append(temp_kmers)
# If we do not have a model, we build one
if i == 0:
print("Building w2v model")
# We build our model on the first MAG
w2v_model = Word2Vec(
sentences=one_mag, vector_size=VECTOR_SIZE,
workers=NUM_OF_WORKERS, seed=SEED)
# Else we just expand its vocabulary
else:
# Now we expand our vocabulary
w2v_model.build_vocab(one_mag, update=True)
print("Finished building")
return w2v_model, fasta_files
def train_model(w2v_model, path_fasta, end, epochs=EPOCHS):
print("Starting model training")
# There are 1364 MAGs enclosed in FASTA files I have to traverse every
# FASTA file, and in each file every sequence
fasta_files = os.listdir(path_fasta)
fasta_files.sort()
# This was done so that I could work with first 100 FASTA files only.
# Otherwise, I should just remove: i, and enumerate
for i, fasta_file_name in enumerate(fasta_files):
if i == end:
break
else:
with open(os.path.join(path_fasta, fasta_file_name), "r")\
as input_file:
one_mag = []
for fasta_string in SeqIO.parse(input_file, "fasta"):
# Get kmers of a genome and create a sentence (list of
# words)
temp_kmers = split_genome(str(fasta_string.seq))
# Create a document (list of sentences)
one_mag.append(temp_kmers)
w2v_model.train(
one_mag, total_examples=w2v_model.corpus_count,
epochs=epochs)
print("Model training finished")
return w2v_model
def get_number_of_clusters(data):
data_columns = data.columns.to_list()
unwanted_columns = ['DateTime', 'K-Means', 'OPTICS']
for unwanted_column in unwanted_columns:
if unwanted_column in data_columns:
data = data.drop(unwanted_column, axis=1)
mag_scaler = preprocessing.StandardScaler()
scaled_data = mag_scaler.fit_transform(data)
num_of_entries = data.shape[0] # Getting number of rows
k_range_end = int(math.sqrt(num_of_entries)) # Usually it is sqrt(#)
k_range = range(1, k_range_end)
k_mean_models = [KMeans(n_clusters=i, random_state=SEED) for i in k_range]
k_scores = [
k_mean_model.fit(scaled_data).score(scaled_data)
for k_mean_model in k_mean_models
]
k_model_data = pd.DataFrame({"k_range": k_range, "k_scores": k_scores})
return k_model_data
def cluster_data(data, num_of_clusters, min_samples, model_name):
data_columns = data.columns.to_list()
unwanted_columns = ['DateTime', 'K-Means', 'OPTICS']
for unwanted_column in unwanted_columns:
if unwanted_column in data_columns:
data = data.drop(unwanted_column, axis=1)
if model_name == 'K-Means':
model = KMeans(n_clusters=num_of_clusters, random_state=SEED)
elif model_name == 'OPTICS':
model = OPTICS(min_samples=min_samples, n_jobs=NUM_OF_WORKERS)
else:
pass
predicted_values = model.fit_predict(data)
return predicted_values
def evaluate_clustering(data, predicted):
data_columns = data.columns.to_list()
unwanted_columns = ['DateTime', 'K-Means', 'OPTICS']
for unwanted_column in unwanted_columns:
if unwanted_column in data_columns:
data = data.drop(unwanted_column, axis=1)
return [metrics.silhouette_score(data, predicted),
metrics.calinski_harabasz_score(data, predicted),
metrics.davies_bouldin_score(data, predicted)]
def create_pairwise_jaccard(data):
tmp_data = data.clip(0, 1)
result = squareform(pdist(tmp_data.astype(bool), jaccard))
return pd.DataFrame(result, index=data.index, columns=data.index)
def cache_dataframe(dataframe, folder_path):
dataframe.to_pickle(folder_path)
return None
def get_cached_dataframe(folder_path):
tmp_df = pd.read_pickle(folder_path).convert_dtypes()
tmp_df = fix_float64_error(tmp_df)
return tmp_df
def fix_dataframe_columns(dataframe):
old_columns = dataframe.columns.to_list()
old_columns = [str(i) for i in old_columns]
new_columns_map = {}
bad_symbols = ['[', ']', '.', ',', '{', '}']
for column in old_columns:
if any(char in column for char in bad_symbols):
new_column = column
for i in bad_symbols:
new_column = new_column.replace(i, '_')
else:
new_column = column
new_columns_map[column] = new_column
return dataframe.rename(columns=new_columns_map)
def example_1_fix_double_header(df):
first_part = df.columns.tolist()
second_part = df.iloc[0].fillna('')
new_names = [first_part[i] + ' ' + str(second_part[i])
for i in range(len(first_part))]
new_names_dict = {}
for i in range(len(new_names)):
new_names_dict[first_part[i]] = new_names[i].strip()
return df.rename(columns=new_names_dict)
def create_temporal_column(list_of_days, start_date, end, day_or_week):
# In this case we just have to extract file names
if day_or_week == 'TIMESTAMP':
list_of_days.sort()
return [dt.datetime.strptime(i.split('.')[0], "%Y-%m-%d")
for i in list_of_days]
else:
list_of_dates = []
list_of_days.sort()
for i in list_of_days[:end]:
# Taking the number after D or W in D03.fa, without .fa so 03
try:
tmp_number = int(i.split('.')[0][1:])
except ValueError:
st.error(
'''File names are not valid. File names should start with
"D" or "W" followed with a number. Example: D04, W12...''')
st.stop()
if day_or_week == 'W':
tmp_datetime = start_date + dt.timedelta(weeks=tmp_number)
else:
tmp_datetime = start_date + dt.timedelta(days=tmp_number)
while tmp_datetime in list_of_dates:
if day_or_week == 'W':
tmp_datetime = tmp_datetime + dt.timedelta(days=1)
else:
tmp_datetime = tmp_datetime + dt.timedelta(hours=1)
list_of_dates.append(tmp_datetime)
return list_of_dates
# ---
# # GENOMIC ANALYSIS
# ---
# Important only if we have filename D01.fa as in example 1
# This function fixes those types of file names
def example_1_fix_archive_file_names(start_date, unpack_archive_path):
# I will first remove every FASTA file that doesn't start with 'D'
files_list_old = os.listdir(unpack_archive_path)
files_list_old.sort()
files_list_new = [i for i in files_list_old if i.startswith('D')
or i.startswith('W')]
files_list_remove = [i for i in files_list_old if i not in files_list_new]
for i in files_list_remove:
os.unlink(os.path.join(unpack_archive_path, i))
# Sorting files and fixing the name. Originally they start with D but
# represent weeks, so I will replace D with W
imported_file_extension = os.path.splitext(
files_list_new[0])[1][1:].strip().lower()
files_list_pass = [i.replace('D', 'W') for i in files_list_new]
files_list_pass = [i.split('_')[0] + '.' + imported_file_extension
for i in files_list_pass]
list_of_dates = create_temporal_column(
files_list_pass, start_date, len(files_list_pass),
files_list_pass[0][0])
list_of_new_names = [i.strftime('%Y-%m-%d') for i in list_of_dates]
for i in range(len(files_list_pass)):
os.replace(
os.path.join(unpack_archive_path, files_list_new[i]),
os.path.join(unpack_archive_path,
list_of_new_names[i] + '.' + imported_file_extension))
return None
def show_data_set(df):
with st.spinner('Showing the data set and related info'):
st.markdown('First 100 entries')
st.dataframe(df.head(100))
try:
tmp_df = df.describe(datetime_is_numeric=True)
if len(tmp_df.columns.to_list()) > 1:
st.markdown('Summary statistics')
st.dataframe(df.describe(datetime_is_numeric=True))
except TypeError or ValueError:
pass
return None
def show_calculated_data_set(df, text_info):
with st.spinner('Calculating features and showing the data set'):
if len(df.columns.to_list()) > 50 or len(df.columns.to_list()) == 1:
st.markdown('**' + text_info + '** ' +
'First 50 entries and first 8 features (columns). ')
st.dataframe(df.iloc[:50, :8])
else:
st.markdown('**' + text_info + '**' + ' First 100 entries.')
st.dataframe(df.head(100))
# TODO: Uncomment pd.describe when the bug is fixed in Pandas
# Bug: https://github.com/pandas-dev/pandas/issues/37429
# More: https://github.com/pandas-dev/pandas/issues/42626
try:
tmp_df = df.describe(datetime_is_numeric=True)
if len(tmp_df.columns.to_list()) > 50\
or len(tmp_df.columns.to_list()) == 1:
st.markdown('**Summary statistics.**' +
' First 8 features (columns).')
st.dataframe(tmp_df.iloc[:, :8])
else:
st.markdown('**Summary statistics**')
st.dataframe(tmp_df)
except TypeError or ValueError:
pass
return None
def show_clustering_info(df, key_suffix):
default_clustering_method_values = []
default_number_of_clusters_or_samples = 2
if key_suffix.endswith('Metaproteomics_CASE_STUDY'):
default_clustering_method_values.append('K-Means')
default_number_of_clusters_or_samples = 3
clustering_methods = st.multiselect(
'Choose clustering method:', options=['K-Means', 'OPTICS'],
key='choose_clus' + key_suffix,
default=default_clustering_method_values)
tmp_df = get_number_of_clusters(df)
st.altair_chart(visualize.elbow_rule(tmp_df),
use_container_width=True)
help_text_kmeans = '''Choose the number according to the elbow rule. The
number of clusters should be the number on the x-axis of
the Elbow chart where the "elbow" exists.'''
help_text_optics = '''Choose the number so that you have a valid number of
clusters according to your preference.'''
if all(i in clustering_methods for i in ['K-Means', 'OPTICS']):
cluster_number = st.slider(
'Select a number of clusters for K-Means using the elbow rule:',
min_value=2, max_value=15, step=1, format='%d',
key='slider_cluster_Kmeans_' + key_suffix, help=help_text_kmeans,
value=default_number_of_clusters_or_samples)
cluster_samples = st.slider(
'Select a minimum number of samples for OPTICS to be considered as\
a core point:', min_value=2, max_value=15, step=1,
format='%d', key='slider_cluster_Optics_' + key_suffix,
help=help_text_optics, value=default_number_of_clusters_or_samples)
elif 'K-Means' in clustering_methods:
cluster_number = st.slider(
'Select a number of clusters for K-Means using the elbow rule:',
min_value=2, max_value=15, step=1, format='%d',
key='slider_cluster_Kmeans_' + key_suffix, help=help_text_kmeans,
value=default_number_of_clusters_or_samples)
cluster_samples = 0
elif 'OPTICS' in clustering_methods:
cluster_number = 0
cluster_samples = st.slider(
'Select a minimum number of samples for OPTICS to be considered as\
a core point:', min_value=2, max_value=15, step=1,
format='%d', key='slider_cluster_Optics_' + key_suffix,
help=help_text_optics, value=default_number_of_clusters_or_samples)
else:
pass
# We create new columns that hold labels for each chosen method
# it holds pairs (name of method, labels)
labels_list = []
for i in clustering_methods:
labels_list.append((i, cluster_data(
df, cluster_number, cluster_samples, i)))
# Cluster evaluation
# TODO: Deal with sklearn future warning !
evaluation_text = ''
for pair in labels_list:
if pair[0] != 'OPTICS':
evaluation_scores = evaluate_clustering(df, pair[1])
evaluation_text += pair[0]\
+ '| silhouette score: ' + str(evaluation_scores[0]) + ', '\
+ 'Calinski-Harabasz index: ' + str(evaluation_scores[1])\
+ ', '\
+ 'Davies-Bouldin index: ' + str(evaluation_scores[2]) + '\n'
if evaluation_text != '':
st.code(evaluation_text)
return labels_list
def check_multi_csv_validity(df_list):
if len(df_list) == 1:
return None
else:
features_check_dict = {}
for i in range(len(df_list)):
feature_list = df_list[i].columns.astype(str).to_list()
# Add features to dict or increment the number
for feature in feature_list:
if feature not in features_check_dict:
features_check_dict[feature] = 0
else:
features_check_dict[feature] += 1
# Now we check if all numbers of appearences are the same, as they
# should be, because data sets must have the same features
tmp_error_signal = None
for feature in features_check_dict:
if tmp_error_signal is None:
tmp_error_signal = features_check_dict[feature]
continue
else:
if tmp_error_signal != features_check_dict[feature]:
st.error('Data sets must have the same features (columns)')
st.stop()
return None
def check_archive_validity(folder_path_or_df, data_set_type):
bad_names_flag = False
list_of_file_extensions = [os.path.splitext(
file_name)[1][1:].strip().lower() for file_name in
os.listdir(folder_path_or_df)]
# We will shrink this list to make everything faster
list_of_file_extensions = list(set(list_of_file_extensions))
valid_extensions = []
if data_set_type == 'FASTA':
valid_extensions = ['faa', 'fa']
elif data_set_type == 'KEGG':
valid_extensions = ['besthits']
elif data_set_type == 'BINS':
valid_extensions = ['gff']
elif data_set_type == 'DEPTH':
return None
if any(i not in valid_extensions for i in list_of_file_extensions):
bad_names_flag = True
if bad_names_flag:
st.error('''One or more file extensions are bad. See upload help above
to find out what file extensions are supported.''')
st.stop()
return None
def create_kegg_matrix(list_data, path_keggs):
print("Creating KEGG matrix")
gene_names = [os.path.splitext(i)[0] for i in os.listdir(path_keggs)]
gene_names.sort()
result_matrix_df = pd.DataFrame(columns=gene_names)
for i in list_data:
tmp_df = i.value_counts().reset_index()
for i, row in tmp_df.iterrows():
result_matrix_df.at[row["ID"], row["Gene"]] = row[0]
result_matrix_df.fillna(0, inplace=True)
result_matrix_df = result_matrix_df.transpose()
print("Finished creating")
return result_matrix_df.sort_index()
def import_kegg_and_create_df(end, path_all_keggs):
print("Importing KEGG data")
kegg_files = os.listdir(path_all_keggs)
kegg_files.sort()
kegg_data_list = []
important_columns = ["Gene", "ID", "maxScore", "hitNumber"]
# This was done so that I could work with first 100 files only. Otherwise,
# I should just remove: i, and enumerate
for i, kegg_file_name in enumerate(kegg_files):
if i == end:
break
else:
# Now I create a DataFrame out of it and save it in the list of
# DataFrames
tmp_df = pd.read_csv(
os.path.join(path_all_keggs, kegg_file_name),
delimiter="\t")
if not all(i in tmp_df.columns.tolist()
for i in important_columns):
st.error('''
Your KEGG file header must contain the following
column names: ''' + important_columns)
st.stop()
tmp_df["Gene"] = tmp_df["Gene"].apply(
lambda x: str(x).split("_PROKKA")[0])
tmp_df["ID"] = tmp_df["ID"].apply(lambda x: str(x).split(":")[1])
tmp_df.drop(["maxScore", "hitNumber"], axis=1, inplace=True)
tmp_df.reset_index(drop=True, inplace=True)
kegg_data_list.append(tmp_df)
print("Finished importing")
return create_kegg_matrix(kegg_data_list, path_all_keggs)
def create_annotated_data_set(end, path_bins):
print("Importing BIN annotated data set")
bin_files = os.listdir(path_bins)
bin_files.sort()
# Creating nested dictionary where each rmag has a dict of products and
# their number of occurence for that rmag
final_dict = {}
for i in bin_files:
final_dict[os.path.splitext(i)[0]] = {}
# Traversing every annotation file, line by line, and saving only 'product'
# column TODO: This can be extended with more columns
for annotation_file in bin_files:
with open(os.path.join(path_bins, annotation_file), 'r') as input_file:
gene_name = str(os.path.splitext(annotation_file)[0])
for line in input_file:
product = line.split('product=')[-1].split(';')[0].rstrip()
if product not in final_dict[gene_name]:
final_dict[gene_name][product] = 0
else:
final_dict[gene_name][product] += 1