-
Notifications
You must be signed in to change notification settings - Fork 2
/
dataset.py
1476 lines (1282 loc) · 50.9 KB
/
dataset.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 copy
import itertools
import math
import os
import pickle
import re
from collections import Counter
from itertools import tee
from textwrap import wrap
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import shap
from ipywidgets import VBox
from plotly.subplots import make_subplots
from plotly.tools import mpl_to_plotly
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import (
GroupShuffleSplit,
cross_val_predict,
cross_val_score,
)
from sklearn.neighbors import LocalOutlierFactor
from microbiome.enumerations import (
FeatureColumnsType,
Normalization,
ReferenceGroup,
TimeUnit,
)
RANDOM_STATE = 42
class MicrobiomeDataset:
# initial columns, necessary for the toolbox to work
specific_columns = [
"sampleID",
"subjectID",
"group",
"age_at_collection",
"reference_group",
]
# new columns automatically created
# Note: e.g. reference group = healthy samples
# non reference group = non healthy samples
# group = country
future_columns = []
def __init__(self, file_name=None, feature_columns=FeatureColumnsType.BACTERIA):
if file_name == "mouse_data":
file_name = "https://raw.githubusercontent.com/JelenaBanjac/microbiome-toolbox/main/notebooks/Mouse_16S/INPUT_FILES/website_mousedata.csv"
elif file_name == "human_data":
file_name = "https://raw.githubusercontent.com/JelenaBanjac/microbiome-toolbox/main/notebooks/Human_Subramanian/INPUT_FILES/subramanian_et_al_l2_ELM_website.csv"
elif file_name is None:
raise Exception("Specify a valid file name. Or choose existing options: `mouse_data` or `human_data`")
# create dataframe regardless of delimiter (sep)
self.df = pd.read_csv(file_name, sep=None, engine="python")
print("columns", self.df.columns)
# collect all columns that are missing
missing_columns = []
for col in self.specific_columns:
if col not in self.df.columns:
if col == "reference_group":
# if this column doesn't exist, create it s.t.
# all samples are in reference by default
self.df["reference_group"] = True
elif col == "group":
# if this column doesn't exist, create it s.t.
# all samples are in one group by default
self.df["group"] = 'none'
else:
missing_columns.append(col)
# check if there is at least one column with bacteria
bacteria_columns = self.df.columns[
# (~self.df.columns.isin(self.specific_columns))
(~self.df.columns.str.contains('|'.join(self.specific_columns)))
& (~self.df.columns.isin(self.future_columns))
& (~self.df.columns.str.startswith("meta_"))
& (~self.df.columns.str.startswith("id_"))
].tolist()
if len(bacteria_columns) > 0:
# if there are bacteria columns, make sure these columns have `bacteria_` prefix
self.df = self.df.rename(
mapper={
k: f"bacteria_{k}"
for k in bacteria_columns
if not k.startswith("bacteria_")
},
axis=1,
)
else:
missing_columns.append("bacteria_*")
print("bacteria_columns", self.bacteria_columns)
if len(missing_columns) > 0:
raise Exception(
"There was an error processing this file! Missing columns: "
+ ",".join(missing_columns)
)
self.df = self.df.apply(lambda row: self._fix_zeros(row), axis=1)
# preprocess df
self.df.sampleID = self.df.sampleID.astype(str)
self.df.subjectID = self.df.subjectID.astype(str)
self.df.reference_group = self.df.reference_group.fillna(False).astype(bool)
self.df = self.df.convert_dtypes()
# convert metadata string columns to categorical
for column in self.metadata_columns:
self.df[column] = self.df[column].astype("category")
# dummy encoding of metadata columns (string and object type)
self.df = pd.get_dummies(self.df, dummy_na=True, columns=self.metadata_columns)
self.df = self.df.fillna(0)
self.df = self.df.sort_values(by="age_at_collection", ignore_index=True)
# initialize trajectory values
self.df["MMI"] = 0
# initialize feature columns (only once, in constructor!)
if isinstance(feature_columns, (list, np.ndarray)):
self._feature_columns = feature_columns
elif feature_columns == FeatureColumnsType.BACTERIA:
self._feature_columns = self.bacteria_columns
elif feature_columns == FeatureColumnsType.METADATA:
self._feature_columns = self.metadata_columns
elif feature_columns == FeatureColumnsType.BACTERIA_AND_METADATA:
self._feature_columns = self.bacteria_and_metadata_columns
# save initial
self.__age_at_collection = self.df.age_at_collection.to_numpy()
self.__reference_group = self.df.reference_group.to_numpy()
self.__df = self.df.copy(deep=True)
# normalization by log-ratio
self.log_ratio_bacteria = None
# normalization by mean and std (along columns)
self.normalized = Normalization.NON_NORMALIZED
self.time_unit = TimeUnit.DAY
self.set_reference_group_choice(ReferenceGroup.USER_DEFINED)
self.nice_name = (
lambda x: re.sub(" +", "|", re.sub("[kpcofgs]__|\.|_", " ", x[9:]).strip())
if x.startswith("bacteria_")
else x
)
self.layout_settings_default = dict(
height=900,
width=1200,
plot_bgcolor="rgba(255,255,255,255)",
paper_bgcolor="rgba(255,255,255,255)",
margin=dict(l=70, r=70, t=70, b=70),
font=dict(size=17),
hoverdistance=-1,
legend=dict(
x=1.01,
y=1,
),
)
self.axis_settings_default = dict(
tick0=0,
mirror=True,
showline=True,
linecolor="lightgrey",
gridcolor="lightgrey",
zeroline=True,
zerolinecolor="lightgrey",
showspikes=True,
spikecolor="gray",
autorange=True,
)
def __str__(self):
ret_val = ""
# dataframe size
ret_val += "### Dataset size\n"
ret_val += f"#samples = {self.df.shape[0]}, #columns = {self.df.shape[1]}\n"
# counts per column type
ret_val += "### Counts per column type\n"
ret_val += f"Number of bacteria columns: {len(self.bacteria_columns)}\n"
ret_val += f"Number of metadata columns: {len(self.metadata_columns)}\n"
ret_val += f"Number of ID columns: {len(self.id_columns)}\n"
ret_val += f"Number of other columns: {len(self.other_columns)}\n"
# count reference
ret_val += "### Reference group\n"
ref_counts = self.df.reference_group.value_counts()
ret_val += f"Reference group count vs. non-reference: {ref_counts[True]} vs. {ref_counts[False]}\n"
return ret_val
def _fix_zeros(self, row):
for col in self.bacteria_columns:
try:
row[col] = 1e-10 if row[col] == 0.0 or row[col] < 1e-10 else row[col]
except TypeError as e:
raise Exception(
f"Check yout bacteria columns, {col[9:]} doesn't have a numerical values."
) from e
return row
@property
def time_unit(self):
return self._time_unit
@time_unit.setter
def time_unit(self, val):
"""Modify age_at_collection column"""
if val not in TimeUnit:
raise ValueError(f"There is no value {val} in TimeUnit enumeration class!")
self._time_unit = val
self.df.age_at_collection = self.__age_at_collection / val.value
self.df.MMI = self.df.MMI / val.value
@property
def nice_name(self):
return self._nice_name
@nice_name.setter
def nice_name(self, val):
self._nice_name = val
# @property
def get_reference_group_choice(self):
return self._reference_group_choice
# @reference_group_choice.setter
def set_reference_group_choice(self, val, novelty_settings=None):
"""Modify reference_group column"""
if val not in ReferenceGroup:
raise ValueError(
f"There is no value {val} in ReferenceGroup enumeration class!"
)
self._reference_group_choice = val
self.df.reference_group = self.__reference_group
# TODO: feature_columns can be 3 cases
X = self.df[self.feature_columns].values
y = self.df.reference_group.values
groups = self.df.subjectID.values
if val == ReferenceGroup.NOVELTY_DETECTION:
reference_group = self._find_best_novelty_reference_group(X, y, groups, settings=novelty_settings)
elif val == ReferenceGroup.USER_DEFINED:
reference_group = self.__reference_group
else:
raise NotImplementedError(f"Not implemented yet {val}, {type(val)}!")
self.df.reference_group = reference_group
# get latest values for y and groups
y = self.df.reference_group.values
# groups = self.df.subjectID.values
if len(self.df.reference_group.unique()) == 1:
results = {
"accuracy": "",
"f1score": "",
"fig": None,
"config": None,
"img_src": None,
}
else:
results = two_groups_differentiation(
self.df[self.feature_columns],
self.df.reference_group,
groups,
y_column="reference_group",
plot=True,
)
self._differentiation_score = results["f1score"]
self.reference_group_plot = results["fig"]
self.reference_group_img_src = results["img_src"]
self.reference_group_accuracy = results["accuracy"]
self.reference_group_f1score = results["f1score"]
self.reference_group_config = results["config"]
def _find_best_novelty_reference_group(self, X, y, groups, settings=None):
# if novelty_settings is None:
# c = Counter(groups)
# n_neighbors_min = 1
# n_neighbors_max = c.most_common(1)[0][1]
# n_neighbors_list = set(
# [
# n_neighbors_min,
# (n_neighbors_min + n_neighbors_max) // 2 + 1,
# n_neighbors_max,
# ]
# )
# novelty_settings = []
# for n_neighbors in n_neighbors_list:
# novelty_settings.append({"n_neighbors": n_neighbors})
# f1score_best = 0
# settings_best = None
# reference_group_best = None
# for settings in novelty_settings:
# # initialize reference group with the given start values
# reference_group = copy.deepcopy(y)
# # novelty detection
# settings_final = {
# "metric": "braycurtis",
# "n_neighbors": 2,
# **settings,
# }
# X_train = X[reference_group == True]
# X_test = X[reference_group == False]
# # find outliers (ones that shall not be in the reference)
# lof = LocalOutlierFactor(novelty=True, **settings_final)
# lof.fit(X_train)
# y_test = lof.predict(X_test)
# # modify reference
# reference_group[reference_group == False] = y_test == 1
# # calculate new f1score
# results = two_groups_differentiation(
# X, copy.deepcopy(reference_group), groups
# )
# f1score = results["f1score"]
# print(f"Novelty settings: {settings_final}")
# print(f"Novelty f1score: {f1score}")
# print(pd.Series(reference_group).value_counts())
# if not all(reference_group):
# if f1score > f1score_best:
# f1score_best = f1score
# settings_best = settings
# reference_group_best = copy.deepcopy(reference_group)
# print(f"BEST Novelty settings: {settings_best}")
# print(f"BEST Novelty f1score: {f1score_best}")
# return reference_group_best
# initialize reference group with the given start values
reference_group = copy.deepcopy(y)
# novelty detection
if settings is None:
settings = {}
settings_final = {
"metric": "braycurtis",
"n_neighbors": 2,
**settings,
}
X_train = X[reference_group == True]
X_test = X[reference_group == False]
# find outliers (ones that shall not be in the reference)
lof = LocalOutlierFactor(novelty=True, **settings_final)
lof.fit(X_train)
y_test = lof.predict(X_test)
# modify reference
reference_group[reference_group == False] = y_test == 1
return reference_group
@property
def differentiation_score(self):
return self._differentiation_score
@property
def feature_columns(self):
if self.log_ratio_bacteria is not None:
feature_columns = self._feature_columns[
self._feature_columns != self.log_ratio_bacteria
]
else:
feature_columns = self._feature_columns
return feature_columns
@feature_columns.setter
def feature_columns(self, val):
if isinstance(val, list):
self._feature_columns = val
elif isinstance(val, FeatureColumnsType):
if val == FeatureColumnsType.BACTERIA:
self._feature_columns = self.bacteria_columns
elif val == FeatureColumnsType.METADATA:
self._feature_columns = self.metadata_columns
elif val == FeatureColumnsType.BACTERIA_AND_METADATA:
self._feature_columns = self.bacteria_and_metadata_columns
# but also update novelty detection result if it was used
# self.reference_group_choice = self._reference_group_choice
@property
def bacteria_columns(self):
return self.df.columns[self.df.columns.str.startswith("bacteria_")].to_numpy()
@property
def metadata_columns(self):
return self.df.columns[self.df.columns.str.startswith("meta_")].to_numpy()
@property
def id_columns(self):
return self.df.columns[self.df.columns.str.startswith("id_")].to_numpy()
@property
def other_columns(self):
return self.df.columns[
(~self.df.columns.str.startswith("bacteria_"))
& (~self.df.columns.str.startswith("meta_"))
& (~self.df.columns.str.startswith("id_"))
].to_numpy()
@property
def bacteria_and_metadata_columns(self):
return np.concatenate((self.bacteria_columns, self.metadata_columns))
@property
def log_ratio_bacteria(self):
return self._log_ratio_bacteria
@log_ratio_bacteria.setter
def log_ratio_bacteria(self, val):
bacteria_columns_all = self.__df.columns[
self.__df.columns.str.startswith("bacteria_")
].to_numpy()
self._log_ratio_bacteria = val
features = self.__df[bacteria_columns_all].values
if val is not None:
self.normalized = Normalization.NON_NORMALIZED
for i, c in enumerate(bacteria_columns_all):
self.df.loc[:, c] = features[:, i]
if c != val:
self.df[c] = self.df.apply(
lambda row: math.log2(row[c] / row[val]), axis=1
)
# remove reference, since these are abundances
self.df = self.df.drop(columns=val, axis=1)
else:
for i, feature_column in enumerate(bacteria_columns_all):
self.df.loc[:, feature_column] = features[:, i]
# self.df = self.__df.copy(deep=True)
@property
def normalized(self):
return self._normalized
@normalized.setter
def normalized(self, val):
"""Normalize all bacteria and metadata columns to 0-1 range.
Normalization is performed both for novelty and trajectory features.
Parameters
----------
val : Normalization
Value indicates whether to normalize or not (NORMALIZED or NON_NORMALIZED).
"""
self._normalized = val
features = self.__df[self.bacteria_and_metadata_columns].values
if val == Normalization.NORMALIZED:
from sklearn.preprocessing import normalize
features = normalize(features, axis=0)
for i, feature_column in enumerate(self.bacteria_and_metadata_columns):
self.df.loc[:, feature_column] = features[:, i]
def set_log_ratio_bacteria_with_least_crossings(self):
def _crossings(x, y1, y2, degree=5):
"""
To calculate crossing points between two abundance curves,
we do the following:
- approximate bacteria abundance over time with a curve,
- get the indices of coordinates where two curves intersect.
"""
f1 = np.poly1d(np.polyfit(x, y1, degree))
f2 = np.poly1d(np.polyfit(x, y2, degree))
x_new = np.linspace(min(x), max(x))
# approximated bacteria abundances y1_new, y2_new
y1_new = f1(x_new)
y2_new = f2(x_new)
# crossings
idx = np.argwhere(np.diff(np.sign(y1_new - y2_new))).flatten()
return idx
from collections import defaultdict
from itertools import product
# abundance approximations
x = self.__df.age_at_collection.tolist()
number_of_crossings = defaultdict(lambda: 0)
for b1, b2 in product(self.bacteria_columns, self.bacteria_columns):
if b1 != b2:
# bacteria abundances y1, y2
y1 = self.__df[b1].tolist()
y2 = self.__df[b2].tolist()
number_of_crossings[b1] += len(_crossings(x, y1, y2, degree=5))
# bacteria with the least number of crossings
self.log_ratio_bacteria = min(number_of_crossings, key=number_of_crossings.get)
def write_data(self, filename):
with open(filename, "wb") as f:
pickle.dump(self, f)
@classmethod
def read_data(filename):
if os.path.exists(filename):
with open(filename, "rb") as f:
df = pickle.loads(f.read())
else:
df = None
return df
def z_score(self, column_name, sample_size=30):
# TODO: above and below zscore values
data = self.df[[column_name, "age_at_collection"]]
data.age_at_collection //= sample_size
from scipy.stats import zmap
column_zscore = data.apply(
lambda x: zmap(
x[column_name],
data[data.age_at_collection == x.age_at_collection][
column_name
].tolist(),
)[0],
axis=1,
).tolist()
return column_zscore
def plot_bacteria_abundances(
self,
number_of_columns=3,
layout_settings=None,
xaxis_settings=None,
yaxis_settings=None,
):
number_of_rows = len(self.bacteria_columns) // number_of_columns + 1
layout_settings_default = dict(
height=number_of_rows * 200,
width=1500,
plot_bgcolor="rgba(255,255,255,255)",
paper_bgcolor="rgba(255,255,255,255)",
margin=dict(l=0, r=0, b=0, pad=0),
title_text="Bacteria Abundances in the Dataset",
font=dict(size=10),
yaxis=dict(position=0.0),
)
if layout_settings is None:
layout_settings = {}
layout_settings_final = {**layout_settings_default, **layout_settings}
if xaxis_settings is None:
xaxis_settings = {}
if yaxis_settings is None:
yaxis_settings = {}
xaxis_settings_final = {**self.axis_settings_default, **xaxis_settings}
yaxis_settings_final = {**self.axis_settings_default, **yaxis_settings}
fig = make_subplots(
rows=number_of_rows,
cols=number_of_columns,
horizontal_spacing=0.1,
subplot_titles=[
"<br>".join(wrap(str(b), 50)) for b in list(self.bacteria_columns)
],
)
for idx, bacteria_name in enumerate(self.bacteria_columns):
df = self.df[["age_at_collection", bacteria_name]]
fig.add_trace(
go.Scatter(
x=df.groupby(by="age_at_collection")
.agg(np.mean)[bacteria_name]
.index,
y=df.groupby(by="age_at_collection")
.agg(np.mean)[bacteria_name]
.values,
error_y=dict(
type="data", # value of error bar given in data coordinates
array=df.groupby(by="age_at_collection")
.agg(np.std)[bacteria_name]
.values,
visible=True,
),
name=self.nice_name(bacteria_name),
hovertemplate="Abundance: %{y:.2f}"
+ f"<br>{self.time_unit.name}:"
+ " %{x}",
),
row=idx // number_of_columns + 1,
col=idx % number_of_columns + 1,
)
fig.update_xaxes(
title=f"Age at collection [{self.time_unit.name}]",
row=idx // number_of_columns + 1,
col=idx % number_of_columns + 1,
**xaxis_settings_final,
)
fig.update_yaxes(
title="Abundance value",
row=idx // number_of_columns + 1,
col=idx % number_of_columns + 1,
**yaxis_settings_final,
)
for i in fig["layout"]["annotations"]:
i["font"] = dict(size=10)
fig.update_layout(**layout_settings_final)
config = {
"toImageButtonOptions": {
"format": "svg", # one of png, svg, jpeg, webp
"filename": "bacteria_abundances",
"height": layout_settings_final["height"],
"width": layout_settings_final["width"],
"scale": 1, # Multiply title/legend/axis/canvas sizes by this factor
}
}
results = {"fig": fig, "config": config}
return results
def plot_bacteria_abundance_heatmaps(
self,
relative_values=False,
fillna=False,
dropna=False,
avg_fn=np.median,
layout_settings=None,
):
layout_settings_default = dict(
height=20 * len(self.bacteria_columns),
width=1500,
)
if layout_settings is None:
layout_settings = {}
layout_settings_final = {**layout_settings_default, **layout_settings}
# extract just the important columns for the heatmap
df = self.df[list(self.bacteria_columns) + ["subjectID", "age_at_collection"]]
# replace long bacteria names with nice names
# df = df.rename({b: self.nice_name(b) for b in self.bacteria_columns}, axis=1)
# update the bacteria_names with short names
def fill_collected(row):
"""Ïf we use bigger time units, then we need to find a median when collapsing all the samples in that time interval into one box in the heatmap"""
val = df[df["age_at_collection"] == row["age_at_collection"]][
row["bacteria_name"]
].values
row["bacteria_value"] = avg_fn(val) if len(val) != 0 else np.nan
return row
x, y = np.meshgrid(
self.bacteria_columns, range(int(max(df.age_at_collection)) + 1)
)
df_heatmap = pd.DataFrame(
data={
"bacteria_name": x.flatten(),
"age_at_collection": y.flatten(),
"bacteria_value": np.nan,
}
)
df_heatmap = df_heatmap.sort_values(by=["bacteria_name", "age_at_collection"])
# if dropna:
# df_heatmap = df_heatmap.dropna()
df_heatmap = df_heatmap.fillna(0)
df_heatmap = df_heatmap.apply(lambda row: fill_collected(row), axis=1)
# create new column bacteria_name_cat in order to sort dataframe by bacteria importance
df_heatmap["bacteria_name_cat"] = pd.Categorical(
df_heatmap["bacteria_name"],
categories=self.bacteria_columns, # order of bacteria is imposed by the list
ordered=True,
)
df_heatmap = df_heatmap.sort_values("bacteria_name_cat")
df_heatmap = df_heatmap[df_heatmap.age_at_collection > 0]
if relative_values:
X = df_heatmap.bacteria_value.values
X = X.reshape(len(self.bacteria_columns), -1)
xmin = np.nanmin(X, axis=1).reshape(len(self.bacteria_columns), 1)
xmax = np.nanmax(X, axis=1).reshape(len(self.bacteria_columns), 1)
X_std = (X - xmin) / (xmax - xmin + 1e-10)
df_heatmap.bacteria_value = X_std.flatten()
# plot top absolute
df_heatmap = df_heatmap[
["age_at_collection", "bacteria_name_cat", "bacteria_value"]
]
bacteria_names = list(map(self.nice_name, self.bacteria_columns))
uniquify(bacteria_names, suffs=(f"_{x!s}" for x in range(1, 100)))
bacteria_names = np.array(bacteria_names)
bacteria_names_mapping = {
k: v for k, v in zip(self.bacteria_columns, bacteria_names)
}
def _rename_bacteria(row):
row["bacteria_name_cat"] = bacteria_names_mapping[row["bacteria_name_cat"]]
return row
df_heatmap = df_heatmap.apply(lambda row: _rename_bacteria(row), axis=1)
df_heatmap_pivot = df_heatmap.pivot(
"bacteria_name_cat", "age_at_collection", "bacteria_value"
)
if fillna:
df_heatmap_pivot = df_heatmap_pivot.fillna(0)
if dropna:
df_heatmap_pivot = df_heatmap_pivot.dropna(axis=1, how="all")
xaxis_mapping = {v: k for k, v in enumerate(df_heatmap_pivot.columns.tolist())}
fig = px.imshow(
df_heatmap_pivot.values,
labels=dict(
x=f"Age [{self.time_unit.name}]", y="Bacteria Name", color="Abundance"
),
x=[xaxis_mapping[i] for i in df_heatmap_pivot.columns.tolist()],
y=df_heatmap_pivot.index.tolist(),
title="Abundances",
**layout_settings_final,
)
if dropna:
fig.update_xaxes(
side="bottom",
tickvals=[xaxis_mapping[i] for i in df_heatmap_pivot.columns.tolist()],
ticktext=df_heatmap_pivot.columns.tolist(),
)
config = {
"toImageButtonOptions": {
"format": "svg", # one of png, svg, jpeg, webp
"filename": "bacteria_abundances_heatmap",
"height": layout_settings_final["height"],
"width": layout_settings_final["width"],
"scale": 1, # Multiply title/legend/axis/canvas sizes by this factor
}
}
results = {"fig": fig, "config": config}
return results
def plot_ultradense_longitudinal_data(
self,
number_of_columns=6,
number_of_bacteria=20,
color_palette="tab20",
layout_settings=None,
xaxis_settings=None,
yaxis_settings=None,
):
number_of_rows = len(self.df.subjectID.unique()) // number_of_columns + int(
len(self.df.subjectID.unique()) % number_of_columns > 0
)
# plotly settings
layout_settings_default = dict(
height=350 * number_of_rows,
width=1500,
plot_bgcolor="rgba(0,0,0,0)",
title_text="Ultradense Longitudinal Data",
)
if layout_settings is None:
layout_settings = {}
layout_settings_final = {**layout_settings_default, **layout_settings}
if xaxis_settings is None:
xaxis_settings = {}
if yaxis_settings is None:
yaxis_settings = {}
xaxis_settings_final = {**self.axis_settings_default, **xaxis_settings}
yaxis_settings_final = {**self.axis_settings_default, **yaxis_settings}
# limit to plot 20 bacteria
bacteria_names = self.bacteria_columns[:number_of_bacteria]
cmap = plt.cm.get_cmap(color_palette, len(bacteria_names))
colors_dict = dict([(b, cmap(i)) for i, b in enumerate(bacteria_names)])
fig = make_subplots(
rows=number_of_rows,
cols=number_of_columns,
shared_xaxes=True,
shared_yaxes=True,
vertical_spacing=0.08,
horizontal_spacing=0.01,
)
for idx, infant in enumerate(self.df.subjectID.unique()):
i, j = (
idx // number_of_columns,
idx % number_of_columns,
)
df1 = self.df.reset_index()
df1 = df1[df1.subjectID == infant].sort_values("age_at_collection")
if len(df1) == 1:
for b in bacteria_names:
fig.add_trace(
go.Scatter(
x=list(df1.age_at_collection.values),
y=list(df1[b].values) * 2,
text=list(map(lambda x: self.nice_name(x), bacteria_names)),
mode="lines",
marker_color=f"rgba{colors_dict[b]}",
name=self.nice_name(b),
legendgroup=self.nice_name(b),
showlegend=True if idx == 0 else False,
stackgroup="one", # define stack group
hovertemplate=f"Taxa: {self.nice_name(b)}"
+ "<br>Abundance: %{y:.2f}"
+ f"<br>{self.time_unit.name}:"
+ " %{x}",
),
row=i + 1,
col=j + 1,
)
fig.update_xaxes(
title=infant,
row=i + 1,
col=j + 1,
**xaxis_settings_final,
)
fig.update_yaxes(
**yaxis_settings_final,
)
else:
for b in bacteria_names:
fig.add_trace(
go.Scatter(
x=list(df1.age_at_collection.values),
y=list(df1[b].values),
text=list(map(lambda x: self.nice_name(x), bacteria_names)),
mode="lines",
marker_color=f"rgba{colors_dict[b]}",
name=self.nice_name(b),
legendgroup=self.nice_name(b),
showlegend=True if idx == 0 else False,
stackgroup="one",
hovertemplate=f"Taxa: {self.nice_name(b)}"
+ "<br>Abundance: %{y:.2f}"
+ f"<br>{self.time_unit.name}:"
+ " %{x}",
),
row=i + 1,
col=j + 1,
)
fig.update_xaxes(
title=infant,
row=i + 1,
col=j + 1,
**xaxis_settings_final,
)
fig.update_yaxes(
**yaxis_settings_final,
)
fig.update_layout(**layout_settings_final)
for i in fig["layout"]["annotations"]:
i["font"] = dict(size=8, color="#000000")
config = {
"toImageButtonOptions": {
"format": "svg", # one of png, svg, jpeg, webp
"filename": "bacteria_abundances_longitudinal",
"height": layout_settings_final["height"],
"width": layout_settings_final["width"],
"scale": 1, # Multiply title/legend/axis/canvas sizes by this factor
}
}
results = {"fig": fig, "config": config}
return results
def embedding_to_latent_space(
self,
color_column_name=None,
embedding_model=PCA(n_components=3),
embedding_dimension=2,
layout_settings=None,
xaxis_settings=None,
yaxis_settings=None,
):
fig = go.Figure()
color_column_name = color_column_name or "group"
subjectIDs = np.array(self.df.subjectID.tolist())
sampleIDs = np.array(self.df.sampleID.tolist())
X = self.df[self.feature_columns].values
X_emb = embedding_model.fit_transform(X)
if isinstance(embedding_model, PCA):
xaxis_label = f"PC1 - {embedding_model.explained_variance_ratio_[0]*100:.1f}% explained variance"
yaxis_label = f"PC2 - {embedding_model.explained_variance_ratio_[1]*100:.1f}% explained variance"
else:
xaxis_label = "1st dimension"
yaxis_label = "2nd dimension"
# plotly settings
layout_settings_default = dict(
height=600,
width=600,
barmode="stack",
uniformtext=dict(mode="hide", minsize=10),
plot_bgcolor="rgba(0,0,0,0)",
paper_bgcolor="rgba(0,0,0,0)",
margin=dict(l=0, r=0, b=0, pad=0),
title_text=f"Embedding in {embedding_dimension}D space",
annotations=[
dict(
x=0.5,
y=1.05,
align="right",
valign="top",
text="colored by " + color_column_name,
showarrow=False,
xref="paper",
yref="paper",
xanchor="center",
yanchor="top",
)
],
)
if layout_settings is None:
layout_settings = {}
layout_settings_final = {**layout_settings_default, **layout_settings}
if xaxis_settings is None:
xaxis_settings = {}
if yaxis_settings is None:
yaxis_settings = {}
xaxis_settings_final = {**self.axis_settings_default, **xaxis_settings}
yaxis_settings_final = {**self.axis_settings_default, **yaxis_settings}
if embedding_dimension == 2:
if color_column_name:
for g in self.df[color_column_name].unique():
idx = np.where(np.array(self.df[color_column_name].values) == g)[0]
fig.add_trace(
go.Scatter(
x=X_emb[:, 0][idx],
y=X_emb[:, 1][idx],
name=str(g) or "NaN",
mode="markers",
text=[
f"<b>SampleID</b> {i}<br><b>SubjectID</b> {j}<br>"
for i, j in zip(sampleIDs[idx], subjectIDs[idx])
],
hovertemplate="%{text}"
+ f"<b>Group ({color_column_name}): {g}</b><br>"
+ "<b>x</b>: %{x:.2f}<br>"
+ "<b>y</b>: %{y:.2f}<br>",
)
)
else:
fig.add_trace(
go.Scatter(
x=X_emb[:, 0],
y=X_emb[:, 1],
# name=sampleIDs,
mode="markers",
text=[
f"<b>SampleID</b> {i}<br><b>SubjectID</b> {j}<br>"
for i, j in zip(sampleIDs, subjectIDs)
],