-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathtest_pydeseq2.py
More file actions
890 lines (693 loc) · 26.6 KB
/
Copy pathtest_pydeseq2.py
File metadata and controls
890 lines (693 loc) · 26.6 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
import os
from pathlib import Path
import anndata as ad
import numpy as np
import pandas as pd
import pytest
import tests
from pydeseq2.dds import DeseqDataSet
from pydeseq2.ds import DeseqStats
from pydeseq2.preprocessing import deseq2_norm
from pydeseq2.preprocessing import deseq2_norm_fit
from pydeseq2.preprocessing import deseq2_norm_transform
from pydeseq2.utils import load_example_data
# Single-factor tests
@pytest.fixture
def counts_df():
return load_example_data(
modality="raw_counts",
dataset="synthetic",
debug=False,
)
@pytest.fixture
def metadata():
return load_example_data(
modality="metadata",
dataset="synthetic",
debug=False,
)
def test_size_factors_ratio(counts_df, metadata):
"""Test that the size_factors calcuation by ratio matches R."""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_size_factors.csv"),
index_col=0,
)["x"].values
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors="condition")
dds.fit_size_factors()
np.testing.assert_almost_equal(
dds.obsm["size_factors"].ravel(), r_size_factors.ravel()
)
def test_size_factors_poscounts(counts_df, metadata):
"""Test that the size_factors calcuation by poscount matches R."""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors="condition")
dds.fit_size_factors("poscounts")
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_size_factors_poscount.csv"),
index_col=0,
)["sizeFactor"].values
np.testing.assert_almost_equal(dds.obsm["size_factors"].ravel(), r_size_factors)
def test_size_factors_control_genes(counts_df, metadata):
"""Test that the size_factors calculation properly takes control_genes"""
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors="condition")
dds.fit_size_factors(control_genes=["gene4"])
np.testing.assert_almost_equal(
dds.obsm["size_factors"].ravel(),
counts_df["gene4"] / np.exp(np.log(counts_df["gene4"]).mean()),
)
dds.fit_size_factors(fit_type="poscounts", control_genes=[3])
np.testing.assert_almost_equal(
dds.obsm["size_factors"].ravel(),
counts_df["gene4"] / np.exp(np.log(counts_df["gene4"]).mean()),
)
dds.fit_size_factors(fit_type="poscounts")
np.testing.assert_raises(
AssertionError,
np.testing.assert_array_equal,
dds.obsm["size_factors"].ravel(),
counts_df["gene4"] / np.exp(np.log(counts_df["gene4"]).mean()),
)
def test_deseq_independent_filtering_parametric_fit(counts_df, metadata, tol=0.02):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_res.csv"),
index_col=0,
)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors="condition",
fit_type="parametric",
)
dds.deseq2()
res = DeseqStats(dds)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_deseq_independent_filtering_mean_fit(counts_df, metadata, tol=0.02):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error, with a mean fit.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_res_mean_curve.csv"),
index_col=0,
)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors="condition",
fit_type="mean",
)
dds.deseq2()
res = DeseqStats(dds)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_deseq_without_independent_filtering_parametric_fit(
counts_df, metadata, tol=0.02
):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error, with a parametric fit and no
independent filtering.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(
test_path, "data/single_factor/r_test_res_no_independent_filtering.csv"
),
index_col=0,
)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors="condition",
fit_type="parametric",
)
dds.deseq2()
res = DeseqStats(dds, independent_filter=False)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
@pytest.mark.parametrize("alt_hypothesis", ["lessAbs", "greaterAbs", "less", "greater"])
def test_alt_hypothesis(alt_hypothesis, counts_df, metadata, tol=0.02):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error, with the alternative hypothesis test.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, f"data/single_factor/r_test_res_{alt_hypothesis}.csv"),
index_col=0,
)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors="condition",
)
dds.deseq2()
res = DeseqStats(
dds,
lfc_null=-0.5 if alt_hypothesis == "less" else 0.5,
alt_hypothesis=alt_hypothesis,
)
res.summary()
res_df = res.results_df
# check that the same p-values are NaN
assert (res_df.pvalue.isna() == r_res.pvalue.isna()).all()
assert (res_df.padj.isna() == r_res.padj.isna()).all()
# Check that the same LFC and Wald statistics are found (up to tol)
assert (
abs(r_res.log2FoldChange - res_df.log2FoldChange) / abs(r_res.log2FoldChange)
).max() < tol
if alt_hypothesis == "lessAbs":
res_df.stat = res_df.stat.abs()
assert (abs(r_res.stat - res_df.stat) / abs(r_res.stat)).max() < tol
# Check for the same pvalue and padj where stat != 0
assert (
abs(r_res.pvalue[r_res.stat != 0] - res_df.pvalue[res_df.stat != 0])
/ r_res.pvalue[r_res.stat != 0]
).max() < tol
def test_deseq_no_refit_cooks(counts_df, metadata, tol=0.02):
"""Test that the outputs of the DESeq2 function *without cooks refit*
match those of the original R package, up to a tolerance in relative error.
Note: this is just to check that the workflow runs bug-free, as we expect no outliers
in the synthetic dataset.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_res.csv"), index_col=0
)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors="condition",
refit_cooks=False,
)
dds.deseq2()
res = DeseqStats(dds)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_lfc_shrinkage(counts_df, metadata, tol=0.02):
"""Test that the outputs of the lfc_shrink function match those of the original
R package (starting from the same inputs), up to a tolerance in relative error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_res.csv"), index_col=0
)
r_shrunk_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_lfc_shrink_res.csv"),
index_col=0,
)
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_size_factors.csv"),
index_col=0,
).squeeze()
r_dispersions = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_dispersions.csv"),
index_col=0,
).squeeze()
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors="condition")
dds.deseq2()
dds.obsm["size_factors"] = r_size_factors.values
dds.varm["dispersions"] = r_dispersions.values
dds.varm["LFC"].iloc[:, 1] = r_res.log2FoldChange.values * np.log(2)
res = DeseqStats(dds)
res.summary()
res.SE = r_res.lfcSE * np.log(2)
res.lfc_shrink(coeff="condition_B_vs_A")
shrunk_res = res.results_df
# Check that the same LFC are found (up to tol)
assert (
abs(r_shrunk_res.log2FoldChange - shrunk_res.log2FoldChange)
/ abs(r_shrunk_res.log2FoldChange)
).max() < tol
def test_lfc_shrinkage_no_apeAdapt(counts_df, metadata, tol=0.02):
"""Test that the outputs of the lfc_shrink function match those of the original
R package (starting from the same inputs), up to a tolerance in relative error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_res.csv"), index_col=0
)
r_shrunk_res = pd.read_csv(
os.path.join(
test_path, "data/single_factor/r_test_lfc_shrink_no_apeAdapt_res.csv"
),
index_col=0,
)
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_size_factors.csv"),
index_col=0,
).squeeze()
r_dispersions = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_dispersions.csv"),
index_col=0,
).squeeze()
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors="condition")
dds.deseq2()
dds.obsm["size_factors"] = r_size_factors.values
dds.varm["dispersions"] = r_dispersions.values
dds.varm["LFC"].iloc[:, 1] = r_res.log2FoldChange.values * np.log(2)
res = DeseqStats(dds)
res.summary()
res.SE = r_res.lfcSE * np.log(2)
res.lfc_shrink(coeff="condition_B_vs_A", adapt=False)
shrunk_res = res.results_df
# Check that the same LFC are found (up to tol)
assert (
abs(r_shrunk_res.log2FoldChange - shrunk_res.log2FoldChange)
/ abs(r_shrunk_res.log2FoldChange)
).max() < tol
def test_iterative_size_factors(counts_df, metadata, tol=0.02):
"""Test that the outputs of the iterative size factor method match those of the
original R package (starting from the same inputs), up to a tolerance in relative
error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_iterative_size_factors.csv"),
index_col=0,
).squeeze()
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors="condition")
dds._fit_iterate_size_factors()
# Check that the same LFC are found (up to tol)
assert (
abs(r_size_factors - dds.obsm["size_factors"]) / abs(r_size_factors)
).max() < tol
# Multi-factor tests
@pytest.mark.parametrize("with_outliers", [True, False])
def test_multifactor_deseq(counts_df, metadata, with_outliers, tol=0.04):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
if with_outliers:
r_res = pd.read_csv(
os.path.join(test_path, "data/multi_factor/r_test_res_outliers.csv"),
index_col=0,
)
else:
r_res = pd.read_csv(
os.path.join(test_path, "data/multi_factor/r_test_res.csv"),
index_col=0,
)
if with_outliers:
# Introduce outlier counts and a condition level with a single replicate
counts_df.loc["sample1", "gene1"] = 2000
counts_df.loc["sample11", "gene7"] = 1000
metadata.loc["sample1", "condition"] = "C"
dds = DeseqDataSet(
counts=counts_df, metadata=metadata, design_factors=["group", "condition"]
)
dds.deseq2()
res = DeseqStats(dds, contrast=["condition", "B", "A"])
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_multifactor_lfc_shrinkage(counts_df, metadata, tol=0.02):
"""Test that the outputs of the lfc_shrink function match those of the original
R package (starting from the same inputs), up to a tolerance in relative error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/multi_factor/r_test_res.csv"), index_col=0
)
r_shrunk_res = pd.read_csv(
os.path.join(test_path, "data/multi_factor/r_test_lfc_shrink_res.csv"),
index_col=0,
)
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/multi_factor/r_test_size_factors.csv"),
index_col=0,
).squeeze()
r_dispersions = pd.read_csv(
os.path.join(test_path, "data/multi_factor/r_test_dispersions.csv"), index_col=0
).squeeze()
dds = DeseqDataSet(
counts=counts_df, metadata=metadata, design_factors=["group", "condition"]
)
dds.deseq2()
dds.obsm["size_factors"] = r_size_factors.values
dds.varm["dispersions"] = r_dispersions.values
dds.varm["LFC"].iloc[:, 1] = r_res.log2FoldChange.values * np.log(2)
res = DeseqStats(dds)
res.summary()
res.SE = r_res.lfcSE * np.log(2)
res.lfc_shrink(coeff="condition_B_vs_A")
shrunk_res = res.results_df
# Check that the same LFC found (up to tol)
assert (
abs(r_shrunk_res.log2FoldChange - shrunk_res.log2FoldChange)
/ abs(r_shrunk_res.log2FoldChange)
).max() < tol
# Continuous tests
@pytest.mark.parametrize("with_outliers", [True, False])
def test_continuous_deseq(
with_outliers,
tol=0.04,
):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error, with a continuous factor.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
counts_df = pd.read_csv(
os.path.join(test_path, "data/continuous/test_counts.csv"), index_col=0
).T
metadata = pd.read_csv(
os.path.join(test_path, "data/continuous/test_metadata.csv"), index_col=0
)
# Load R results
if with_outliers:
r_res = pd.read_csv(
os.path.join(test_path, "data/continuous/r_test_res_outliers.csv"),
index_col=0,
)
else:
r_res = pd.read_csv(
os.path.join(test_path, "data/continuous/r_test_res.csv"), index_col=0
)
if with_outliers:
# Introduce outlier counts and a condition level with a single replicate
counts_df.loc["sample1", "gene1"] = 2000
counts_df.loc["sample11", "gene7"] = 1000
metadata.loc["sample1", "condition"] = "C"
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors=["group", "condition", "measurement"],
continuous_factors=["measurement"],
)
dds.deseq2()
res = DeseqStats(dds)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_continuous_lfc_shrinkage(tol=0.02):
"""Test that the outputs of the lfc_shrink function match those of the original
R package (starting from the same inputs), up to a tolerance in relative error.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/continuous/r_test_res.csv"), index_col=0
)
r_shrunk_res = pd.read_csv(
os.path.join(test_path, "data/continuous/r_test_lfc_shrink_res.csv"),
index_col=0,
)
counts_df = pd.read_csv(
os.path.join(test_path, "data/continuous/test_counts.csv"), index_col=0
).T
metadata = pd.read_csv(
os.path.join(test_path, "data/continuous/test_metadata.csv"), index_col=0
)
r_size_factors = pd.read_csv(
os.path.join(test_path, "data/continuous/r_test_size_factors.csv"),
index_col=0,
).squeeze()
r_dispersions = pd.read_csv(
os.path.join(test_path, "data/continuous/r_test_dispersions.csv"), index_col=0
).squeeze()
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors=["group", "condition", "measurement"],
continuous_factors=["measurement"],
)
dds.deseq2()
dds.obsm["size_factors"] = r_size_factors.values
dds.varm["dispersions"] = r_dispersions.values
dds.varm["LFC"].iloc[:, 1] = r_res.log2FoldChange.values * np.log(2)
res = DeseqStats(dds)
res.summary()
res.SE = r_res.lfcSE * np.log(2)
res.lfc_shrink(coeff="measurement")
shrunk_res = res.results_df
# Check that the same LFC found (up to tol)
assert (
abs(r_shrunk_res.log2FoldChange - shrunk_res.log2FoldChange)
/ abs(r_shrunk_res.log2FoldChange)
).max() < tol
def test_wide_deseq(
tol=0.02,
):
"""Test that the outputs of the DESeq2 function match those of the original R
package, up to a tolerance in relative error, on a dataset with more genes than
samples.
"""
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
counts_df = pd.read_csv(
os.path.join(test_path, "data/wide/test_counts.csv"), index_col=0
).T
metadata = pd.read_csv(
os.path.join(test_path, "data/wide/test_metadata.csv"), index_col=0
)
# Load R results
r_res = pd.read_csv(os.path.join(test_path, "data/wide/r_test_res.csv"), index_col=0)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors=["group", "condition"],
)
dds.deseq2()
res = DeseqStats(dds)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_contrast(counts_df, metadata):
"""
Check that the contrasts ['condition', 'B', 'A'] and ['condition', 'A', 'B'] give
coherent results (change of sign in LFCs and Wald stats, same (adjusted p-values).
"""
dds = DeseqDataSet(
counts=counts_df, metadata=metadata, design_factors=["group", "condition"]
)
dds.deseq2()
res_B_vs_A = DeseqStats(dds, contrast=["condition", "B", "A"])
res_A_vs_B = DeseqStats(dds, contrast=["condition", "A", "B"])
res_B_vs_A.summary()
res_A_vs_B.summary()
# Check that all values correspond, up to signs
for col in res_B_vs_A.results_df.columns:
np.testing.assert_almost_equal(
res_B_vs_A.results_df[col].abs().values,
res_A_vs_B.results_df[col].abs().values,
decimal=8,
)
# Check that the sign of LFCs and stats are inverted
np.testing.assert_almost_equal(
res_B_vs_A.results_df.log2FoldChange.values,
-res_A_vs_B.results_df.log2FoldChange.values,
decimal=8,
)
np.testing.assert_almost_equal(
res_B_vs_A.results_df.stat.values, -res_A_vs_B.results_df.stat.values, decimal=8
)
def test_anndata_init(counts_df, metadata, tol=0.02):
"""
Test initializing dds with an AnnData object that already has filled in fields,
including with the same names as those used by pydeseq2.
"""
np.random.seed(42)
# Make an anndata object
adata = ad.AnnData(X=counts_df.astype(int), obs=metadata)
# Put some dummy data in unused fields
adata.obsm["dummy_metadata"] = np.random.choice(2, adata.n_obs)
adata.varm["dummy_param"] = np.random.randn(adata.n_vars)
# Put values in the dispersions field
adata.varm["dispersions"] = np.random.randn(adata.n_vars) ** 2
# Load R data
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_res = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_test_res.csv"), index_col=0
)
# Initialize DeseqDataSet from anndata and test results
dds = DeseqDataSet(adata=adata, design_factors="condition")
dds.deseq2()
res = DeseqStats(dds)
res.summary()
res_df = res.results_df
# Check results
assert_res_almost_equal(res_df, r_res, tol)
def test_vst(counts_df, metadata, tol=0.02):
"""
Test the output of VST compared with DESeq2.
"""
# Load R data
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_vst = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_vst.csv"), index_col=0
).T
r_vst_with_design = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_vst_with_design.csv"), index_col=0
).T
# Test blind design
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors=["condition"])
dds.vst(use_design=False)
assert (np.abs(r_vst - dds.layers["vst_counts"]) / r_vst).max().max() < tol
# Test full design
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors=["condition"])
dds.vst(use_design=True)
assert (
np.abs(r_vst_with_design - dds.layers["vst_counts"]) / r_vst_with_design
).max().max() < tol
def test_mean_vst(counts_df, metadata, tol=0.02):
"""
Test the output of VST with ``fitType="mean"`` compared with DESeq2.
"""
# Load R data
test_path = str(Path(os.path.realpath(tests.__file__)).parent.resolve())
r_vst = pd.read_csv(
os.path.join(test_path, "data/single_factor/r_mean_vst.csv"), index_col=0
).T
# Test blind design
dds = DeseqDataSet(counts=counts_df, metadata=metadata, design_factors=["condition"])
dds.vst(use_design=False, fit_type="mean")
assert (np.abs(r_vst - dds.layers["vst_counts"]) / r_vst).max().max() < tol
def test_ref_level(counts_df, metadata):
"""Test that DeseqDataSet columns are created according to the passed reference
level, if any.
"""
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design_factors=["group", "condition"],
ref_level=["group", "Y"],
)
# Check that the column exists
assert "group_X_vs_Y" in dds.obsm["design_matrix"].columns
# Check that its content is correct
assert (
dds.obsm["design_matrix"]["group_X_vs_Y"]
== metadata["group"].apply(
lambda x: 1 if x == "X" else 0 if x == "Y" else np.nan
)
).all()
def test_deseq2_norm(counts_df, metadata):
"""Test that deseq2_norm() called on a pandas dataframe outputs the same results as
DeseqDataSet.fit_size_factors()
"""
# Fit size factors from DeseqDataSet
dds = DeseqDataSet(counts=counts_df, metadata=metadata)
dds.fit_size_factors()
s1 = dds.obsm["size_factors"]
# Fit size factors from counts directly
s2 = deseq2_norm(counts_df)[1]
np.testing.assert_almost_equal(
s1,
s2,
decimal=8,
)
@pytest.fixture
def train_counts(counts_df):
return counts_df[25:75]
@pytest.fixture
def test_counts(counts_df):
return counts_df[0:25]
@pytest.fixture
def train_metadata(metadata):
return metadata[25:75]
@pytest.fixture
def train_dds(train_counts, train_metadata):
return DeseqDataSet(
counts=train_counts, metadata=train_metadata, design_factors="condition"
)
def test_deseq2_norm_fit(train_counts):
# patient from 25 to 75
logmeans, filtered_genes = deseq2_norm_fit(train_counts)
# 10 genes
assert logmeans.shape == (10,)
assert filtered_genes.shape == (10,)
def test_deseq2_norm_transform(train_counts, test_counts):
# First fit with some indices
logmeans, filtered_genes = deseq2_norm_fit(train_counts)
normed_counts, size_factors = deseq2_norm_transform(
test_counts, logmeans, filtered_genes
)
assert isinstance(normed_counts, pd.DataFrame)
# 25 samples, 10 genes
assert normed_counts.shape == (25, 10)
assert size_factors.shape == (25,)
def test_vst_fit(train_dds):
# patient from 25 to 75
train_dds.vst_fit()
# the correct attributes are fit
assert "vst_trend_coeffs" in train_dds.uns
assert "normed_counts" in train_dds.layers
assert "size_factors" in train_dds.obsm
def test_vst_transform(train_dds, test_counts):
# First fit with some indices
train_dds.vst_fit()
result = train_dds.vst_transform(test_counts.to_numpy())
assert isinstance(result, np.ndarray)
# 25 samples, 10 genes
assert result.shape == (25, 10)
@pytest.mark.parametrize(
("dea_fit_type", "vst_fit_type"),
[
("mean", "parametric"),
("parametric", "mean"),
("parametric", "parametric"),
("mean", "mean"),
],
)
def test_vst_blind(train_counts, train_metadata, dea_fit_type, vst_fit_type):
"""Test vst with combinatory dea dea_fit_type and fit_type"""
train_dds = DeseqDataSet(
counts=train_counts,
metadata=train_metadata,
design_factors="condition",
fit_type=dea_fit_type,
)
train_dds.deseq2()
if dea_fit_type == "parametric":
assert "trend_coeffs" in train_dds.uns
else:
assert "mean_disp" in train_dds.uns
assert "normed_counts" in train_dds.layers
assert "size_factors" in train_dds.obsm
assert train_dds.fit_type == dea_fit_type
train_dds.vst(use_design=False, fit_type=vst_fit_type)
# Check that the dea fit type hasn't changed
assert train_dds.fit_type == dea_fit_type
def test_vst_transform_no_fit(train_counts, train_metadata, test_counts):
"""Test vst_transform without calling vst_fit()"""
train_dds = DeseqDataSet(
counts=train_counts,
metadata=train_metadata,
design_factors="condition",
fit_type="parametric",
)
with pytest.raises(RuntimeError):
train_dds.vst_transform(test_counts.to_numpy())
def assert_res_almost_equal(py_res, r_res, tol=0.02):
# check that the same p-values are NaN
assert (py_res.pvalue.isna() == r_res.pvalue.isna()).all()
assert (py_res.padj.isna() == r_res.padj.isna()).all()
# Check that the same LFC, p-values and adjusted p-values are found (up to tol)
assert (
abs(r_res.log2FoldChange - py_res.log2FoldChange) / abs(r_res.log2FoldChange)
).max() < tol
assert (abs(r_res.pvalue - py_res.pvalue) / r_res.pvalue).max() < tol
assert (abs(r_res.padj - py_res.padj) / r_res.padj).max() < tol
def test_plot_rle(train_counts, train_metadata):
"""Test that the RLE plot is generated without error."""
dds = DeseqDataSet(
counts=train_counts,
metadata=train_metadata,
design="~condition",
)
dds.plot_rle(normalize=False)
dds.plot_rle(normalize=True)