/
tests.py
2370 lines (2128 loc) · 107 KB
/
tests.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 anndata
try:
from anndata.base import Raw
except ImportError:
from anndata import Raw
import batchglm.api as glm
import dask
import logging
import numpy as np
import pandas as pd
import patsy
import scipy.sparse
from typing import Union, List, Dict, Callable, Tuple
from diffxpy import pkg_constants
from .det import DifferentialExpressionTestLRT, DifferentialExpressionTestWald, \
DifferentialExpressionTestTT, DifferentialExpressionTestRank, _DifferentialExpressionTestSingle, \
DifferentialExpressionTestVsRest, _DifferentialExpressionTestMulti, DifferentialExpressionTestByPartition
from .det_cont import DifferentialExpressionTestWaldCont, DifferentialExpressionTestLRTCont
from .det_pair import DifferentialExpressionTestZTestLazy, DifferentialExpressionTestZTest, \
DifferentialExpressionTestPairwiseStandard
from .utils import parse_gene_names, parse_sample_description, parse_size_factors, parse_grouping, \
constraint_system_from_star, preview_coef_names
def _fit(
noise_model,
data,
design_loc,
design_scale,
design_loc_names: list = None,
design_scale_names: list = None,
constraints_loc: np.ndarray = None,
constraints_scale: np.ndarray = None,
init_model=None,
init_a: Union[np.ndarray, str] = "AUTO",
init_b: Union[np.ndarray, str] = "AUTO",
gene_names=None,
size_factors=None,
batch_size: Union[None, int, Tuple[int, int]] = None,
backend: str = "numpy",
training_strategy: Union[str, List[Dict[str, object]], Callable] = "AUTO",
quick_scale: bool = None,
train_args: dict = {},
close_session=True,
dtype="float64"
):
"""
:param noise_model: str, noise model to use in model-based unit_test. Possible options:
- 'nb': default
:param design_loc: Design matrix of location model.
:param design_loc: Design matrix of scale model.
:param constraints_loc: : Constraints for location model.
Array with constraints in rows and model parameters in columns.
Each constraint contains non-zero entries for the a of parameters that
has to sum to zero. This constraint is enforced by binding one parameter
to the negative sum of the other parameters, effectively representing that
parameter as a function of the other parameters. This dependent
parameter is indicated by a -1 in this array, the independent parameters
of that constraint (which may be dependent at an earlier constraint)
are indicated by a 1.
:param constraints_scale: : Constraints for scale model.
Array with constraints in rows and model parameters in columns.
Each constraint contains non-zero entries for the a of parameters that
has to sum to zero. This constraint is enforced by binding one parameter
to the negative sum of the other parameters, effectively representing that
parameter as a function of the other parameters. This dependent
parameter is indicated by a -1 in this array, the independent parameters
of that constraint (which may be dependent at an earlier constraint)
are indicated by a 1.
:param init_model: (optional) If provided, this model will be used to initialize this Estimator.
:param init_a: (Optional) Low-level initial values for a.
Can be:
- str:
* "auto": automatically choose best initialization
* "standard": initialize intercept with observed mean
* "init_model": initialize with another model (see `ìnit_model` parameter)
* "closed_form": try to initialize with closed form
- np.ndarray: direct initialization of 'a'
:param init_b: (Optional) Low-level initial values for b
Can be:
- str:
* "auto": automatically choose best initialization
* "standard": initialize with zeros
* "init_model": initialize with another model (see `ìnit_model` parameter)
* "closed_form": try to initialize with closed form
- np.ndarray: direct initialization of 'b'
:param size_factors: 1D array of transformed library size factors for each cell in the
same order as in data
:param batch_size: Argument controlling the memory load of the fitting procedure. For backends that allow
chunking of operations, this parameter controls the size of the batch / chunk.
- If backend is "tf1" or "tf2": number of observations per batch
- If backend is "numpy": Tuple of (number of observations per chunk, number of genes per chunk)
:param backend: Which linear algebra library to chose. This impact the available noise models and optimizers /
training strategies. Available are:
- "numpy" numpy
- "tf1" tensorflow1.* >= 1.13
- "tf2" tensorflow2.*
:param training_strategy: {str} training strategy to use. Can be:
- str: will use Estimator.TrainingStrategy[training_strategy] to train
:param quick_scale: Depending on the optimizer, `scale` will be fitted faster and maybe less accurate.
Useful in scenarios where fitting the exact `scale` is not absolutely necessary.
:param train_args: Backend-specific parameter estimation (optimizer) settings. This is a dictionary, its
entries depend on the backend. These optimizer settings are set to defaults if not passed in this
dictionary.
- backend=="tf1":
- backend=="tf2":
- optimizer: str
- convergence_criteria: str
- stopping_criteria: str
- learning_rate: float
- batched_model: True
- backend=="numpy":
- nproc: int = 3: number of processes to use in steps of multiprocessing that require scipy.minimize.
Note that the number of processes in the steps only based on linear algebra functions may deviate.
:param dtype: Allows specifying the precision which should be used to fit data.
Should be "float32" for single precision or "float64" for double precision.
:param close_session: If True, will finalize the estimator. Otherwise, return the estimator itself.
"""
# Load estimator for required noise model and backend:
if backend.lower() in ["tf1"]:
if noise_model == "nb" or noise_model == "negative_binomial":
from batchglm.api.models.tf1.glm_nb import Estimator, InputDataGLM
elif noise_model == "norm" or noise_model == "normal":
from batchglm.api.models.tf1.glm_norm import Estimator, InputDataGLM
else:
raise ValueError('noise_model="%s" not recognized.' % noise_model)
if batch_size is None:
batch_size = 128
else:
if not isinstance(batch_size, int):
raise ValueError("batch_size has to be an integer if backend is tf1")
chunk_size_cells = int(1e9)
chunk_size_genes = 128
elif backend.lower() in ["tf2"]:
if noise_model == "nb" or noise_model == "negative_binomial":
from batchglm.api.models.tf2.glm_nb import Estimator, InputDataGLM
else:
raise ValueError('noise_model="%s" not recognized.' % noise_model)
if batch_size is None:
batch_size = 128
else:
if not isinstance(batch_size, int):
raise ValueError("batch_size has to be an integer if backend is tf2")
chunk_size_cells = int(1e9)
chunk_size_genes = 128
elif backend.lower() in ["numpy"]:
if isinstance(training_strategy, str):
if training_strategy.lower() == "auto":
training_strategy = "DEFAULT"
if noise_model == "nb" or noise_model == "negative_binomial":
from batchglm.api.models.numpy.glm_nb import Estimator, InputDataGLM
else:
raise ValueError('noise_model="%s" not recognized.' % noise_model)
# Set default chunk size:
if batch_size is None:
chunk_size_cells = int(1e9)
chunk_size_genes = 128
batch_size = (chunk_size_cells, chunk_size_genes)
else:
if isinstance(batch_size, int) or len(batch_size) != 2:
raise ValueError("batch_size has to be a tuple of length 2 if backend is numpy")
chunk_size_cells = batch_size[0]
chunk_size_genes = batch_size[1]
else:
raise ValueError('backend="%s" not recognized.' % backend)
input_data = InputDataGLM(
data=data,
design_loc=design_loc,
design_scale=design_scale,
design_loc_names=design_loc_names,
design_scale_names=design_scale_names,
constraints_loc=constraints_loc,
constraints_scale=constraints_scale,
size_factors=size_factors,
feature_names=gene_names,
chunk_size_cells=chunk_size_cells,
chunk_size_genes=chunk_size_genes,
as_dask=backend.lower() in ["numpy"],
cast_dtype=dtype
)
# Assemble variable key word arguments to constructor of Estimator.
constructor_args = {}
if quick_scale is not None:
constructor_args["quick_scale"] = quick_scale
# Backend-specific constructor arguments:
if backend.lower() in ["tf1"]:
constructor_args['provide_optimizers'] = {
"gd": pkg_constants.BATCHGLM_OPTIM_GD,
"adam": pkg_constants.BATCHGLM_OPTIM_ADAM,
"adagrad": pkg_constants.BATCHGLM_OPTIM_ADAGRAD,
"rmsprop": pkg_constants.BATCHGLM_OPTIM_RMSPROP,
"nr": pkg_constants.BATCHGLM_OPTIM_NEWTON,
"nr_tr": pkg_constants.BATCHGLM_OPTIM_NEWTON_TR,
"irls": pkg_constants.BATCHGLM_OPTIM_IRLS,
"irls_gd": pkg_constants.BATCHGLM_OPTIM_IRLS_GD,
"irls_tr": pkg_constants.BATCHGLM_OPTIM_IRLS_TR,
"irls_gd_tr": pkg_constants.BATCHGLM_OPTIM_IRLS_GD_TR
}
constructor_args['provide_batched'] = pkg_constants.BATCHGLM_PROVIDE_BATCHED
constructor_args['provide_fim'] = pkg_constants.BATCHGLM_PROVIDE_FIM
constructor_args['provide_hessian'] = pkg_constants.BATCHGLM_PROVIDE_HESSIAN
constructor_args["batch_size"] = batch_size
elif backend.lower() not in ["tf2"]:
pass
elif backend.lower() not in ["numpy"]:
pass
else:
raise ValueError('backend="%s" not recognized.' % backend)
estim = Estimator(
input_data=input_data,
init_a=init_a,
init_b=init_b,
dtype=dtype,
**constructor_args
)
estim.initialize()
# Assemble backend specific key word arguments to training function:
if batch_size is not None:
train_args["batch_size"] = batch_size
if backend.lower() in ["tf1"]:
pass
elif backend.lower() in ["tf2"]:
train_args["autograd"] = pkg_constants.BATCHGLM_AUTOGRAD
train_args["featurewise"] = pkg_constants.BATCHGLM_FEATUREWISE
elif backend.lower() in ["numpy"]:
pass
estim.train_sequence(
training_strategy=training_strategy,
**train_args
)
if close_session:
estim.finalize()
return estim
def lrt(
data: Union[anndata.AnnData, Raw, np.ndarray, scipy.sparse.csr_matrix, glm.typing.InputDataBase],
full_formula_loc: str,
reduced_formula_loc: str,
full_formula_scale: str = "~1",
reduced_formula_scale: str = "~1",
as_numeric: Union[List[str], Tuple[str], str] = (),
init_a: Union[np.ndarray, str] = "AUTO",
init_b: Union[np.ndarray, str] = "AUTO",
gene_names: Union[np.ndarray, list] = None,
sample_description: pd.DataFrame = None,
noise_model="nb",
size_factors: Union[np.ndarray, pd.core.series.Series, np.ndarray] = None,
batch_size: Union[None, int, Tuple[int, int]] = None,
backend: str = "numpy",
train_args: dict = {},
training_strategy: Union[str, List[Dict[str, object]], Callable] = "AUTO",
quick_scale: bool = False,
dtype="float64",
**kwargs
):
"""
Perform log-likelihood ratio test for differential expression for each gene.
Note that lrt() does not support constraints in its current form. Please
use wald() for constraints.
:param data: Input data matrix (observations x features) or (cells x genes).
:param full_formula_loc: formula
Full model formula for location parameter model.
:param reduced_formula_loc: formula
Reduced model formula for location and scale parameter models.
:param full_formula_scale: formula
Full model formula for scale parameter model.
:param reduced_formula_scale: formula
Reduced model formula for scale parameter model.
:param as_numeric:
Which columns of sample_description to treat as numeric and
not as categorical. This yields columns in the design matrix
which do not correpond to one-hot encoded discrete factors.
This makes sense for number of genes, time, pseudotime or space
for example.
:param init_a: (Optional) Low-level initial values for a.
Can be:
- str:
* "auto": automatically choose best initialization
* "standard": initialize intercept with observed mean
* "init_model": initialize with another model (see `ìnit_model` parameter)
* "closed_form": try to initialize with closed form
- np.ndarray: direct initialization of 'a'
:param init_b: (Optional) Low-level initial values for b
Can be:
- str:
* "auto": automatically choose best initialization
* "standard": initialize with zeros
* "init_model": initialize with another model (see `ìnit_model` parameter)
* "closed_form": try to initialize with closed form
- np.ndarray: direct initialization of 'b'
:param gene_names: optional list/array of gene names which will be used if `data` does not implicitly store these
:param sample_description: optional pandas.DataFrame containing sample annotations
:param noise_model: str, noise model to use in model-based unit_test. Possible options:
- 'nb': default
:param size_factors: 1D array of transformed library size factors for each cell in the
same order as in data or string-type column identifier of size-factor containing
column in sample description.
:param batch_size: Argument controlling the memory load of the fitting procedure. For backends that allow
chunking of operations, this parameter controls the size of the batch / chunk.
- If backend is "tf1" or "tf2": number of observations per batch
- If backend is "numpy": Tuple of (number of observations per chunk, number of genes per chunk)
:param backend: Which linear algebra library to chose. This impact the available noise models and optimizers /
training strategies. Available are:
- "numpy" numpy
- "tf1" tensorflow1.* >= 1.13
- "tf2" tensorflow2.*
:param training_strategy: {str, function, list} training strategy to use. Can be:
- str: will use Estimator.TrainingStrategy[training_strategy] to train
- function: Can be used to implement custom training function will be called as
`training_strategy(estimator)`.
- list of keyword dicts containing method arguments: Will call Estimator.train() once with each dict of
method arguments.
Example:
.. code-block:: python
[
{"learning_rate": 0.5, },
{"learning_rate": 0.05, },
]
This will run training first with learning rate = 0.5 and then with learning rate = 0.05.
:param quick_scale: Depending on the optimizer, `scale` will be fitted faster and maybe less accurate.
Useful in scenarios where fitting the exact `scale` is not absolutely necessary.
:param dtype: Allows specifying the precision which should be used to fit data.
Should be "float32" for single precision or "float64" for double precision.
:param kwargs: [Debugging] Additional arguments will be passed to the _fit method.
"""
# TODO test nestedness
if len(kwargs) != 0:
logging.getLogger("diffxpy").info("additional kwargs: %s", str(kwargs))
if isinstance(as_numeric, str):
as_numeric = [as_numeric]
gene_names = parse_gene_names(data, gene_names)
sample_description = parse_sample_description(data, sample_description)
size_factors = parse_size_factors(
size_factors=size_factors,
data=data,
sample_description=sample_description
)
full_design_loc = glm.data.design_matrix(
sample_description=sample_description,
formula=full_formula_loc,
as_categorical=[False if x in as_numeric else True for x in sample_description.columns.values],
return_type="patsy"
)
reduced_design_loc = glm.data.design_matrix(
sample_description=sample_description,
formula=reduced_formula_loc,
as_categorical=[False if x in as_numeric else True for x in sample_description.columns.values],
return_type="patsy"
)
full_design_scale = glm.data.design_matrix(
sample_description=sample_description,
formula=full_formula_scale,
as_categorical=[False if x in as_numeric else True for x in sample_description.columns.values],
return_type="patsy"
)
reduced_design_scale = glm.data.design_matrix(
sample_description=sample_description,
formula=reduced_formula_scale,
as_categorical=[False if x in as_numeric else True for x in sample_description.columns.values],
return_type="patsy"
)
reduced_model = _fit(
noise_model=noise_model,
data=data,
design_loc=reduced_design_loc,
design_scale=reduced_design_scale,
constraints_loc=None,
constraints_scale=None,
init_a=init_a,
init_b=init_b,
gene_names=gene_names,
size_factors=size_factors,
batch_size=batch_size,
backend=backend,
train_args=train_args,
training_strategy=training_strategy,
quick_scale=quick_scale,
dtype=dtype,
**kwargs
)
full_model = _fit(
noise_model=noise_model,
data=data,
design_loc=full_design_loc,
design_scale=full_design_scale,
constraints_loc=None,
constraints_scale=None,
gene_names=gene_names,
init_a="init_model",
init_b="init_model",
init_model=reduced_model,
size_factors=size_factors,
batch_size=batch_size,
backend=backend,
train_args=train_args,
training_strategy=training_strategy,
quick_scale=quick_scale,
dtype=dtype,
**kwargs
)
de_test = DifferentialExpressionTestLRT(
sample_description=sample_description,
full_design_loc_info=full_design_loc.design_info,
full_estim=full_model,
reduced_design_loc_info=reduced_design_loc.design_info,
reduced_estim=reduced_model,
)
return de_test
def wald(
data: Union[anndata.AnnData, Raw, np.ndarray, scipy.sparse.csr_matrix, glm.typing.InputDataBase],
factor_loc_totest: Union[str, List[str]] = None,
coef_to_test: Union[str, List[str]] = None,
formula_loc: Union[None, str] = None,
formula_scale: Union[None, str] = "~1",
as_numeric: Union[List[str], Tuple[str], str] = (),
init_a: Union[np.ndarray, str] = "AUTO",
init_b: Union[np.ndarray, str] = "AUTO",
gene_names: Union[np.ndarray, list] = None,
sample_description: Union[None, pd.DataFrame] = None,
dmat_loc: Union[patsy.design_info.DesignMatrix] = None,
dmat_scale: Union[patsy.design_info.DesignMatrix] = None,
constraints_loc: Union[None, List[str], Tuple[str, str], dict, np.ndarray] = None,
constraints_scale: Union[None, List[str], Tuple[str, str], dict, np.ndarray] = None,
noise_model: str = "nb",
size_factors: Union[np.ndarray, pd.core.series.Series, str] = None,
batch_size: Union[None, int, Tuple[int, int]] = None,
backend: str = "numpy",
train_args: dict = {},
training_strategy: Union[str, List[Dict[str, object]], Callable] = "AUTO",
quick_scale: bool = False,
dtype="float64",
**kwargs
):
"""
Perform Wald test for differential expression for each gene.
:param data: Input data matrix (observations x features) or (cells x genes).
:param factor_loc_totest: str, list of strings
List of factors of formula to test with Wald test.
E.g. "condition" or ["batch", "condition"] if formula_loc would be "~ 1 + batch + condition"
:param coef_to_test:
If there are more than two groups specified by `factor_loc_totest`,
this parameter allows to specify the group which should be tested.
Alternatively, if factor_loc_totest is not given, this list sets
the exact coefficients which are to be tested.
:param formula_loc: formula
model formula for location and scale parameter models.
:param formula_scale: formula
model formula for scale parameter model.
:param as_numeric:
Which columns of sample_description to treat as numeric and
not as categorical. This yields columns in the design matrix
which do not correspond to one-hot encoded discrete factors.
This makes sense for number of genes, time, pseudotime or space
for example.
:param init_a: (Optional) Low-level initial values for a.
Can be:
- str:
* "auto": automatically choose best initialization
* "standard": initialize intercept with observed mean
* "closed_form": try to initialize with closed form
- np.ndarray: direct initialization of 'a'
:param init_b: (Optional) Low-level initial values for b
Can be:
- str:
* "auto": automatically choose best initialization
* "standard": initialize with zeros
* "closed_form": try to initialize with closed form
- np.ndarray: direct initialization of 'b'
:param gene_names: optional list/array of gene names which will be used if `data` does not implicitly store these
:param sample_description: optional pandas.DataFrame containing sample annotations
:param dmat_loc: Pre-built location model design matrix.
This over-rides formula_loc and sample description information given in
data or sample_description.
:param dmat_scale: Pre-built scale model design matrix.
This over-rides formula_scale and sample description information given in
data or sample_description.
:param constraints_loc: Constraints for location model. Can be one of the following:
- np.ndarray:
Array with constraints in rows and model parameters in columns.
Each constraint contains non-zero entries for the a of parameters that
has to sum to zero. This constraint is enforced by binding one parameter
to the negative sum of the other parameters, effectively representing that
parameter as a function of the other parameters. This dependent
parameter is indicated by a -1 in this array, the independent parameters
of that constraint (which may be dependent at an earlier constraint)
are indicated by a 1. You should only use this option
together with prebuilt design matrix for the location model, dmat_loc,
for example via de.utils.setup_constrained().
- dict:
Every element of the dictionary corresponds to one set of equality constraints.
Each set has to be be an entry of the form {..., x: y, ...}
where x is the factor to be constrained and y is a factor by which levels of x are grouped
and then constrained. Set y="1" to constrain all levels of x to sum to one,
a single equality constraint.
E.g.: {"batch": "condition"} Batch levels within each condition are constrained to sum to
zero. This is applicable if repeats of a an experiment within each condition
are independent so that the set-up ~1+condition+batch is perfectly confounded.
Can only group by non-constrained effects right now, use constraint_matrix_from_string
for other cases.
- list of strings or tuple of strings:
String encoded equality constraints.
E.g. ["batch1 + batch2 + batch3 = 0"]
- None:
No constraints are used, this is equivalent to using an identity matrix as a
constraint matrix.
:param constraints_scale: Constraints for scale model. Can be one of the following:
- np.ndarray:
Array with constraints in rows and model parameters in columns.
Each constraint contains non-zero entries for the a of parameters that
has to sum to zero. This constraint is enforced by binding one parameter
to the negative sum of the other parameters, effectively representing that
parameter as a function of the other parameters. This dependent
parameter is indicated by a -1 in this array, the independent parameters
of that constraint (which may be dependent at an earlier constraint)
are indicated by a 1. You should only use this option
together with prebuilt design matrix for the scale model, dmat_scale,
for example via de.utils.setup_constrained().
- dict:
Every element of the dictionary corresponds to one set of equality constraints.
Each set has to be be an entry of the form {..., x: y, ...}
where x is the factor to be constrained and y is a factor by which levels of x are grouped
and then constrained. Set y="1" to constrain all levels of x to sum to one,
a single equality constraint.
E.g.: {"batch": "condition"} Batch levels within each condition are constrained to sum to
zero. This is applicable if repeats of a an experiment within each condition
are independent so that the set-up ~1+condition+batch is perfectly confounded.
Can only group by non-constrained effects right now, use constraint_matrix_from_string
for other cases.
- list of strings or tuple of strings:
String encoded equality constraints.
E.g. ["batch1 + batch2 + batch3 = 0"]
- None:
No constraints are used, this is equivalent to using an identity matrix as a
constraint matrix.
:param size_factors: 1D array of transformed library size factors for each cell in the
same order as in data or string-type column identifier of size-factor containing
column in sample description.
:param noise_model: str, noise model to use in model-based unit_test. Possible options:
- 'nb': default
:param batch_size: Argument controlling the memory load of the fitting procedure. For backends that allow
chunking of operations, this parameter controls the size of the batch / chunk.
- If backend is "tf1" or "tf2": number of observations per batch
- If backend is "numpy": Tuple of (number of observations per chunk, number of genes per chunk)
:param backend: Which linear algebra library to chose. This impact the available noise models and optimizers /
training strategies. Available are:
- "numpy" numpy
- "tf1" tensorflow1.* >= 1.13
- "tf2" tensorflow2.*
:param training_strategy: {str, function, list} training strategy to use. Can be:
- str: will use Estimator.TrainingStrategy[training_strategy] to train
- function: Can be used to implement custom training function will be called as
`training_strategy(estimator)`.
- list of keyword dicts containing method arguments: Will call Estimator.train() once with each dict of
method arguments.
:param quick_scale: Depending on the optimizer, `scale` will be fitted faster and maybe less accurate.
Useful in scenarios where fitting the exact `scale` is not absolutely necessary.
:param dtype: Allows specifying the precision which should be used to fit data.
Should be "float32" for single precision or "float64" for double precision.
:param kwargs: [Debugging] Additional arguments will be passed to the _fit method.
"""
if len(kwargs) != 0:
logging.getLogger("diffxpy").debug("additional kwargs: %s", str(kwargs))
if (dmat_loc is None and formula_loc is None) or \
(dmat_loc is not None and formula_loc is not None):
raise ValueError("Supply either dmat_loc or formula_loc.")
if (dmat_scale is None and formula_scale is None) or \
(dmat_scale is not None and formula_scale != "~1"):
raise ValueError("Supply either dmat_scale or formula_scale.")
if dmat_loc is not None and factor_loc_totest is not None:
raise ValueError("Supply coef_to_test and not factor_loc_totest if dmat_loc is supplied.")
# Check that factor_loc_totest and coef_to_test are lists and not single strings:
if isinstance(factor_loc_totest, str):
factor_loc_totest = [factor_loc_totest]
if isinstance(coef_to_test, str):
coef_to_test = [coef_to_test]
if isinstance(as_numeric, str):
as_numeric = [as_numeric]
# Parse input data formats:
gene_names = parse_gene_names(data, gene_names)
if dmat_loc is None and dmat_scale is None:
sample_description = parse_sample_description(data, sample_description)
size_factors = parse_size_factors(
size_factors=size_factors,
data=data,
sample_description=sample_description
)
# Build design matrices and constraints.
design_loc, design_loc_names, constraints_loc, term_names_loc = constraint_system_from_star(
dmat=dmat_loc,
sample_description=sample_description,
formula=formula_loc,
as_numeric=as_numeric,
constraints=constraints_loc,
return_type="patsy"
)
design_scale, design_scale_names, constraints_scale, term_names_scale = constraint_system_from_star(
dmat=dmat_scale,
sample_description=sample_description,
formula=formula_scale,
as_numeric=as_numeric,
constraints=constraints_scale,
return_type="patsy"
)
# Define indices of coefficients to test:
constraints_loc_temp = constraints_loc if constraints_loc is not None else np.eye(design_loc.shape[-1])
# Check that design_loc is patsy, otherwise use term_names for slicing.
if factor_loc_totest is not None:
if not isinstance(design_loc, patsy.design_info.DesignMatrix):
col_indices = np.where([
x in factor_loc_totest
for x in term_names_loc
])[0]
else:
# Select coefficients to test via formula model:
col_indices = np.concatenate([
np.arange(design_loc.shape[-1])[design_loc.design_info.slice(x)]
for x in factor_loc_totest
])
assert len(col_indices) > 0, "Could not find any matching columns!"
if coef_to_test is not None:
if len(factor_loc_totest) > 1:
raise ValueError("do not set coef_to_test if more than one factor_loc_totest is given")
samples = sample_description[factor_loc_totest].astype(type(coef_to_test)) == coef_to_test
one_cols = np.where(design_loc[samples][:, col_indices][0] == 1)
if one_cols.size == 0:
# there is no such column; modify design matrix to create one
design_loc[:, col_indices] = np.where(samples, 1, 0)
elif coef_to_test is not None:
# Directly select coefficients to test from design matrix:
if sample_description is not None:
coef_loc_names = preview_coef_names(
sample_description=sample_description,
formula=formula_loc,
as_numeric=as_numeric
)
else:
coef_loc_names = dmat_loc.columns.tolist()
if not np.all([x in coef_loc_names for x in coef_to_test]):
raise ValueError(
"the requested test coefficients %s were found in model coefficients %s" %
(", ".join([x for x in coef_to_test if x not in coef_loc_names]),
", ".join(coef_loc_names))
)
col_indices = np.asarray([
coef_loc_names.index(x) for x in coef_to_test
])
else:
raise ValueError("either set factor_loc_totest or coef_to_test")
# Check that all tested coefficients are independent:
for x in col_indices:
if np.sum(constraints_loc_temp[x, :]) != 1:
raise ValueError("Constraints input is wrong: not all tested coefficients are unconstrained.")
# Adjust tested coefficients from dependent to independent (fitted) parameters:
col_indices = np.array([np.where(constraints_loc_temp[x, :] == 1)[0][0] for x in col_indices])
# Fit model.
model = _fit(
noise_model=noise_model,
data=data,
design_loc=design_loc,
design_scale=design_scale,
design_loc_names=design_loc_names,
design_scale_names=design_scale_names,
constraints_loc=constraints_loc,
constraints_scale=constraints_scale,
init_a=init_a,
init_b=init_b,
gene_names=gene_names,
size_factors=size_factors,
batch_size=batch_size,
backend=backend,
train_args=train_args,
training_strategy=training_strategy,
quick_scale=quick_scale,
dtype=dtype,
**kwargs,
)
# Prepare differential expression test.
de_test = DifferentialExpressionTestWald(
model_estim=model,
col_indices=col_indices,
noise_model=noise_model,
sample_description=sample_description
)
return de_test
def wald_repeated(
det: DifferentialExpressionTestWald,
factor_loc_totest: Union[str, List[str]] = None,
coef_to_test: Union[str, List[str]] = None,
**kwargs
):
"""
Run another wald test on a DifferentialExpressionTestWald object that already contains a model fit.
This allows you to assess signficance of another parameter set without refitting the model.
:param factor_loc_totest: str, list of strings
List of factors of formula to test with Wald test.
E.g. "condition" or ["batch", "condition"] if formula_loc would be "~ 1 + batch + condition"
:param coef_to_test:
If there are more than two groups specified by `factor_loc_totest`,
this parameter allows to specify the group which should be tested.
Alternatively, if factor_loc_totest is not given, this list sets
the exact coefficients which are to be tested.
"""
if len(kwargs) != 0:
logging.getLogger("diffxpy").debug("additional kwargs: %s", str(kwargs))
# Check that factor_loc_totest and coef_to_test are lists and not single strings:
if isinstance(factor_loc_totest, str):
factor_loc_totest = [factor_loc_totest]
if isinstance(coef_to_test, str):
coef_to_test = [coef_to_test]
# Check that design_loc is patsy, otherwise use term_names for slicing.
par_loc_names = det.model_estim.model.design_loc_names
if factor_loc_totest is not None and coef_to_test is None:
col_indices = np.concatenate([np.where([
fac in x
for x in par_loc_names
])[0] for fac in factor_loc_totest])
elif factor_loc_totest is None and coef_to_test is not None:
if not np.all([x in par_loc_names for x in coef_to_test]):
raise ValueError(
"the requested test coefficients %s were found in model coefficients %s" %
(", ".join([x for x in coef_to_test if x not in par_loc_names]),
", ".join(par_loc_names))
)
col_indices = np.asarray([
par_loc_names.index(x) for x in coef_to_test
])
elif factor_loc_totest is None and coef_to_test is None:
raise ValueError("Do not supply factor_loc_totest and coef_to_test in wald_repeated, run a new wald test.")
else:
raise ValueError("Either set factor_loc_totest or coef_to_test.")
assert len(col_indices) > 0, "Could not find any matching columns!"
# Check that all tested coefficients are independent:
constraints_loc = det.model_estim.model.constraints_loc
if isinstance(constraints_loc, dask.array.core.Array):
constraints_loc = constraints_loc.compute()
for x in col_indices:
if np.sum(constraints_loc[x, :]) != 1:
raise ValueError("Constraints input is wrong: not all tested coefficients are unconstrained.")
# Adjust tested coefficients from dependent to independent (fitted) parameters:
col_indices = np.array([
np.where(constraints_loc[x, :] == 1)[0][0]
for x in col_indices
])
# Prepare differential expression test.
de_test = DifferentialExpressionTestWald(
model_estim=det.model_estim,
col_indices=col_indices,
noise_model=det.noise_model,
sample_description=det.sample_description
)
return de_test
def t_test(
data: Union[anndata.AnnData, Raw, np.ndarray, scipy.sparse.csr_matrix, glm.typing.InputDataBase],
grouping,
gene_names: Union[np.ndarray, list] = None,
sample_description: pd.DataFrame = None,
is_logged: bool = False,
is_sig_zerovar: bool = True
):
"""
Perform Welch's t-test for differential expression
between two groups on adata object for each gene.
:param data: Array-like, or anndata.Anndata object containing observations.
Input data matrix (observations x features) or (cells x genes).
:param grouping: str, array
- column in data.obs/sample_description which contains the split of observations into the two groups.
- array of length `num_observations` containing group labels
:param gene_names: optional list/array of gene names which will be used if `data` does not implicitly store these
:param sample_description: optional pandas.DataFrame containing sample annotations
:param is_logged:
Whether data is already logged. If True, log-fold changes are computed as fold changes on this data.
If False, log-fold changes are computed as log-fold changes on this data.
:param is_sig_zerovar:
Whether to assign p-value of 0 to a gene which has zero variance in both groups but not the same mean. If False,
the p-value is set to np.nan.
"""
gene_names = parse_gene_names(data, gene_names)
grouping = parse_grouping(data, sample_description, grouping)
de_test = DifferentialExpressionTestTT(
data=data,
sample_description=sample_description,
grouping=grouping,
gene_names=gene_names,
is_logged=is_logged,
is_sig_zerovar=is_sig_zerovar
)
return de_test
def rank_test(
data: Union[anndata.AnnData, Raw, np.ndarray, scipy.sparse.csr_matrix, glm.typing.InputDataBase],
grouping: Union[str, np.ndarray, list],
gene_names: Union[np.ndarray, list] = None,
sample_description: pd.DataFrame = None,
is_logged: bool = False,
is_sig_zerovar: bool = True
):
"""
Perform Mann-Whitney rank test (Wilcoxon rank-sum test) for differential expression
between two groups on adata object for each gene.
:param data: Array-like, or anndata.Anndata object containing observations.
Input data matrix (observations x features) or (cells x genes).
:param grouping: str, array
- column in data.obs/sample_description which contains the split of observations into the two groups.
- array of length `num_observations` containing group labels
:param gene_names: optional list/array of gene names which will be used if `data` does not implicitly store these
:param sample_description: optional pandas.DataFrame containing sample annotations
:param is_logged:
Whether data is already logged. If True, log-fold changes are computed as fold changes on this data.
If False, log-fold changes are computed as log-fold changes on this data.
:param is_sig_zerovar:
Whether to assign p-value of 0 to a gene which has zero variance in both groups but not the same mean. If False,
the p-value is set to np.nan.
"""
gene_names = parse_gene_names(data, gene_names)
grouping = parse_grouping(data, sample_description, grouping)
de_test = DifferentialExpressionTestRank(
data=data,
sample_description=sample_description,
grouping=grouping,
gene_names=gene_names,
is_logged=is_logged,
is_sig_zerovar=is_sig_zerovar
)
return de_test
def two_sample(
data: Union[anndata.AnnData, Raw, np.ndarray, scipy.sparse.csr_matrix, glm.typing.InputDataBase],
grouping: Union[str, np.ndarray, list],
as_numeric: Union[List[str], Tuple[str], str] = (),
test: str = "t-test",
gene_names: Union[np.ndarray, list] = None,
sample_description: pd.DataFrame = None,
noise_model: str = None,
size_factors: np.ndarray = None,
batch_size: Union[None, int, Tuple[int, int]] = None,
backend: str = "numpy",
train_args: dict = {},
training_strategy: Union[str, List[Dict[str, object]], Callable] = "AUTO",
is_sig_zerovar: bool = True,
quick_scale: bool = None,
dtype="float64",
**kwargs
) -> _DifferentialExpressionTestSingle:
r"""
Perform differential expression test between two groups on adata object
for each gene.
This function wraps the selected statistical test for the scenario of
a two sample comparison. All unit_test offered in this wrapper
test for the difference of the mean parameter of both samples.
The exact unit_test are as follows (assuming the group labels
are saved in a column named "group"):
- "lrt" - (log-likelihood ratio test):
Requires the fitting of 2 generalized linear models (full and reduced).
The models are automatically assembled as follows, use the de.test.lrt()
function if you would like to perform a different test.
* full model location parameter: ~ 1 + group
* full model scale parameter: ~ 1 + group
* reduced model location parameter: ~ 1
* reduced model scale parameter: ~ 1 + group
- "wald" - Wald test:
Requires the fitting of 1 generalized linear models.
model location parameter: ~ 1 + group
model scale parameter: ~ 1 + group
Test the group coefficient of the location parameter model against 0.
- "t-test" - Welch's t-test:
Doesn't require fitting of generalized linear models.
Welch's t-test between both observation groups.
- "rank" - Wilcoxon rank sum (Mann-Whitney U) test:
Doesn't require fitting of generalized linear models.
Wilcoxon rank sum (Mann-Whitney U) test between both observation groups.
:param data: Array-like, or anndata.Anndata object containing observations.
Input data matrix (observations x features) or (cells x genes).
:param grouping: str, array
- column in data.obs/sample_description which contains the split of observations into the two groups.
- array of length `num_observations` containing group labels
:param as_numeric:
Which columns of sample_description to treat as numeric and
not as categorical. This yields columns in the design matrix
which do not correpond to one-hot encoded discrete factors.
This makes sense for number of genes, time, pseudotime or space
for example.
:param test: str, statistical test to use. Possible options:
- 'wald': default
- 'lrt'
- 't-test'
- 'rank'
:param gene_names: optional list/array of gene names which will be used if `data` does not implicitly store these
:param sample_description: optional pandas.DataFrame containing sample annotations
:param size_factors: 1D array of transformed library size factors for each cell in the
same order as in data
:param noise_model: str, noise model to use in model-based unit_test. Possible options:
- 'nb': default
:param batch_size: Argument controlling the memory load of the fitting procedure. For backends that allow
chunking of operations, this parameter controls the size of the batch / chunk.
- If backend is "tf1" or "tf2": number of observations per batch
- If backend is "numpy": Tuple of (number of observations per chunk, number of genes per chunk)
:param backend: Which linear algebra library to chose. This impact the available noise models and optimizers /
training strategies. Available are:
- "numpy" numpy
- "tf1" tensorflow1.* >= 1.13
- "tf2" tensorflow2.*
:param training_strategy: {str, function, list} training strategy to use. Can be:
- str: will use Estimator.TrainingStrategy[training_strategy] to train
- function: Can be used to implement custom training function will be called as
`training_strategy(estimator)`.
- list of keyword dicts containing method arguments: Will call Estimator.train() once with each dict of
method arguments.
:param is_sig_zerovar: