deepbatch 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deepbatch-0.2.0/MANIFEST.in +2 -0
- deepbatch-0.2.0/PKG-INFO +110 -0
- deepbatch-0.2.0/README.md +97 -0
- deepbatch-0.2.0/examples/adaptive_detection.py +34 -0
- deepbatch-0.2.0/examples/adaptive_detection_results.csv +10 -0
- deepbatch-0.2.0/examples/batch_magnitude.py +103 -0
- deepbatch-0.2.0/examples/batch_magnitude_results.csv +66 -0
- deepbatch-0.2.0/examples/benchmark.py +39 -0
- deepbatch-0.2.0/examples/detection_results.csv +5 -0
- deepbatch-0.2.0/examples/evaluation_results.csv +41 -0
- deepbatch-0.2.0/examples/evaluation_suite.py +125 -0
- deepbatch-0.2.0/pyproject.toml +21 -0
- deepbatch-0.2.0/setup.cfg +4 -0
- deepbatch-0.2.0/src/deepbatch/__init__.py +13 -0
- deepbatch-0.2.0/src/deepbatch/assays.py +98 -0
- deepbatch-0.2.0/src/deepbatch/evaluate.R +40 -0
- deepbatch-0.2.0/src/deepbatch/evaluation.py +197 -0
- deepbatch-0.2.0/src/deepbatch/model.py +190 -0
- deepbatch-0.2.0/src/deepbatch/upstream.py +88 -0
- deepbatch-0.2.0/src/deepbatch.egg-info/PKG-INFO +110 -0
- deepbatch-0.2.0/src/deepbatch.egg-info/SOURCES.txt +25 -0
- deepbatch-0.2.0/src/deepbatch.egg-info/dependency_links.txt +1 -0
- deepbatch-0.2.0/src/deepbatch.egg-info/requires.txt +7 -0
- deepbatch-0.2.0/src/deepbatch.egg-info/top_level.txt +1 -0
- deepbatch-0.2.0/tests/test_deepbatch.py +68 -0
- deepbatch-0.2.0/tests/test_evaluation.py +102 -0
- deepbatch-0.2.0/tests/test_magnitude.py +66 -0
deepbatch-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deepbatch
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Measure batch effects and their impact on biological contrasts across molecular assays
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: numpy>=1.24
|
|
8
|
+
Requires-Dist: pandas>=2.0
|
|
9
|
+
Requires-Dist: scipy>=1.10
|
|
10
|
+
Provides-Extra: singlecell
|
|
11
|
+
Requires-Dist: scib-metrics<0.7,>=0.6.2; extra == "singlecell"
|
|
12
|
+
Requires-Dist: umap-learn==0.5.9.post2; extra == "singlecell"
|
|
13
|
+
|
|
14
|
+
# DeepBatch
|
|
15
|
+
|
|
16
|
+
DeepBatch 0.2.0 measures batch effects across molecular assays and corrects additive shifts. Rows are samples and columns are features. The core model fits independent observations on a continuous analysis scale.
|
|
17
|
+
|
|
18
|
+
## Install locally
|
|
19
|
+
|
|
20
|
+
From this directory, run `python -m pip install .`. Python 3.10+ is required.
|
|
21
|
+
|
|
22
|
+
## Measure, correct, and estimate contrast distortion
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import numpy as np
|
|
26
|
+
import pandas as pd
|
|
27
|
+
from deepbatch import fit_batch
|
|
28
|
+
|
|
29
|
+
rng = np.random.default_rng(42)
|
|
30
|
+
samples = pd.Index([f"s{i}" for i in range(12)])
|
|
31
|
+
group = pd.Series(["control"] * 6 + ["case"] * 6, index=samples, name="group")
|
|
32
|
+
batch = pd.Series(list("AAAABB") + list("AABBBB"), index=samples)
|
|
33
|
+
data = pd.DataFrame(rng.normal(size=(12, 3)), index=samples, columns=["f1", "f2", "f3"])
|
|
34
|
+
data["f1"] += 0.8 * batch.eq("B") + 0.5 * group.eq("case")
|
|
35
|
+
|
|
36
|
+
fit = fit_batch(data, batch, protected=group.to_frame())
|
|
37
|
+
print(fit.global_scores)
|
|
38
|
+
print(fit.features.partial_r2.describe())
|
|
39
|
+
print(fit.features.join(fit.batch_contrast("B", "A")).sort_values("partial_r2", ascending=False))
|
|
40
|
+
print(fit.contrast_distortion(group, case="case", control="control"))
|
|
41
|
+
adjusted = fit.correct(data, batch)
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The model includes an intercept, protected covariates, and fixed batch effects. Encode categorical covariates as strings or pandas categories. Numeric covariates enter as continuous predictors. Metadata aligns by sample ID. A rank-deficient design raises an error. The condition number and residual degrees of freedom are available on the fit. Use numeric covariate scales appropriate for interpreting the condition number.
|
|
45
|
+
|
|
46
|
+
- `batch_share_total` divides the additional sum of squares for batch by the total centered sum of squares across features. `batch_share_remaining` uses the residual sum of squares after protecting biology as its denominator. Feature scaling affects both global scores.
|
|
47
|
+
- `partial_r2` and its degrees-of-freedom-adjusted counterpart describe individual features. Undefined fractions are NaN. Adjusted estimates can be negative.
|
|
48
|
+
- `adjusted_batch_share_remaining` compares the pooled residual mean squares of the full and protected models. Negative values are retained. All three global scores pool sums of squares across the supplied features. Features with more variation carry more weight. For equal scale across features, standardize explicitly before fitting and interpret contrasts on that standardized scale.
|
|
49
|
+
- `batch_contrast("B", "A")` returns the adjusted B-minus-A difference, standard error and pointwise t interval for each feature. On log2 intensities, an estimate of 1 represents a twofold difference. The model assumes an additive common shift across biological groups. Intervals assume independent samples and approximately Gaussian, equal-variance residuals within each feature. In study samples, a difference conditional on measured biology can still reflect unmeasured biology.
|
|
50
|
+
- `correct` subtracts fitted batch shifts centered at the training sample-weighted mean. It accepts new samples from known batches with the same ordered feature panel. Correction returns analysis-scale data. Use the original measurements and an appropriate joint model for downstream inference.
|
|
51
|
+
- `contrast_distortion` predicts the signed batch contribution to a case-minus-control arithmetic mean difference on the analysis scale. Include the group in the protected design. Its pointwise t intervals assume independent, homoscedastic Gaussian errors per feature, fixed group allocations, and a common additive batch effect. They do not account for selecting a correction on these same observations.
|
|
52
|
+
|
|
53
|
+
## Other assays and study designs
|
|
54
|
+
|
|
55
|
+
### Evaluation methods
|
|
56
|
+
|
|
57
|
+
| Scientific question | Python interface | Interpretation |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| Does a candidate batch partition align with the measurements? | `guided_pca(data, batch)` | First guided-to-unguided PC variance ratio and a Monte Carlo permutation p-value. Requires exchangeable samples. The native implementation centers the data and uses unscaled batch indicators. |
|
|
60
|
+
| Which features differ after protecting biology? | `feature_batch_tests(data, batch, protected)` | Partial F test across observed batches for each feature, with Benjamini–Hochberg adjustment across testable features. Assumes independent Gaussian observations with constant residual variance per feature. |
|
|
61
|
+
| How much variation in a PCA representation is associated with batch? | `pc_batch_share(data, batch, protected, retain=0.9)` | Reports the retained fraction and component count alongside raw and adjusted fixed-effects shares in that subspace. With all PCs and batch as sole predictor the total share gives the ordinary variance-weighted PCR score. |
|
|
62
|
+
| Is there global batch separation or unequal spread? | `r_evaluation(data, batch, method="permanova", protected=metadata)` or `method="permdisp"` | Upstream vegan marginal Euclidean PERMANOVA and spatial-median PERMDISP with small-sample adjustment. PERMDISP takes unadjusted groups. Optional `blocks=` restricts exchanges to the specified blocks when valid for the design. |
|
|
63
|
+
| How much variance is associated with random factors? | `r_evaluation(..., method="pvca", protected=factors)` or `method="variancePartition"` | Upstream Bioconductor PVCA uses internal VSN, categorical factors and retained-PC attribution. Supply intensities suitable for VSN. variancePartition returns per-feature fractions on the supplied scale. Encode categorical covariates as strings/categories and quantitative covariates as numeric for variancePartition. |
|
|
64
|
+
| Are samples separated or QCs imprecise? | `silhouette(data, labels)`, `qc_metrics(references, study)` | Per-sample ordinary silhouette; feature-level QC RSD and D-ratio from classical sample SDs. QC RSD requires intensities on a ratio scale. Use comparable sample material for interpreting technical dispersion. |
|
|
65
|
+
| Does an integrated single-cell embedding mix batches and preserve biology? | `single_cell_evaluation(adata, batch_key="batch", label_key="cell_type", embeddings=["integrated"])` | Runs the upstream scIB-metrics Benchmarker. Includes local batch mixing (iLISI, kBET), graph connectivity, PCR comparison, label silhouette, cLISI and clustering agreement (ARI/NMI). Results retain upstream score transformations; across-embedding min–max scaling is disabled. Pass a pre-integration embedding with `pre_integrated_embedding_obsm_key=` when available. |
|
|
66
|
+
|
|
67
|
+
Use `python -m pip install ".[singlecell]"` for the AnnData interface. Its dependency set uses the UMAP version tested with the graph metrics. For the R interface, install R and the packages for the desired methods. In R, use `install.packages("vegan")` or `BiocManager::install(c("pvca", "variancePartition"))`. Supply `rscript=` when Rscript is outside PATH. Backend warnings are available in the returned DataFrame's `attrs["diagnostics"]`.
|
|
68
|
+
|
|
69
|
+
Method references: [guided PCA](https://academic.oup.com/bioinformatics/article/29/22/2877/313226), [PERMANOVA](https://vegandevs.github.io/vegan/reference/adonis.html), [PERMDISP](https://vegandevs.github.io/vegan/reference/betadisper.html), [PVCA](https://bioconductor.org/packages/pvca), [variancePartition](https://bioconductor.org/packages/variancePartition), [scIB-metrics](https://scib-metrics.readthedocs.io/en/stable/api.html).
|
|
70
|
+
|
|
71
|
+
### Experimental estimators and benchmarks
|
|
72
|
+
|
|
73
|
+
For independent samples in two observed batches, `adaptive_location_test(data, batch, strata=group)` combines a sum and a maximum of squared within-stratum batch correlations to detect widespread and localized intensity shifts. Use categorical strata within which batch assignments are exchangeable, with both batches observed in each stratum. The function returns the two component p-values and a permutation-calibrated `omnibus_p` for the joint screen. Use a prespecified effect estimator such as `fit_batch` to quantify shifts and intervals on the relevant assay scale. The permutation test assumes exchangeability of the joint measurements under the null; unequal residual distributions can invalidate a mean-only interpretation.
|
|
74
|
+
|
|
75
|
+
Run `python examples/adaptive_detection.py` to reproduce the [two-batch pilot](examples/adaptive_detection_results.csv). Its 95% Wilson intervals quantify simulation uncertainty under the specific data-generating designs.
|
|
76
|
+
|
|
77
|
+
- `pc_batch_share(data, batch, protected, clip_mad=3)` clips each feature at its median ±3 scaled median absolute deviations before PCA. This experimental GVA variant uses adjusted fixed-effects shares in the retained representation. Its benchmark asks how well that representation estimates a known clean full-space target under outliers.
|
|
78
|
+
- `reference_contrast(data, batch, references, reference_batch, target="B", baseline="A", protected=metadata)` reports study-only, reference-mean, reference-median and inverse-variance-combined estimates of the signed B-minus-A shift. The combined estimate assumes independent study and reference errors and a transferable technical shift. Estimated weights are feature-specific. This is an experimental use of standard inverse-variance weighting.
|
|
79
|
+
- Run `python examples/evaluation_suite.py` for clean, contaminated, mismatched-reference and null simulations. Add `--waves <export-directory>` to resample whole, standardized within-export reference residuals with a known injected shift. Run `python examples/evaluation_suite.py --detection` for an independent detection benchmark. Each scenario uses 200 simulation replicates with seed 2026. Compare RMSE within a target only. Monte Carlo SEs describe simulation uncertainty.
|
|
80
|
+
|
|
81
|
+
Full results: [estimation RMSE](examples/evaluation_results.csv) and [detection rates](examples/detection_results.csv). In the contamination scenario the clipped PC score reduced RMSE for clean variance share from 0.119 to 0.073 relative to ordinary retained PCs. In clean data, full-space adjusted regression achieved 0.011 versus 0.028 for clipped PCs. Combining reference and study shifts improved clean-data RMSE from 0.256 to 0.221, but reference mismatch increased it from 0.259 to 0.328. These scenarios support conditional method choices.
|
|
82
|
+
|
|
83
|
+
### Assay inputs
|
|
84
|
+
|
|
85
|
+
| Input | Function and scope |
|
|
86
|
+
|---|---|
|
|
87
|
+
| Metabolomics or proteomics | Supply consistently transformed intensities, e.g. log2. Use an explicit detection mask with `detection_rates(mask, batch)` to quantify missing detections separately. |
|
|
88
|
+
| RNA, ATAC-seq or histone peak counts | Use `log_cpm(counts, library_size=totals)` for a log-scale exploratory analysis. Count columns must represent the same genes or regions for every sample. Total-count scaling assumes comparable composition. |
|
|
89
|
+
| Methylation | `methylation_log_odds(methylated, coverage)` computes log2 odds with a pseudocount. Zero coverage remains missing. Filter on coverage and use a common observed panel for the matrix fit. The fit gives observations equal weight. |
|
|
90
|
+
| ATAC or histone peak intervals | `peak_jaccard(left, right)` reports base-pair overlap divided by union on a common genome build using BED-style DataFrames. Compare technical replicates to study peak reproducibility. |
|
|
91
|
+
| Shared references across batches | `reference_correct(data, batch, references, reference_batch)` uses offsets from a common material independently of biological labels. `reference_dispersion(references, reference_batch)` estimates the root sum of feature variances in each batch. Use separate reference replicates to evaluate correction. |
|
|
92
|
+
|
|
93
|
+
The matrix fit requires finite dense data. This release provides transformed-scale diagnostics for count and methylation assays. Native count likelihoods, coverage-weighted models, subject random effects, drift correction and sparse single-cell matrices are outside this version's implemented scope.
|
|
94
|
+
|
|
95
|
+
## Reproduce the pilot
|
|
96
|
+
|
|
97
|
+
### Batch magnitude
|
|
98
|
+
|
|
99
|
+
Run `python examples/batch_magnitude.py` for a CSV of bias, RMSE, pointwise interval coverage, sparse-feature recovery and Monte Carlo standard errors. Each scenario has 200 independent simulations. Known truth uses the variance of the injected shifts after removing the true within-group means, on a population sampled uniformly over the designed rows with unit noise variance per feature. The total denominator includes biological signal, technical signal, their covariance and noise. The remaining denominator includes unique technical signal and noise.
|
|
100
|
+
|
|
101
|
+
The [recorded results](examples/batch_magnitude_results.csv) cover 32 scenarios (seed 2026). With 120 samples, 100 features, 80% of cases and 20% of controls in batch B, and zero true batch shift, raw remaining-share bias was 0.00846 (Monte Carlo SE 0.000086). Adjusted bias was −0.000013 (SE 0.000087). In the same design with five shifted features, ranking by partial R² recovered 98.5% of them among the top five (SE 0.37 percentage points). At 40 samples, recovery fell to 68.5% (SE 1.24 points). These simulations use independent Gaussian errors and additive shifts.
|
|
102
|
+
|
|
103
|
+
Run `python examples/batch_magnitude.py --scaling` for median fit time over three runs and peak traced allocations during fitting. On the development machine with one BLAS thread, 200 × 100, 1,000 × 100, 1,000 × 1,000 and 2,000 × 2,000 matrices took 0.002, 0.003, 0.015 and 0.071 seconds and peaked at 0.55, 2.48, 23.11 and 91.94 MiB, respectively. Tracing starts after input creation and excludes untraced native memory.
|
|
104
|
+
|
|
105
|
+
### Contrast distortion
|
|
106
|
+
|
|
107
|
+
Run `python examples/benchmark.py` after installation. It simulates paired clean and batch-affected matrices, holds the biology and noise fixed, varies batch imbalance, and scores predicted distortion and corrected group differences against the hidden clean contrast. In this particular additive fit the last two estimation errors have the same magnitude by construction. This pilot exercises the estimator under its assumptions. Independent reference materials and additional noise models are needed to evaluate transfer across assays.
|
|
108
|
+
|
|
109
|
+
Run `python -m unittest discover -s tests -v` to check numerical and input-handling behavior.
|
|
110
|
+
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# DeepBatch
|
|
2
|
+
|
|
3
|
+
DeepBatch 0.2.0 measures batch effects across molecular assays and corrects additive shifts. Rows are samples and columns are features. The core model fits independent observations on a continuous analysis scale.
|
|
4
|
+
|
|
5
|
+
## Install locally
|
|
6
|
+
|
|
7
|
+
From this directory, run `python -m pip install .`. Python 3.10+ is required.
|
|
8
|
+
|
|
9
|
+
## Measure, correct, and estimate contrast distortion
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
from deepbatch import fit_batch
|
|
15
|
+
|
|
16
|
+
rng = np.random.default_rng(42)
|
|
17
|
+
samples = pd.Index([f"s{i}" for i in range(12)])
|
|
18
|
+
group = pd.Series(["control"] * 6 + ["case"] * 6, index=samples, name="group")
|
|
19
|
+
batch = pd.Series(list("AAAABB") + list("AABBBB"), index=samples)
|
|
20
|
+
data = pd.DataFrame(rng.normal(size=(12, 3)), index=samples, columns=["f1", "f2", "f3"])
|
|
21
|
+
data["f1"] += 0.8 * batch.eq("B") + 0.5 * group.eq("case")
|
|
22
|
+
|
|
23
|
+
fit = fit_batch(data, batch, protected=group.to_frame())
|
|
24
|
+
print(fit.global_scores)
|
|
25
|
+
print(fit.features.partial_r2.describe())
|
|
26
|
+
print(fit.features.join(fit.batch_contrast("B", "A")).sort_values("partial_r2", ascending=False))
|
|
27
|
+
print(fit.contrast_distortion(group, case="case", control="control"))
|
|
28
|
+
adjusted = fit.correct(data, batch)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The model includes an intercept, protected covariates, and fixed batch effects. Encode categorical covariates as strings or pandas categories. Numeric covariates enter as continuous predictors. Metadata aligns by sample ID. A rank-deficient design raises an error. The condition number and residual degrees of freedom are available on the fit. Use numeric covariate scales appropriate for interpreting the condition number.
|
|
32
|
+
|
|
33
|
+
- `batch_share_total` divides the additional sum of squares for batch by the total centered sum of squares across features. `batch_share_remaining` uses the residual sum of squares after protecting biology as its denominator. Feature scaling affects both global scores.
|
|
34
|
+
- `partial_r2` and its degrees-of-freedom-adjusted counterpart describe individual features. Undefined fractions are NaN. Adjusted estimates can be negative.
|
|
35
|
+
- `adjusted_batch_share_remaining` compares the pooled residual mean squares of the full and protected models. Negative values are retained. All three global scores pool sums of squares across the supplied features. Features with more variation carry more weight. For equal scale across features, standardize explicitly before fitting and interpret contrasts on that standardized scale.
|
|
36
|
+
- `batch_contrast("B", "A")` returns the adjusted B-minus-A difference, standard error and pointwise t interval for each feature. On log2 intensities, an estimate of 1 represents a twofold difference. The model assumes an additive common shift across biological groups. Intervals assume independent samples and approximately Gaussian, equal-variance residuals within each feature. In study samples, a difference conditional on measured biology can still reflect unmeasured biology.
|
|
37
|
+
- `correct` subtracts fitted batch shifts centered at the training sample-weighted mean. It accepts new samples from known batches with the same ordered feature panel. Correction returns analysis-scale data. Use the original measurements and an appropriate joint model for downstream inference.
|
|
38
|
+
- `contrast_distortion` predicts the signed batch contribution to a case-minus-control arithmetic mean difference on the analysis scale. Include the group in the protected design. Its pointwise t intervals assume independent, homoscedastic Gaussian errors per feature, fixed group allocations, and a common additive batch effect. They do not account for selecting a correction on these same observations.
|
|
39
|
+
|
|
40
|
+
## Other assays and study designs
|
|
41
|
+
|
|
42
|
+
### Evaluation methods
|
|
43
|
+
|
|
44
|
+
| Scientific question | Python interface | Interpretation |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| Does a candidate batch partition align with the measurements? | `guided_pca(data, batch)` | First guided-to-unguided PC variance ratio and a Monte Carlo permutation p-value. Requires exchangeable samples. The native implementation centers the data and uses unscaled batch indicators. |
|
|
47
|
+
| Which features differ after protecting biology? | `feature_batch_tests(data, batch, protected)` | Partial F test across observed batches for each feature, with Benjamini–Hochberg adjustment across testable features. Assumes independent Gaussian observations with constant residual variance per feature. |
|
|
48
|
+
| How much variation in a PCA representation is associated with batch? | `pc_batch_share(data, batch, protected, retain=0.9)` | Reports the retained fraction and component count alongside raw and adjusted fixed-effects shares in that subspace. With all PCs and batch as sole predictor the total share gives the ordinary variance-weighted PCR score. |
|
|
49
|
+
| Is there global batch separation or unequal spread? | `r_evaluation(data, batch, method="permanova", protected=metadata)` or `method="permdisp"` | Upstream vegan marginal Euclidean PERMANOVA and spatial-median PERMDISP with small-sample adjustment. PERMDISP takes unadjusted groups. Optional `blocks=` restricts exchanges to the specified blocks when valid for the design. |
|
|
50
|
+
| How much variance is associated with random factors? | `r_evaluation(..., method="pvca", protected=factors)` or `method="variancePartition"` | Upstream Bioconductor PVCA uses internal VSN, categorical factors and retained-PC attribution. Supply intensities suitable for VSN. variancePartition returns per-feature fractions on the supplied scale. Encode categorical covariates as strings/categories and quantitative covariates as numeric for variancePartition. |
|
|
51
|
+
| Are samples separated or QCs imprecise? | `silhouette(data, labels)`, `qc_metrics(references, study)` | Per-sample ordinary silhouette; feature-level QC RSD and D-ratio from classical sample SDs. QC RSD requires intensities on a ratio scale. Use comparable sample material for interpreting technical dispersion. |
|
|
52
|
+
| Does an integrated single-cell embedding mix batches and preserve biology? | `single_cell_evaluation(adata, batch_key="batch", label_key="cell_type", embeddings=["integrated"])` | Runs the upstream scIB-metrics Benchmarker. Includes local batch mixing (iLISI, kBET), graph connectivity, PCR comparison, label silhouette, cLISI and clustering agreement (ARI/NMI). Results retain upstream score transformations; across-embedding min–max scaling is disabled. Pass a pre-integration embedding with `pre_integrated_embedding_obsm_key=` when available. |
|
|
53
|
+
|
|
54
|
+
Use `python -m pip install ".[singlecell]"` for the AnnData interface. Its dependency set uses the UMAP version tested with the graph metrics. For the R interface, install R and the packages for the desired methods. In R, use `install.packages("vegan")` or `BiocManager::install(c("pvca", "variancePartition"))`. Supply `rscript=` when Rscript is outside PATH. Backend warnings are available in the returned DataFrame's `attrs["diagnostics"]`.
|
|
55
|
+
|
|
56
|
+
Method references: [guided PCA](https://academic.oup.com/bioinformatics/article/29/22/2877/313226), [PERMANOVA](https://vegandevs.github.io/vegan/reference/adonis.html), [PERMDISP](https://vegandevs.github.io/vegan/reference/betadisper.html), [PVCA](https://bioconductor.org/packages/pvca), [variancePartition](https://bioconductor.org/packages/variancePartition), [scIB-metrics](https://scib-metrics.readthedocs.io/en/stable/api.html).
|
|
57
|
+
|
|
58
|
+
### Experimental estimators and benchmarks
|
|
59
|
+
|
|
60
|
+
For independent samples in two observed batches, `adaptive_location_test(data, batch, strata=group)` combines a sum and a maximum of squared within-stratum batch correlations to detect widespread and localized intensity shifts. Use categorical strata within which batch assignments are exchangeable, with both batches observed in each stratum. The function returns the two component p-values and a permutation-calibrated `omnibus_p` for the joint screen. Use a prespecified effect estimator such as `fit_batch` to quantify shifts and intervals on the relevant assay scale. The permutation test assumes exchangeability of the joint measurements under the null; unequal residual distributions can invalidate a mean-only interpretation.
|
|
61
|
+
|
|
62
|
+
Run `python examples/adaptive_detection.py` to reproduce the [two-batch pilot](examples/adaptive_detection_results.csv). Its 95% Wilson intervals quantify simulation uncertainty under the specific data-generating designs.
|
|
63
|
+
|
|
64
|
+
- `pc_batch_share(data, batch, protected, clip_mad=3)` clips each feature at its median ±3 scaled median absolute deviations before PCA. This experimental GVA variant uses adjusted fixed-effects shares in the retained representation. Its benchmark asks how well that representation estimates a known clean full-space target under outliers.
|
|
65
|
+
- `reference_contrast(data, batch, references, reference_batch, target="B", baseline="A", protected=metadata)` reports study-only, reference-mean, reference-median and inverse-variance-combined estimates of the signed B-minus-A shift. The combined estimate assumes independent study and reference errors and a transferable technical shift. Estimated weights are feature-specific. This is an experimental use of standard inverse-variance weighting.
|
|
66
|
+
- Run `python examples/evaluation_suite.py` for clean, contaminated, mismatched-reference and null simulations. Add `--waves <export-directory>` to resample whole, standardized within-export reference residuals with a known injected shift. Run `python examples/evaluation_suite.py --detection` for an independent detection benchmark. Each scenario uses 200 simulation replicates with seed 2026. Compare RMSE within a target only. Monte Carlo SEs describe simulation uncertainty.
|
|
67
|
+
|
|
68
|
+
Full results: [estimation RMSE](examples/evaluation_results.csv) and [detection rates](examples/detection_results.csv). In the contamination scenario the clipped PC score reduced RMSE for clean variance share from 0.119 to 0.073 relative to ordinary retained PCs. In clean data, full-space adjusted regression achieved 0.011 versus 0.028 for clipped PCs. Combining reference and study shifts improved clean-data RMSE from 0.256 to 0.221, but reference mismatch increased it from 0.259 to 0.328. These scenarios support conditional method choices.
|
|
69
|
+
|
|
70
|
+
### Assay inputs
|
|
71
|
+
|
|
72
|
+
| Input | Function and scope |
|
|
73
|
+
|---|---|
|
|
74
|
+
| Metabolomics or proteomics | Supply consistently transformed intensities, e.g. log2. Use an explicit detection mask with `detection_rates(mask, batch)` to quantify missing detections separately. |
|
|
75
|
+
| RNA, ATAC-seq or histone peak counts | Use `log_cpm(counts, library_size=totals)` for a log-scale exploratory analysis. Count columns must represent the same genes or regions for every sample. Total-count scaling assumes comparable composition. |
|
|
76
|
+
| Methylation | `methylation_log_odds(methylated, coverage)` computes log2 odds with a pseudocount. Zero coverage remains missing. Filter on coverage and use a common observed panel for the matrix fit. The fit gives observations equal weight. |
|
|
77
|
+
| ATAC or histone peak intervals | `peak_jaccard(left, right)` reports base-pair overlap divided by union on a common genome build using BED-style DataFrames. Compare technical replicates to study peak reproducibility. |
|
|
78
|
+
| Shared references across batches | `reference_correct(data, batch, references, reference_batch)` uses offsets from a common material independently of biological labels. `reference_dispersion(references, reference_batch)` estimates the root sum of feature variances in each batch. Use separate reference replicates to evaluate correction. |
|
|
79
|
+
|
|
80
|
+
The matrix fit requires finite dense data. This release provides transformed-scale diagnostics for count and methylation assays. Native count likelihoods, coverage-weighted models, subject random effects, drift correction and sparse single-cell matrices are outside this version's implemented scope.
|
|
81
|
+
|
|
82
|
+
## Reproduce the pilot
|
|
83
|
+
|
|
84
|
+
### Batch magnitude
|
|
85
|
+
|
|
86
|
+
Run `python examples/batch_magnitude.py` for a CSV of bias, RMSE, pointwise interval coverage, sparse-feature recovery and Monte Carlo standard errors. Each scenario has 200 independent simulations. Known truth uses the variance of the injected shifts after removing the true within-group means, on a population sampled uniformly over the designed rows with unit noise variance per feature. The total denominator includes biological signal, technical signal, their covariance and noise. The remaining denominator includes unique technical signal and noise.
|
|
87
|
+
|
|
88
|
+
The [recorded results](examples/batch_magnitude_results.csv) cover 32 scenarios (seed 2026). With 120 samples, 100 features, 80% of cases and 20% of controls in batch B, and zero true batch shift, raw remaining-share bias was 0.00846 (Monte Carlo SE 0.000086). Adjusted bias was −0.000013 (SE 0.000087). In the same design with five shifted features, ranking by partial R² recovered 98.5% of them among the top five (SE 0.37 percentage points). At 40 samples, recovery fell to 68.5% (SE 1.24 points). These simulations use independent Gaussian errors and additive shifts.
|
|
89
|
+
|
|
90
|
+
Run `python examples/batch_magnitude.py --scaling` for median fit time over three runs and peak traced allocations during fitting. On the development machine with one BLAS thread, 200 × 100, 1,000 × 100, 1,000 × 1,000 and 2,000 × 2,000 matrices took 0.002, 0.003, 0.015 and 0.071 seconds and peaked at 0.55, 2.48, 23.11 and 91.94 MiB, respectively. Tracing starts after input creation and excludes untraced native memory.
|
|
91
|
+
|
|
92
|
+
### Contrast distortion
|
|
93
|
+
|
|
94
|
+
Run `python examples/benchmark.py` after installation. It simulates paired clean and batch-affected matrices, holds the biology and noise fixed, varies batch imbalance, and scores predicted distortion and corrected group differences against the hidden clean contrast. In this particular additive fit the last two estimation errors have the same magnitude by construction. This pilot exercises the estimator under its assumptions. Independent reference materials and additional noise models are needed to evaluate transfer across assays.
|
|
95
|
+
|
|
96
|
+
Run `python -m unittest discover -s tests -v` to check numerical and input-handling behavior.
|
|
97
|
+
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Reproduce the first DeepBatch adaptive location benchmark; print CSV to stdout."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from scipy.stats import binomtest
|
|
5
|
+
|
|
6
|
+
from deepbatch import adaptive_location_test
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def benchmark(repeats=300, seed=502):
|
|
10
|
+
rng = np.random.default_rng(seed)
|
|
11
|
+
group = pd.Series(np.repeat([0, 1], 40))
|
|
12
|
+
batch = pd.Series([0] * 30 + [1] * 10 + [0] * 10 + [1] * 30)
|
|
13
|
+
scenarios = {"null": (0, 0), "dense": (80, 0.25), "sparse": (2, 0.9)}
|
|
14
|
+
results = []
|
|
15
|
+
for name, (affected, shift) in scenarios.items():
|
|
16
|
+
trials = []
|
|
17
|
+
for _ in range(repeats):
|
|
18
|
+
# Blocks of eight correlated features, unit marginal noise variance.
|
|
19
|
+
shared = np.repeat(rng.normal(size=(80, 10)), 8, axis=1)
|
|
20
|
+
y = np.sqrt(0.2) * shared + np.sqrt(0.8) * rng.normal(size=(80, 80))
|
|
21
|
+
y += group.to_numpy()[:, None] * np.linspace(-1, 1, 80)
|
|
22
|
+
y[:, :affected] += batch.to_numpy()[:, None] * shift
|
|
23
|
+
trials.append(adaptive_location_test(pd.DataFrame(y), batch, strata=group,
|
|
24
|
+
permutations=199, seed=rng))
|
|
25
|
+
for method, values in pd.DataFrame(trials).items():
|
|
26
|
+
hits = int((values <= 0.05).sum())
|
|
27
|
+
ci = binomtest(hits, repeats).proportion_ci(method="wilson")
|
|
28
|
+
results.append((name, method, repeats, hits / repeats, ci.low, ci.high))
|
|
29
|
+
return pd.DataFrame(results, columns=["scenario", "test", "runs", "rejection_rate", "lower", "upper"])
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
if __name__ == "__main__":
|
|
33
|
+
print(benchmark().to_csv(index=False, float_format="%.4f", lineterminator="\n"), end="")
|
|
34
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
scenario,test,runs,rejection_rate,lower,upper
|
|
2
|
+
null,dense_p,300,0.0567,0.0357,0.0889
|
|
3
|
+
null,sparse_p,300,0.0500,0.0305,0.0808
|
|
4
|
+
null,omnibus_p,300,0.0533,0.0331,0.0849
|
|
5
|
+
dense,dense_p,300,0.9500,0.9192,0.9695
|
|
6
|
+
dense,sparse_p,300,0.4367,0.3817,0.4932
|
|
7
|
+
dense,omnibus_p,300,0.9300,0.8954,0.9538
|
|
8
|
+
sparse,dense_p,300,0.3267,0.2761,0.3816
|
|
9
|
+
sparse,sparse_p,300,0.6600,0.6047,0.7113
|
|
10
|
+
sparse,omnibus_p,300,0.6400,0.5842,0.6922
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Known-truth evaluation, using independent simulation runs for Monte Carlo SEs."""
|
|
2
|
+
import argparse
|
|
3
|
+
from itertools import product
|
|
4
|
+
from time import perf_counter
|
|
5
|
+
import tracemalloc
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from deepbatch import fit_batch
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def simulate(n, p, fraction, strength, rng, repeats):
|
|
14
|
+
"""Fixed design; population moments average uniformly over its observed rows."""
|
|
15
|
+
half = n // 2
|
|
16
|
+
count = round(half * fraction)
|
|
17
|
+
group = pd.Series(np.repeat([0, 1], half), name="group")
|
|
18
|
+
batch = pd.Series([1] * (half - count) + [0] * count
|
|
19
|
+
+ [1] * count + [0] * (half - count))
|
|
20
|
+
g = group.to_numpy()[:, None]
|
|
21
|
+
shift = np.full(p, {"null": 0., "weak": 0.3, "strong": 1.2, "sparse": 0.}[strength])
|
|
22
|
+
hits = p // 20
|
|
23
|
+
if strength == "sparse":
|
|
24
|
+
shift[:hits] = 1.2
|
|
25
|
+
technical = batch.to_numpy()[:, None] * shift
|
|
26
|
+
signal = g * np.linspace(0.2, 1, p) + technical
|
|
27
|
+
# Removing the true mean within each biological group projects out the
|
|
28
|
+
# protected design. Each feature has unit conditional noise variance.
|
|
29
|
+
unique = technical - pd.DataFrame(technical).groupby(group).transform("mean").to_numpy()
|
|
30
|
+
batch_power = np.mean(unique ** 2)
|
|
31
|
+
target_remaining = batch_power / (1 + batch_power)
|
|
32
|
+
target_total = batch_power / (1 + np.var(signal, axis=0).mean())
|
|
33
|
+
covariates = group.to_frame()
|
|
34
|
+
rows = []
|
|
35
|
+
for _ in range(repeats):
|
|
36
|
+
fit = fit_batch(pd.DataFrame(signal + rng.normal(size=signal.shape)), batch, covariates)
|
|
37
|
+
pair = fit.batch_contrast(1, 0)
|
|
38
|
+
scores = fit.global_scores
|
|
39
|
+
row = {
|
|
40
|
+
"total_error": scores.batch_share_total - target_total,
|
|
41
|
+
"remaining_error": scores.batch_share_remaining - target_remaining,
|
|
42
|
+
"adjusted_error": scores.adjusted_batch_share_remaining - target_remaining,
|
|
43
|
+
"coverage": ((pair.lower <= shift) & (shift <= pair.upper)).mean(),
|
|
44
|
+
}
|
|
45
|
+
if strength == "sparse":
|
|
46
|
+
top = fit.features.partial_r2.nlargest(hits).index
|
|
47
|
+
row["recall_at_k"] = np.mean(top < hits)
|
|
48
|
+
rows.append(row)
|
|
49
|
+
summary = {"n": n, "p": p, "case_fraction_B": fraction, "signal": strength,
|
|
50
|
+
"true_total": target_total, "true_remaining": target_remaining}
|
|
51
|
+
for name, values in pd.DataFrame(rows).items():
|
|
52
|
+
vals = values.to_numpy()
|
|
53
|
+
if name.endswith("_error"):
|
|
54
|
+
prefix = name.removesuffix("_error")
|
|
55
|
+
mse = np.mean(vals ** 2)
|
|
56
|
+
rmse = np.sqrt(mse)
|
|
57
|
+
summary[prefix + "_bias"] = vals.mean()
|
|
58
|
+
summary[prefix + "_bias_mcse"] = vals.std(ddof=1) / np.sqrt(repeats)
|
|
59
|
+
summary[prefix + "_rmse"] = rmse
|
|
60
|
+
summary[prefix + "_rmse_mcse"] = (
|
|
61
|
+
(vals ** 2).std(ddof=1) / (2 * rmse * np.sqrt(repeats)) if rmse else 0.
|
|
62
|
+
)
|
|
63
|
+
else:
|
|
64
|
+
summary[name] = vals.mean()
|
|
65
|
+
summary[name + "_mcse"] = vals.std(ddof=1) / np.sqrt(repeats)
|
|
66
|
+
return summary
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def scaling(seed):
|
|
70
|
+
"""Peak traced allocations during fitting, excluding the prebuilt inputs."""
|
|
71
|
+
rng = np.random.default_rng(seed)
|
|
72
|
+
rows = []
|
|
73
|
+
for n, p in [(200, 100), (1000, 100), (1000, 1000), (2000, 2000)]:
|
|
74
|
+
y = pd.DataFrame(rng.normal(size=(n, p)))
|
|
75
|
+
batch = pd.Series(np.arange(n) % 4)
|
|
76
|
+
durations, peaks = [], []
|
|
77
|
+
for _ in range(3):
|
|
78
|
+
tracemalloc.start()
|
|
79
|
+
start = perf_counter()
|
|
80
|
+
fit_batch(y, batch)
|
|
81
|
+
durations.append(perf_counter() - start)
|
|
82
|
+
peaks.append(tracemalloc.get_traced_memory()[1] / 2 ** 20)
|
|
83
|
+
tracemalloc.stop()
|
|
84
|
+
rows.append((n, p, np.median(durations), max(peaks)))
|
|
85
|
+
return pd.DataFrame(rows, columns=["n", "p", "median_seconds", "peak_traced_MiB"])
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
if __name__ == "__main__":
|
|
89
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
90
|
+
parser.add_argument("--repeats", type=int, default=200)
|
|
91
|
+
parser.add_argument("--seed", type=int, default=2026)
|
|
92
|
+
parser.add_argument("--scaling", action="store_true")
|
|
93
|
+
args = parser.parse_args()
|
|
94
|
+
if args.scaling:
|
|
95
|
+
print(scaling(args.seed).to_string(index=False))
|
|
96
|
+
else:
|
|
97
|
+
if args.repeats < 2:
|
|
98
|
+
parser.error("At least two independent repeats are needed for Monte Carlo SEs.")
|
|
99
|
+
rng = np.random.default_rng(args.seed)
|
|
100
|
+
scenarios = product((40, 120), (20, 100), (0.5, 0.8), ("null", "weak", "strong", "sparse"))
|
|
101
|
+
results = [simulate(n, p, f, s, rng, args.repeats) for n, p, f, s in scenarios]
|
|
102
|
+
print(pd.DataFrame(results).to_csv(index=False, float_format="%.7g"), end="")
|
|
103
|
+
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
n,p,case_fraction_B,signal,true_total,true_remaining,total_bias,total_bias_mcse,total_rmse,total_rmse_mcse,remaining_bias,remaining_bias_mcse,remaining_rmse,remaining_rmse_mcse,adjusted_bias,adjusted_bias_mcse,adjusted_rmse,adjusted_rmse_mcse,coverage,coverage_mcse,recall_at_k,recall_at_k_mcse
|
|
2
|
+
|
|
3
|
+
40,20,0.5,null,0,0,0.02407541,0.0005851063,0.02545099,0.000670094,0.02733865,0.0006535577,0.02885138,0.0007456514,0.001050504,0.0006712214,0.009526839,0.0006964239,0.94525,0.003590144,,
|
|
4
|
+
|
|
5
|
+
40,20,0.5,weak,0.01996031,0.02200489,0.02146059,0.0007934846,0.02420436,0.0008121437,0.02501795,0.0009039237,0.02808018,0.0009371308,-0.0007381898,0.0009283541,0.01311683,0.0006864973,0.9555,0.00310596,,
|
|
6
|
+
|
|
7
|
+
40,20,0.5,strong,0.2457779,0.2647059,0.02291416,0.00156814,0.03184984,0.001380248,0.03030193,0.001707079,0.03870551,0.001560513,0.01124809,0.001753216,0.02716982,0.001375438,0.95625,0.003208373,,
|
|
8
|
+
|
|
9
|
+
40,20,0.5,sparse,0.01603225,0.01768173,0.02326855,0.0006906745,0.02522607,0.0006820467,0.02678988,0.0007794965,0.02895882,0.000775446,0.0009647915,0.000800564,0.01133448,0.0005260858,0.9555,0.00322502,0.91,0.02028689
|
|
10
|
+
|
|
11
|
+
40,20,0.8,null,0,0,0.02432047,0.0005965912,0.02573546,0.0006892307,0.02768435,0.0006761902,0.02928161,0.0007791512,0.001405547,0.0006944656,0.009896957,0.0007273285,0.94075,0.003900095,,
|
|
12
|
+
|
|
13
|
+
40,20,0.8,weak,0.01219061,0.01419558,0.02194857,0.0006883886,0.02400087,0.00069878,0.02668869,0.0008148255,0.02905874,0.000831188,0.000766648,0.0008368478,0.01183006,0.0006140381,0.94975,0.003390378,,
|
|
14
|
+
|
|
15
|
+
40,20,0.8,strong,0.1370827,0.1872562,0.01670282,0.001277784,0.02457433,0.001159441,0.02808872,0.001643738,0.03642319,0.001482663,0.006881825,0.001688163,0.02478888,0.001241205,0.9515,0.003148542,,
|
|
16
|
+
|
|
17
|
+
40,20,0.8,sparse,0.01022785,0.0113888,0.02198626,0.0007025326,0.02411664,0.0007510555,0.02549343,0.0008039878,0.02790247,0.000860406,-0.0005367774,0.0008257172,0.01166054,0.0005810974,0.954,0.003515222,0.755,0.03048807
|
|
18
|
+
|
|
19
|
+
40,100,0.5,null,0,0,0.02295361,0.0002402792,0.02320253,0.0002403931,0.02610038,0.0002721391,0.0263812,0.0002719073,-0.0002212302,0.0002794942,0.003948952,0.0002086805,0.94815,0.001558052,,
|
|
20
|
+
|
|
21
|
+
40,100,0.5,weak,0.01998042,0.02200489,0.02341386,0.0003830622,0.02402934,0.0003951211,0.02720473,0.0004341501,0.02788559,0.0004449718,0.001507694,0.0004458839,0.006468139,0.000358965,0.9469,0.00158889,,
|
|
22
|
+
|
|
23
|
+
40,100,0.5,strong,0.2459684,0.2647059,0.02081686,0.0007796825,0.02354389,0.0007313913,0.02817542,0.0008344771,0.03053569,0.0008074041,0.009064105,0.0008570306,0.01511039,0.0006852196,0.94995,0.001579545,,
|
|
24
|
+
|
|
25
|
+
40,100,0.5,sparse,0.01604846,0.01768173,0.02328351,0.0003156629,0.0237055,0.0003144299,0.02684556,0.0003570743,0.02731404,0.0003564072,0.001021974,0.000366725,0.005273271,0.0002526428,0.9506,0.001481273,0.857,0.008782978
|
|
26
|
+
|
|
27
|
+
40,100,0.8,null,0,0,0.02366932,0.0002292257,0.02388918,0.0002316446,0.02685474,0.0002598293,0.02710372,0.0002632176,0.0005535142,0.0002668517,0.003804883,0.0002096708,0.94935,0.001525458,,
|
|
28
|
+
|
|
29
|
+
40,100,0.8,weak,0.01220233,0.01419558,0.02180567,0.0003452804,0.02234304,0.0003481308,0.02651495,0.00040914,0.02713585,0.0004132615,0.0005882063,0.0004201979,0.005956733,0.0003058366,0.95005,0.001679761,,
|
|
30
|
+
|
|
31
|
+
40,100,0.8,strong,0.1371753,0.1872562,0.01725489,0.0006215169,0.01935462,0.0005821316,0.02931526,0.0008024171,0.03142475,0.000767338,0.008141512,0.0008241041,0.01419276,0.0006447568,0.95015,0.001535963,,
|
|
32
|
+
|
|
33
|
+
40,100,0.8,sparse,0.01023551,0.0113888,0.02277422,0.000330281,0.02324593,0.0003591916,0.02642224,0.0003783633,0.02695596,0.0004110327,0.0004171379,0.0003885893,0.005497575,0.0004154272,0.95055,0.001517399,0.685,0.01239529
|
|
34
|
+
|
|
35
|
+
120,20,0.5,null,0,0,0.007599053,0.0001698445,0.007967823,0.0001874411,0.008452687,0.0001881098,0.008859435,0.0002076039,-2.207619e-05,0.0001897176,0.002676387,0.0001712192,0.9505,0.003508604,,
|
|
36
|
+
|
|
37
|
+
120,20,0.5,weak,0.01996031,0.02200489,0.007072791,0.0004009116,0.009055919,0.0004159225,0.008030099,0.0004430204,0.01017544,0.0004581453,-0.0002602004,0.0004468069,0.006308355,0.0003327363,0.94825,0.003689887,,
|
|
38
|
+
|
|
39
|
+
120,20,0.5,strong,0.2457779,0.2647059,0.005882784,0.001025261,0.01561371,0.0008327948,0.008011651,0.001088681,0.01732185,0.000925774,0.001795561,0.001097986,0.01559273,0.0008759232,0.94975,0.003445511,,
|
|
40
|
+
|
|
41
|
+
120,20,0.5,sparse,0.01603225,0.01768173,0.007735328,0.000388452,0.009479631,0.0003527962,0.008766951,0.0004322516,0.01067899,0.0003946424,0.0004459992,0.000435946,0.006165927,0.0002642788,0.95125,0.003639494,1,0
|
|
42
|
+
|
|
43
|
+
120,20,0.8,null,0,0,0.007503058,0.0001663143,0.007861317,0.0001790571,0.008376325,0.0001869293,0.008781593,0.0002019049,-9.909152e-05,0.000188527,0.002661346,0.000138409,0.94875,0.003516606,,
|
|
44
|
+
|
|
45
|
+
120,20,0.8,weak,0.01219061,0.01419558,0.007163055,0.0003361364,0.008590338,0.0003337722,0.008582659,0.0003956505,0.01023784,0.0003946642,0.0002303366,0.0003990321,0.005633751,0.0002616585,0.95125,0.003622194,,
|
|
46
|
+
|
|
47
|
+
120,20,0.8,strong,0.1370827,0.1872562,0.006394709,0.0007252407,0.01206487,0.0005441783,0.01013104,0.0009384487,0.01667017,0.0007208054,0.003271102,0.0009464696,0.01374646,0.0006317925,0.95775,0.002967527,,
|
|
48
|
+
|
|
49
|
+
120,20,0.8,sparse,0.01022785,0.0113888,0.008000496,0.0003263373,0.009230419,0.0003157422,0.009096127,0.0003663503,0.01046173,0.0003566883,0.0007242035,0.0003694815,0.005262249,0.0002494053,0.9465,0.003372032,0.995,0.005
|
|
50
|
+
|
|
51
|
+
120,100,0.5,null,0,0,0.007608926,7.741749e-05,0.007686901,7.915534e-05,0.008472934,8.627901e-05,0.008559905,8.816517e-05,-1.656404e-06,8.701644e-05,0.001227519,6.358586e-05,0.94855,0.001641787,,
|
|
52
|
+
|
|
53
|
+
120,100,0.5,weak,0.01998042,0.02200489,0.007813009,0.0001850078,0.008237381,0.0001831131,0.008861378,0.0002053788,0.009322978,0.0002030897,0.0005781837,0.0002071341,0.002978641,0.0001364062,0.948,0.001531905,,
|
|
54
|
+
|
|
55
|
+
120,100,0.5,strong,0.2459684,0.2647059,0.007616441,0.0004608043,0.01001329,0.0004177401,0.01009148,0.0004930972,0.01225658,0.0004691613,0.003893164,0.0004973117,0.008023291,0.0004141999,0.9486,0.001695457,,
|
|
56
|
+
|
|
57
|
+
120,100,0.5,sparse,0.01604846,0.01768173,0.007765024,0.0001694127,0.008124471,0.0001681423,0.008796526,0.0001887098,0.009190513,0.0001871079,0.0004758274,0.0001903227,0.002726671,0.0001389272,0.94765,0.001585071,1,0
|
|
58
|
+
|
|
59
|
+
120,100,0.8,null,0,0,0.007596074,7.727154e-05,0.007673887,7.834305e-05,0.00846195,8.582854e-05,0.008548131,8.716364e-05,-1.273438e-05,8.656211e-05,0.001221175,5.678318e-05,0.9508,0.001582505,,
|
|
60
|
+
|
|
61
|
+
120,100,0.8,weak,0.01220233,0.01419558,0.00743234,0.0001553011,0.0077485,0.0001572416,0.008847074,0.000181697,0.009210888,0.0001837778,0.0004970111,0.0001832499,0.002632403,0.00012989,0.946,0.001656417,,
|
|
62
|
+
|
|
63
|
+
120,100,0.8,strong,0.1371753,0.1872562,0.005289987,0.0003591038,0.007324351,0.0003205146,0.008946818,0.0004587124,0.01104167,0.0004059969,0.002076758,0.000462633,0.006848704,0.0003235019,0.9493,0.001474251,,
|
|
64
|
+
|
|
65
|
+
120,100,0.8,sparse,0.01023551,0.0113888,0.007539609,0.0001540314,0.007846471,0.0001597177,0.008576015,0.0001719777,0.00891256,0.0001782665,0.0001996464,0.0001734476,0.002454911,0.0001316606,0.9487,0.001489174,0.985,0.003734263
|
|
66
|
+
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Run with 'python examples/benchmark.py' after installing deepbatch."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from deepbatch import fit_batch
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def benchmark(seed=24, repeats=200):
|
|
9
|
+
rng = np.random.default_rng(seed)
|
|
10
|
+
rows = []
|
|
11
|
+
group = pd.Series(np.repeat(["control", "case"], 50), name="group")
|
|
12
|
+
case = group.eq("case")
|
|
13
|
+
for n_case_b in (25, 35, 45):
|
|
14
|
+
b = pd.Series([1] * (50 - n_case_b) + [0] * n_case_b
|
|
15
|
+
+ [1] * n_case_b + [0] * (50 - n_case_b))
|
|
16
|
+
for run in range(repeats):
|
|
17
|
+
clean = pd.DataFrame(rng.normal(0, 0.4, (100, 20)) + 0.3 * case.to_numpy()[:, None])
|
|
18
|
+
shift = np.linspace(0, 0.8, clean.shape[1])
|
|
19
|
+
observed = clean + b.to_numpy()[:, None] * shift
|
|
20
|
+
truth = ((observed[case].mean() - observed[~case].mean())
|
|
21
|
+
- (clean[case].mean() - clean[~case].mean()))
|
|
22
|
+
fit = fit_batch(observed, b, group.to_frame())
|
|
23
|
+
pred = fit.contrast_distortion(group, case="case", control="control")
|
|
24
|
+
corrected = fit.correct(observed, b)
|
|
25
|
+
error = pred.distortion - truth
|
|
26
|
+
residual = (corrected[case].mean() - corrected[~case].mean()
|
|
27
|
+
- clean[case].mean() + clean[~case].mean())
|
|
28
|
+
rows.append({"case_fraction_in_B": n_case_b / 50, "run": run,
|
|
29
|
+
"raw_contrast_mse": np.mean(truth ** 2),
|
|
30
|
+
"distortion_mse": np.mean(error ** 2),
|
|
31
|
+
"corrected_contrast_mse": np.mean(residual ** 2),
|
|
32
|
+
"interval_coverage": np.mean((pred.lower <= truth + 1e-12)
|
|
33
|
+
& (truth <= pred.upper + 1e-12))})
|
|
34
|
+
return pd.DataFrame(rows)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
if __name__ == "__main__":
|
|
38
|
+
print(benchmark().groupby("case_fraction_in_B").mean().drop(columns="run").round(4))
|
|
39
|
+
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
scenario,target,method,size,rmse,mcse
|
|
2
|
+
clean,assay_unit_shift,combined,200,0.2206491,0.001793563
|
|
3
|
+
clean,assay_unit_shift,reference_mean,200,0.4050963,0.003171355
|
|
4
|
+
clean,assay_unit_shift,reference_median,200,0.4828127,0.004167903
|
|
5
|
+
clean,assay_unit_shift,study,200,0.2556437,0.002024291
|
|
6
|
+
clean,clean_full_space_share,adjusted_partial,200,0.01129864,0.0004884985
|
|
7
|
+
clean,clean_full_space_share,clipped_pc90_adjusted,200,0.02796016,0.0007953094
|
|
8
|
+
clean,clean_full_space_share,pc90_adjusted,200,0.0274132,0.0007907256
|
|
9
|
+
clean,clean_full_space_share,raw_partial,200,0.01745223,0.0006364287
|
|
10
|
+
injection_outliers,assay_unit_shift,combined,200,0.3331197,0.00470123
|
|
11
|
+
injection_outliers,assay_unit_shift,reference_mean,200,0.4125539,0.003140322
|
|
12
|
+
injection_outliers,assay_unit_shift,reference_median,200,0.4856236,0.00395442
|
|
13
|
+
injection_outliers,assay_unit_shift,study,200,0.5399922,0.02078124
|
|
14
|
+
injection_outliers,clean_full_space_share,adjusted_partial,200,0.1220579,0.001857256
|
|
15
|
+
injection_outliers,clean_full_space_share,clipped_pc90_adjusted,200,0.07259726,0.00234741
|
|
16
|
+
injection_outliers,clean_full_space_share,pc90_adjusted,200,0.1192871,0.00200845
|
|
17
|
+
injection_outliers,clean_full_space_share,raw_partial,200,0.1100152,0.001794485
|
|
18
|
+
null,assay_unit_shift,combined,200,0.2199353,0.001654302
|
|
19
|
+
null,assay_unit_shift,reference_mean,200,0.4088141,0.003451397
|
|
20
|
+
null,assay_unit_shift,reference_median,200,0.4913875,0.004056386
|
|
21
|
+
null,assay_unit_shift,study,200,0.2552101,0.001862417
|
|
22
|
+
null,clean_full_space_share,adjusted_partial,200,0.002626098,0.0001585579
|
|
23
|
+
null,clean_full_space_share,clipped_pc90_adjusted,200,0.002998614,0.0001833526
|
|
24
|
+
null,clean_full_space_share,pc90_adjusted,200,0.002986331,0.0001834377
|
|
25
|
+
null,clean_full_space_share,raw_partial,200,0.01278906,0.0001908872
|
|
26
|
+
reference_mismatch,assay_unit_shift,combined,200,0.3278556,0.001994849
|
|
27
|
+
reference_mismatch,assay_unit_shift,reference_mean,200,0.8956068,0.004398814
|
|
28
|
+
reference_mismatch,assay_unit_shift,reference_median,200,0.9364538,0.004932073
|
|
29
|
+
reference_mismatch,assay_unit_shift,study,200,0.2588727,0.001980768
|
|
30
|
+
reference_mismatch,clean_full_space_share,adjusted_partial,200,0.0117122,0.0005686548
|
|
31
|
+
reference_mismatch,clean_full_space_share,clipped_pc90_adjusted,200,0.02761676,0.0009053557
|
|
32
|
+
reference_mismatch,clean_full_space_share,pc90_adjusted,200,0.02700928,0.000901351
|
|
33
|
+
reference_mismatch,clean_full_space_share,raw_partial,200,0.01730645,0.0007214039
|
|
34
|
+
wave_residuals,assay_unit_shift,combined,200,0.2204247,0.00414292
|
|
35
|
+
wave_residuals,assay_unit_shift,reference_mean,200,0.4011259,0.007938038
|
|
36
|
+
wave_residuals,assay_unit_shift,reference_median,200,0.4428172,0.009137483
|
|
37
|
+
wave_residuals,assay_unit_shift,study,200,0.2604434,0.005032647
|
|
38
|
+
wave_residuals,clean_full_space_share,adjusted_partial,200,0.03418749,0.001903561
|
|
39
|
+
wave_residuals,clean_full_space_share,clipped_pc90_adjusted,200,0.04946981,0.002422175
|
|
40
|
+
wave_residuals,clean_full_space_share,pc90_adjusted,200,0.04507473,0.002371742
|
|
41
|
+
wave_residuals,clean_full_space_share,raw_partial,200,0.03597036,0.001953385
|