maxcombat 0.1.2__py3-none-any.whl
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.
Potentially problematic release.
This version of maxcombat might be problematic. Click here for more details.
- maxcombat/__init__.py +3 -0
- maxcombat/cli.py +208 -0
- maxcombat/core.py +572 -0
- maxcombat/utils.py +109 -0
- maxcombat-0.1.2.dist-info/METADATA +141 -0
- maxcombat-0.1.2.dist-info/RECORD +10 -0
- maxcombat-0.1.2.dist-info/WHEEL +5 -0
- maxcombat-0.1.2.dist-info/entry_points.txt +2 -0
- maxcombat-0.1.2.dist-info/licenses/LICENSE +21 -0
- maxcombat-0.1.2.dist-info/top_level.txt +1 -0
maxcombat/__init__.py
ADDED
maxcombat/cli.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Written by Olivier Coen. Released under the MIT license.
|
|
3
|
+
|
|
4
|
+
"""cli.py: thin command-line interface around maxcombat."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
from multiprocessing import cpu_count
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
# ------------------------------------------------------------
|
|
15
|
+
# CONSTANTS
|
|
16
|
+
# ------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
DEFAULT_NJOBS = 8
|
|
19
|
+
|
|
20
|
+
# --------------------------------------------------------------
|
|
21
|
+
# PARSE ARGUMENTS
|
|
22
|
+
# --------------------------------------------------------------
|
|
23
|
+
|
|
24
|
+
def parse_args() -> argparse.Namespace:
|
|
25
|
+
parser = argparse.ArgumentParser(description="maxcombat: scalable batch-effect correction largely based on reComBat")
|
|
26
|
+
parser.add_argument(
|
|
27
|
+
"--counts", type=Path, dest="count_file", required=True,
|
|
28
|
+
help="Parquet gathering all count data (genes as rows, samples as columns)"
|
|
29
|
+
)
|
|
30
|
+
parser.add_argument(
|
|
31
|
+
"--design", type=Path, dest="design_file", required=True,
|
|
32
|
+
help="CSV design file with 'sample' and 'batch' columns"
|
|
33
|
+
)
|
|
34
|
+
parser.add_argument(
|
|
35
|
+
"--gene-id-colname", type=str, dest="gene_id_col",
|
|
36
|
+
help="Name of the gene ID column in the counts file",
|
|
37
|
+
)
|
|
38
|
+
parser.add_argument(
|
|
39
|
+
"--model", help="Regression model used to standardize the data"
|
|
40
|
+
)
|
|
41
|
+
parser.add_argument(
|
|
42
|
+
"--parametric", action=argparse.BooleanOptionalAction, default=True,
|
|
43
|
+
help="Parametric (default) or --no-parametric empirical Bayes optimization"
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument(
|
|
46
|
+
"--config", type=Path, dest="config_file",
|
|
47
|
+
help="JSON file with keyword arguments for the scikit-learn regressor"
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"--conv-criterion", dest="conv_criterion", type=float,
|
|
51
|
+
help="Relative convergence criterion (default 1e-4)"
|
|
52
|
+
)
|
|
53
|
+
parser.add_argument(
|
|
54
|
+
"--max-iter", dest="max_iter", type=int,
|
|
55
|
+
help="Maximum number of iterations (default 1000)"
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"--mean-only", dest="mean_only", action="store_true",
|
|
59
|
+
help="Adjust the mean only, no scaling"
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--clip-negative-values", dest="clip_negative_values", action="store_true",
|
|
63
|
+
help="Clip negative output values to 0"
|
|
64
|
+
)
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"--reference-batch", dest="reference_batch", default=None,
|
|
67
|
+
help="Batch label left unadjusted. Defaults to None (all batches adjusted)",
|
|
68
|
+
)
|
|
69
|
+
parser.add_argument(
|
|
70
|
+
"--optimize-params", dest="optimize_params",
|
|
71
|
+
action=argparse.BooleanOptionalAction, default=True,
|
|
72
|
+
help="Perform empirical Bayes optimization (default). Use --no-optimize-params to skip it",
|
|
73
|
+
)
|
|
74
|
+
parser.add_argument(
|
|
75
|
+
"--x-covariates", dest="x_covariates_file", type=Path, default=None,
|
|
76
|
+
help="CSV with a 'sample' column plus covariates of desired variation (e.g. condition). Categorical columns are one-hot encoded (first level dropped)",
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument(
|
|
79
|
+
"--c-covariates", dest="c_covariates_file", type=Path, default=None,
|
|
80
|
+
help="CSV with a 'sample' column plus covariates of unwanted variation (e.g. RIN, sex). Categorical columns are one-hot encoded (first level dropped)",
|
|
81
|
+
)
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"--out-f32", dest="cast_output_to_float32",
|
|
84
|
+
help="Cast corrected data to float32 before export to save memory",
|
|
85
|
+
)
|
|
86
|
+
parser.add_argument(
|
|
87
|
+
"--out", type=Path, dest="outfile", required=True,
|
|
88
|
+
help="Output Parquet file"
|
|
89
|
+
)
|
|
90
|
+
parser.add_argument(
|
|
91
|
+
"--cpus", type=int,
|
|
92
|
+
help="Number of threads for numpy/polars. Defaults to min(8, <number of available cores>"
|
|
93
|
+
)
|
|
94
|
+
return parser.parse_args()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# --------------------------------------------------------------
|
|
98
|
+
# OTHER IMPORTS + LIMITATION OF THREADS USED BY NUMPY / POLARS
|
|
99
|
+
# --------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
args = parse_args()
|
|
102
|
+
|
|
103
|
+
# Limit thread usage; must be set before importing numpy-heavy libs.
|
|
104
|
+
n_cpus = args.cpus or min(DEFAULT_NJOBS, cpu_count())
|
|
105
|
+
os.environ.update({
|
|
106
|
+
"OMP_NUM_THREADS": str(n_cpus),
|
|
107
|
+
"OPENBLAS_NUM_THREADS": str(n_cpus),
|
|
108
|
+
"MKL_NUM_THREADS": str(n_cpus),
|
|
109
|
+
"NUMEXPR_NUM_THREADS": str(n_cpus),
|
|
110
|
+
"POLARS_MAX_THREADS": str(n_cpus),
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
import numpy as np # noqa: E402
|
|
114
|
+
import polars as pl # noqa: E402
|
|
115
|
+
|
|
116
|
+
from maxcombat.core import ReComBat # noqa: E402
|
|
117
|
+
from maxcombat.utils import parse_table, build_covariates, parse_config, export
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# --------------------------------------------------------------
|
|
121
|
+
# MAIN
|
|
122
|
+
# --------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
def main() -> None:
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
|
|
128
|
+
logger = logging.getLogger("maxcombat-cli")
|
|
129
|
+
|
|
130
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
131
|
+
# READ AND ALIGN
|
|
132
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
133
|
+
|
|
134
|
+
logger.info(f"Parsing counts from {args.count_file}")
|
|
135
|
+
counts, gene_id_col = parse_table(args.count_file, args.gene_id_col)
|
|
136
|
+
logger.info(f"Getting design from {args.design_file}")
|
|
137
|
+
design = pl.read_csv(args.design_file)
|
|
138
|
+
|
|
139
|
+
samples = [c for c in counts.columns if c != gene_id_col]
|
|
140
|
+
gene_ids = counts.select(gene_id_col)
|
|
141
|
+
counts = counts.drop(gene_id_col)
|
|
142
|
+
|
|
143
|
+
# taking only the subpart of the design that corresponds to the count data
|
|
144
|
+
design = design.filter(pl.col('sample').is_in(samples))
|
|
145
|
+
|
|
146
|
+
data = counts.to_numpy() # (n_genes, n_samples)
|
|
147
|
+
batches = design["batch"].to_numpy()
|
|
148
|
+
|
|
149
|
+
# parsing covariates if provided
|
|
150
|
+
x_covariates = build_covariates(args.x_covariates_file, samples) if args.x_covariates_file else None
|
|
151
|
+
c_covariates = build_covariates(args.c_covariates_file, samples) if args.c_covariates_file else None
|
|
152
|
+
|
|
153
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
154
|
+
# BATCH CORRECTION
|
|
155
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
156
|
+
|
|
157
|
+
if np.unique(batches).size == 1:
|
|
158
|
+
logger.info("Only one batch found. Skipping batch correction.")
|
|
159
|
+
corrected = data
|
|
160
|
+
|
|
161
|
+
else:
|
|
162
|
+
model = ReComBat(
|
|
163
|
+
parametric=args.parametric, # False if --no-parametric is provided
|
|
164
|
+
model=args.model,
|
|
165
|
+
config=parse_config(args.config_file),
|
|
166
|
+
conv_criterion=args.conv_criterion,
|
|
167
|
+
max_iter=args.max_iter,
|
|
168
|
+
mean_only=args.mean_only,
|
|
169
|
+
optimize_params=args.optimize_params,
|
|
170
|
+
reference_batch=args.reference_batch,
|
|
171
|
+
clip_negative_values=args.clip_negative_values,
|
|
172
|
+
n_jobs=n_cpus
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
corrected = model.fit_transform(
|
|
176
|
+
data,
|
|
177
|
+
batches,
|
|
178
|
+
X=x_covariates,
|
|
179
|
+
C=c_covariates,
|
|
180
|
+
sample_names=samples
|
|
181
|
+
) # (n_genes, n_samples)
|
|
182
|
+
|
|
183
|
+
# update new samples, removing orphans that were dropped
|
|
184
|
+
samples = [s for s, k in zip(samples, model.keep_mask_) if k]
|
|
185
|
+
assert corrected.shape[1] == len(samples)
|
|
186
|
+
|
|
187
|
+
# post-processing (clipping negative values if needed)
|
|
188
|
+
corrected = model.post_process(corrected)
|
|
189
|
+
|
|
190
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
191
|
+
# POSTPROCESSING AND EXPORT
|
|
192
|
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
193
|
+
|
|
194
|
+
out_df = pl.DataFrame(corrected, schema=samples)
|
|
195
|
+
if args.cast_output_to_float32:
|
|
196
|
+
out_df = out_df.select(pl.all().cast(pl.Float32))
|
|
197
|
+
|
|
198
|
+
out_df = pl.concat([gene_ids, out_df], how="horizontal")
|
|
199
|
+
|
|
200
|
+
logger.info(f"Exporting corrected counts to {args.outfile}")
|
|
201
|
+
export(out_df, args.outfile)
|
|
202
|
+
|
|
203
|
+
logger.info("Done")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
if __name__ == "__main__":
|
|
208
|
+
main()
|
maxcombat/core.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""reComBat: regularised ComBat batch-effect correction, NumPy-only edition.
|
|
3
|
+
|
|
4
|
+
# Author: Michael F. Adamer (https://github.com/BorgwardtLab/reComBat)
|
|
5
|
+
# Modernized by Olivier Coen & Mistral.
|
|
6
|
+
# Changed:
|
|
7
|
+
# - pandas removed, all replaced by NumPy arrays only
|
|
8
|
+
# - genes as rows, samples as columns
|
|
9
|
+
# - 'ElasticNet' as default model
|
|
10
|
+
# - bug fixes and type hints.
|
|
11
|
+
# - restrict the number of jobs to min(<all CPUs>, 8) by default
|
|
12
|
+
# Added:
|
|
13
|
+
# - drop orphan samples (samples that are alone in their batch) before fitting
|
|
14
|
+
# - optional: clip negative values (safety net for downstream analyses)
|
|
15
|
+
#
|
|
16
|
+
# Original BSD-3-Clause license applies,see THIRD_PARTY_NOTICES.md.
|
|
17
|
+
|
|
18
|
+
Convention
|
|
19
|
+
----------
|
|
20
|
+
- ``data``: (n_genes, n_samples) — genes as rows, samples as columns.
|
|
21
|
+
- ``batches``: (n_samples,) array of batch labels (any hashable, compared with ==).
|
|
22
|
+
- ``X``, ``C``: (n_samples, k) covariate matrices, already numerically encoded
|
|
23
|
+
(e.g. one-hot for categorical covariates). With the pandas version you passed
|
|
24
|
+
DataFrames with a ``_numerical`` postfix; build the encoded matrix yourself,
|
|
25
|
+
e.g. with ``sklearn.preprocessing.OneHotEncoder(drop="first")``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import inspect
|
|
31
|
+
import logging
|
|
32
|
+
import multiprocessing
|
|
33
|
+
import warnings
|
|
34
|
+
from typing import Any
|
|
35
|
+
|
|
36
|
+
import numpy as np
|
|
37
|
+
import numpy.typing as npt
|
|
38
|
+
from joblib import Parallel, delayed
|
|
39
|
+
from sklearn.linear_model import ElasticNet, Lasso, LinearRegression, Ridge
|
|
40
|
+
from tqdm import tqdm
|
|
41
|
+
|
|
42
|
+
Array = npt.NDArray[np.float64]
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger("maxcombat")
|
|
45
|
+
|
|
46
|
+
_MODELS = {
|
|
47
|
+
"linear": LinearRegression,
|
|
48
|
+
"ridge": Ridge,
|
|
49
|
+
"lasso": Lasso,
|
|
50
|
+
"elastic_net": ElasticNet,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
CONFIG_DTYPES = {
|
|
54
|
+
"alpha": float,
|
|
55
|
+
"l1_ratio": float,
|
|
56
|
+
"max_iter": int,
|
|
57
|
+
"tol": float,
|
|
58
|
+
"random_state": int,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
DEFAULT_MODEL = "elastic_net"
|
|
62
|
+
DEFAULT_CONV_CRITERION = 1e-4
|
|
63
|
+
DEFAULT_MAX_ITER = 1000
|
|
64
|
+
|
|
65
|
+
DEFAULT_CONFIG = {
|
|
66
|
+
"alpha": 1e-9,
|
|
67
|
+
"copy_X": False,
|
|
68
|
+
"selection": "random",
|
|
69
|
+
"random_state": 42,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
DEFAULT_NJOBS = 8
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class ReComBat:
|
|
76
|
+
"""Regularised ComBat batch-effect corrector.
|
|
77
|
+
|
|
78
|
+
Parameters
|
|
79
|
+
----------
|
|
80
|
+
parametric : bool
|
|
81
|
+
Use parametric empirical Bayes optimization (True) or non-parametric (False).
|
|
82
|
+
model : str
|
|
83
|
+
Regression model used for standardization: "linear", "ridge", "lasso" or "elastic_net".
|
|
84
|
+
config : dict | None
|
|
85
|
+
Extra keyword arguments forwarded to the scikit-learn regressor.
|
|
86
|
+
conv_criterion : float
|
|
87
|
+
Relative convergence criterion of the parametric empirical Bayes optimization.
|
|
88
|
+
max_iter : int
|
|
89
|
+
Maximum number of steps of the parametric empirical Bayes optimization.
|
|
90
|
+
n_jobs : int | None
|
|
91
|
+
Number of parallel jobs in the non-parametric optimization. Defaults to min(<all CPUs>, 8)
|
|
92
|
+
mean_only : bool
|
|
93
|
+
Adjust the mean only, no scaling.
|
|
94
|
+
optimize_params : bool
|
|
95
|
+
Perform empirical Bayes optimization.
|
|
96
|
+
reference_batch
|
|
97
|
+
Batch label left unadjusted. None to adjust all batches.
|
|
98
|
+
verbose : bool
|
|
99
|
+
Enable info logging.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(
|
|
103
|
+
self,
|
|
104
|
+
parametric: bool = True,
|
|
105
|
+
model: str | None = None,
|
|
106
|
+
config: dict[str, Any] | None = None,
|
|
107
|
+
conv_criterion: float | None = None,
|
|
108
|
+
max_iter: int | None = None,
|
|
109
|
+
n_jobs: int | None = None,
|
|
110
|
+
mean_only: bool = False,
|
|
111
|
+
optimize_params: bool = True,
|
|
112
|
+
reference_batch: Any = None,
|
|
113
|
+
clip_negative_values: bool = False,
|
|
114
|
+
verbose: bool = True,
|
|
115
|
+
) -> None:
|
|
116
|
+
if model is not None and model not in _MODELS:
|
|
117
|
+
raise ValueError(f"Unknown model {model!r}, choose one of {sorted(_MODELS)}.")
|
|
118
|
+
self.parametric = parametric
|
|
119
|
+
self.model = model or DEFAULT_MODEL
|
|
120
|
+
self.config: dict[str, Any] = build_config(config, self.model)
|
|
121
|
+
self.conv_criterion = conv_criterion or DEFAULT_CONV_CRITERION
|
|
122
|
+
self.max_iter = max_iter or DEFAULT_MAX_ITER
|
|
123
|
+
self.n_jobs = n_jobs or min(DEFAULT_NJOBS, multiprocessing.cpu_count())
|
|
124
|
+
self.mean_only = mean_only
|
|
125
|
+
self.optimize_params = optimize_params
|
|
126
|
+
self.reference_batch = reference_batch
|
|
127
|
+
self.clip_negative_values = clip_negative_values
|
|
128
|
+
if not verbose:
|
|
129
|
+
logger.setLevel(logging.WARNING)
|
|
130
|
+
self._fitted = False
|
|
131
|
+
|
|
132
|
+
# ------------------------------------------------------------------
|
|
133
|
+
# Public API
|
|
134
|
+
# ------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
def fit(
|
|
137
|
+
self,
|
|
138
|
+
data: Array,
|
|
139
|
+
batches: npt.NDArray[Any],
|
|
140
|
+
X: Array | None = None,
|
|
141
|
+
C: Array | None = None,
|
|
142
|
+
sample_names: npt.NDArray[Any] | list | None = None,
|
|
143
|
+
) -> "ReComBat":
|
|
144
|
+
"""Fit maxcombat.
|
|
145
|
+
|
|
146
|
+
Samples that are alone in their batch (orphans) are dropped
|
|
147
|
+
automatically, together with the matching rows of X and C. The
|
|
148
|
+
boolean mask actually applied is exposed in ``self.keep_mask_`` so
|
|
149
|
+
callers can realign sample names afterwards.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
data : (n_genes, n_samples) array
|
|
154
|
+
batches : (n_samples,) array of batch labels, aligned on data columns
|
|
155
|
+
X : (n_samples, k) array, optional — covariates of desired variation
|
|
156
|
+
C : (n_samples, k) array, optional — covariates of unwanted variation
|
|
157
|
+
sample_names : (n_samples,) array, optional — sample labels, used only
|
|
158
|
+
for logging orphan-sample removal
|
|
159
|
+
"""
|
|
160
|
+
# --------------------------------------------------------------
|
|
161
|
+
# PREPROCESSING: drop orphan samples (batches with a single sample)
|
|
162
|
+
# --------------------------------------------------------------
|
|
163
|
+
orphans = find_orphan_samples(batches)
|
|
164
|
+
keep = np.ones(batches.shape[0], dtype=bool)
|
|
165
|
+
keep[orphans] = False
|
|
166
|
+
|
|
167
|
+
if orphans.size:
|
|
168
|
+
for idx in orphans:
|
|
169
|
+
name = sample_names[idx] if sample_names is not None else f"#{idx}"
|
|
170
|
+
warnings.warn(f"Sample {name} is alone in its batch. Removing this sample.")
|
|
171
|
+
data = data[:, keep]
|
|
172
|
+
batches = batches[keep]
|
|
173
|
+
X = X[keep] if X is not None else None
|
|
174
|
+
C = C[keep] if C is not None else None
|
|
175
|
+
logger.info(f"Removed {orphans.size} orphan samples.")
|
|
176
|
+
|
|
177
|
+
# Exposed so callers can realign sample names on the kept samples.
|
|
178
|
+
self.keep_mask_ = keep
|
|
179
|
+
|
|
180
|
+
if data.shape[1] == 0:
|
|
181
|
+
raise ValueError("No samples left after removing orphan samples.")
|
|
182
|
+
|
|
183
|
+
data_sxg = self._validate(data, batches, X, C)
|
|
184
|
+
logger.info("Fitting maxcombat.")
|
|
185
|
+
|
|
186
|
+
unique_batches, batches_one_hot = self._one_hot(batches)
|
|
187
|
+
|
|
188
|
+
if self.reference_batch is not None:
|
|
189
|
+
if self.reference_batch not in unique_batches:
|
|
190
|
+
warnings.warn("Reference batch %r not found; adjusting all batches.", self.reference_batch)
|
|
191
|
+
else:
|
|
192
|
+
self._reference_batch_idx = int(np.flatnonzero(unique_batches == self.reference_batch)[0])
|
|
193
|
+
# True membership mask, independent of the one-hot trick below.
|
|
194
|
+
self._reference_sample_mask = batches == self.reference_batch
|
|
195
|
+
batches_one_hot[:, self._reference_batch_idx] = 1
|
|
196
|
+
|
|
197
|
+
logger.info("Fitting the linear model.")
|
|
198
|
+
Z = self._fit_model(data_sxg, batches_one_hot, X, C)
|
|
199
|
+
|
|
200
|
+
if self.optimize_params:
|
|
201
|
+
if self.parametric:
|
|
202
|
+
logger.info("Starting the parametric empirical Bayes optimization.")
|
|
203
|
+
self._parametric_optimization(Z, batches_one_hot)
|
|
204
|
+
else:
|
|
205
|
+
logger.info("Starting the non-parametric empirical Bayes optimization.")
|
|
206
|
+
self._non_parametric_optimization(Z, batches_one_hot)
|
|
207
|
+
else:
|
|
208
|
+
logger.info("Computing parameters without optimization.")
|
|
209
|
+
self.gamma_star_hat_, self.delta_star_squared_hat_ = self._initial_values(Z, batches_one_hot)
|
|
210
|
+
|
|
211
|
+
if self.reference_batch is not None and self.reference_batch in unique_batches:
|
|
212
|
+
self.gamma_star_hat_[self._reference_batch_idx] = 1.0
|
|
213
|
+
self.delta_star_squared_hat_[self._reference_batch_idx] = 1.0
|
|
214
|
+
|
|
215
|
+
self._fitted = True
|
|
216
|
+
logger.info("maxcombat fitted.")
|
|
217
|
+
return self
|
|
218
|
+
|
|
219
|
+
def transform(
|
|
220
|
+
self,
|
|
221
|
+
data: Array,
|
|
222
|
+
batches: npt.NDArray[Any],
|
|
223
|
+
X: Array | None = None,
|
|
224
|
+
C: Array | None = None
|
|
225
|
+
) -> Array:
|
|
226
|
+
"""Adjust data. Batch labels, covariates and gene count must match the fitted model."""
|
|
227
|
+
if not self._fitted:
|
|
228
|
+
raise AttributeError("reComBat has not been fitted yet. Call fit() first.")
|
|
229
|
+
data_sxg = self._validate(data, batches, X, C)
|
|
230
|
+
if data_sxg.shape[1] != self.alpha_.shape[1]:
|
|
231
|
+
raise ValueError("Wrong number of genes.")
|
|
232
|
+
|
|
233
|
+
unique_batches, batches_one_hot = self._one_hot(batches)
|
|
234
|
+
if batches_one_hot.shape[1] != self.gamma_star_hat_.shape[0]:
|
|
235
|
+
raise ValueError("Wrong number of batches.")
|
|
236
|
+
if self.reference_batch is not None and self.reference_batch in unique_batches:
|
|
237
|
+
batches_one_hot[:, self._reference_batch_idx] = 1
|
|
238
|
+
|
|
239
|
+
X_tmp = X @ self.beta_x_ if X is not None else 0.0
|
|
240
|
+
C_tmp = C @ self.beta_c_ if C is not None else 0.0 # fixed: original used beta_x_ here
|
|
241
|
+
|
|
242
|
+
Z = (data_sxg - self.alpha_ - X_tmp - C_tmp) / np.sqrt(self.sigma_)
|
|
243
|
+
adjusted_sxg = self._adjust_data(Z, batches_one_hot, X)
|
|
244
|
+
|
|
245
|
+
if self.reference_batch is not None:
|
|
246
|
+
reference_samples = batches == self.reference_batch
|
|
247
|
+
adjusted_sxg[reference_samples] = data_sxg[reference_samples]
|
|
248
|
+
|
|
249
|
+
logger.info("Transform finished.")
|
|
250
|
+
return adjusted_sxg.T # back to (n_genes, n_samples)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def fit_transform(
|
|
254
|
+
self,
|
|
255
|
+
data: Array,
|
|
256
|
+
batches: npt.NDArray[Any],
|
|
257
|
+
X: Array | None = None,
|
|
258
|
+
C: Array | None = None,
|
|
259
|
+
sample_names: npt.NDArray[Any] | list | None = None,
|
|
260
|
+
) -> Array:
|
|
261
|
+
"""Fit, then adjust data in one go.
|
|
262
|
+
|
|
263
|
+
Orphan samples are dropped inside ``fit``; the returned array has
|
|
264
|
+
``keep_mask_.sum()`` columns, in the original column order.
|
|
265
|
+
"""
|
|
266
|
+
return self.fit(data, batches, X=X, C=C, sample_names=sample_names).transform(
|
|
267
|
+
data[:, self.keep_mask_],
|
|
268
|
+
batches[self.keep_mask_],
|
|
269
|
+
X=X[self.keep_mask_] if X is not None else None,
|
|
270
|
+
C=C[self.keep_mask_] if C is not None else None,
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def post_process(self, data: Array) -> Array:
|
|
275
|
+
"""Post-process data after correction."""
|
|
276
|
+
corrected = data
|
|
277
|
+
if self.clip_negative_values:
|
|
278
|
+
logger.info("Clipping negative values to 0")
|
|
279
|
+
total = data.size
|
|
280
|
+
corrected, n_clipped = clip_negative_values(data)
|
|
281
|
+
logger.info(f"Clipped {n_clipped} ({100 * n_clipped / max(total, 1):.2f}%) negative values to 0")
|
|
282
|
+
return corrected
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# ------------------------------------------------------------------
|
|
286
|
+
# Validation and encoding
|
|
287
|
+
# ------------------------------------------------------------------
|
|
288
|
+
|
|
289
|
+
@staticmethod
|
|
290
|
+
def _validate(
|
|
291
|
+
data: Array,
|
|
292
|
+
batches: npt.NDArray[Any],
|
|
293
|
+
X: Array | None = None,
|
|
294
|
+
C: Array | None = None
|
|
295
|
+
) -> Array:
|
|
296
|
+
data = np.asarray(data, dtype=float)
|
|
297
|
+
batches = np.asarray(batches)
|
|
298
|
+
if data.ndim != 2:
|
|
299
|
+
raise ValueError(f"data must be 2D (n_genes, n_samples), got {data.ndim}D.")
|
|
300
|
+
if data.shape[1] != batches.shape[0]:
|
|
301
|
+
raise ValueError("data has a different number of samples than batches.")
|
|
302
|
+
if np.isnan(data).any():
|
|
303
|
+
raise ValueError("The data contains NaN values.")
|
|
304
|
+
if batches.shape[0] and np.array([b is None or (isinstance(b, float) and np.isnan(b)) for b in batches]).any():
|
|
305
|
+
raise ValueError("The batches contain NaN values.")
|
|
306
|
+
for name, M in (("X", X), ("C", C)):
|
|
307
|
+
if M is None:
|
|
308
|
+
continue
|
|
309
|
+
M = np.asarray(M, dtype=float)
|
|
310
|
+
if M.shape[0] != data.shape[1]:
|
|
311
|
+
raise ValueError(f"Design matrix {name} has a different number of samples than data.")
|
|
312
|
+
if np.isnan(M).any():
|
|
313
|
+
raise ValueError(f"The design matrix {name} contains NaN values.")
|
|
314
|
+
data_sxg = data.T # (n_samples, n_genes)
|
|
315
|
+
if np.unique(batches).size < 2:
|
|
316
|
+
raise ValueError("There should be at least two batches in the dataset.")
|
|
317
|
+
return data_sxg
|
|
318
|
+
|
|
319
|
+
@staticmethod
|
|
320
|
+
def _one_hot(batches: npt.NDArray[Any]) -> tuple[npt.NDArray[Any], Array]:
|
|
321
|
+
unique_batches = np.unique(batches)
|
|
322
|
+
batches_one_hot = (batches[:, None] == unique_batches[None, :]).astype(float)
|
|
323
|
+
if np.any(batches_one_hot.sum(axis=0) == 1):
|
|
324
|
+
raise ValueError("There should be at least two samples in each batch.")
|
|
325
|
+
return unique_batches, batches_one_hot
|
|
326
|
+
|
|
327
|
+
# ------------------------------------------------------------------
|
|
328
|
+
# Linear model
|
|
329
|
+
# ------------------------------------------------------------------
|
|
330
|
+
|
|
331
|
+
def _fit_model(
|
|
332
|
+
self,
|
|
333
|
+
data_sxg: Array,
|
|
334
|
+
batches_one_hot: Array,
|
|
335
|
+
X: Array | None,
|
|
336
|
+
C: Array | None
|
|
337
|
+
) -> Array:
|
|
338
|
+
n_batches = batches_one_hot.shape[1]
|
|
339
|
+
covariates = [batches_one_hot]
|
|
340
|
+
if X is not None:
|
|
341
|
+
covariates.append(np.asarray(X, dtype=float))
|
|
342
|
+
if C is not None:
|
|
343
|
+
covariates.append(np.asarray(C, dtype=float))
|
|
344
|
+
design = np.hstack(covariates)
|
|
345
|
+
design = np.atleast_2d(np.asarray(design, dtype=float))
|
|
346
|
+
x_dim = 0 if X is None else np.asarray(X, dtype=float).shape[1]
|
|
347
|
+
c_dim = 0 if C is None else np.asarray(C, dtype=float).shape[1]
|
|
348
|
+
|
|
349
|
+
regressor = _MODELS[self.model](fit_intercept=False, **self.config)
|
|
350
|
+
regressor.fit(design, data_sxg)
|
|
351
|
+
coef = regressor.coef_.T # (n_covariates, n_genes)
|
|
352
|
+
|
|
353
|
+
if self.reference_batch is None:
|
|
354
|
+
self.alpha_ = batches_one_hot.sum(axis=0, keepdims=True) @ coef[:n_batches] / batches_one_hot.sum()
|
|
355
|
+
else:
|
|
356
|
+
self.alpha_ = coef[self._reference_batch_idx][None, :]
|
|
357
|
+
self.beta_x_ = coef[n_batches : n_batches + x_dim]
|
|
358
|
+
self.beta_c_ = coef[n_batches + x_dim : n_batches + x_dim + c_dim]
|
|
359
|
+
|
|
360
|
+
data_hat = design @ coef
|
|
361
|
+
if self.reference_batch is None:
|
|
362
|
+
self.sigma_ = np.mean((data_sxg - data_hat) ** 2, axis=0, keepdims=True)
|
|
363
|
+
else:
|
|
364
|
+
mask = self._reference_sample_mask
|
|
365
|
+
self.sigma_ = np.mean((data_sxg[mask] - data_hat[mask]) ** 2, axis=0, keepdims=True)
|
|
366
|
+
|
|
367
|
+
Z = (
|
|
368
|
+
data_sxg
|
|
369
|
+
- (design[:, n_batches : n_batches + x_dim] @ self.beta_x_ if x_dim else 0.0)
|
|
370
|
+
- (design[:, n_batches + x_dim :] @ self.beta_c_ if c_dim else 0.0)
|
|
371
|
+
- self.alpha_
|
|
372
|
+
) / np.sqrt(self.sigma_)
|
|
373
|
+
return Z
|
|
374
|
+
|
|
375
|
+
# ------------------------------------------------------------------
|
|
376
|
+
# Empirical Bayes
|
|
377
|
+
# ------------------------------------------------------------------
|
|
378
|
+
|
|
379
|
+
@staticmethod
|
|
380
|
+
def _initial_values(Z: Array, batches_one_hot: Array) -> tuple[Array, Array]:
|
|
381
|
+
gamma_hat = np.vstack([Z[batches_one_hot[:, i] == 1].mean(axis=0) for i in range(batches_one_hot.shape[1])])
|
|
382
|
+
delta_hat_squared = np.vstack([Z[batches_one_hot[:, i] == 1].var(axis=0, ddof=1) for i in range(batches_one_hot.shape[1])])
|
|
383
|
+
return gamma_hat, delta_hat_squared
|
|
384
|
+
|
|
385
|
+
def _parametric_initial_values(self, Z: Array, batches_one_hot: Array):
|
|
386
|
+
gamma_hat, delta_hat_squared = self._initial_values(Z, batches_one_hot)
|
|
387
|
+
gamma_bar = gamma_hat.mean(axis=1)
|
|
388
|
+
tau_bar_squared = gamma_hat.var(axis=1, ddof=1)
|
|
389
|
+
v_bar = delta_hat_squared.mean(axis=1)
|
|
390
|
+
s_bar_squared = delta_hat_squared.var(axis=1, ddof=1)
|
|
391
|
+
lambda_bar = (v_bar**2 + 2 * s_bar_squared) / s_bar_squared
|
|
392
|
+
theta_bar = (v_bar**3 + v_bar * s_bar_squared) / s_bar_squared
|
|
393
|
+
return gamma_hat, gamma_bar, delta_hat_squared, tau_bar_squared, lambda_bar, theta_bar
|
|
394
|
+
|
|
395
|
+
@staticmethod
|
|
396
|
+
def _new_gamma(
|
|
397
|
+
n_i: float, # scalar
|
|
398
|
+
tau_bar_squared_i: float, # scalar
|
|
399
|
+
gamma_hat_i: Array, # (n_genes,)
|
|
400
|
+
delta_star_squared_i: Array, # (n_genes,)
|
|
401
|
+
gamma_bar_i: float, # scalar
|
|
402
|
+
) -> Array: # (n_genes,)
|
|
403
|
+
num = n_i * tau_bar_squared_i * gamma_hat_i + delta_star_squared_i * gamma_bar_i
|
|
404
|
+
den = n_i * tau_bar_squared_i + delta_star_squared_i
|
|
405
|
+
return num / den
|
|
406
|
+
|
|
407
|
+
@staticmethod
|
|
408
|
+
def _new_delta_star_squared(
|
|
409
|
+
theta_bar_i: float, # scalar
|
|
410
|
+
Z_i: Array, # (n_i, n_genes)
|
|
411
|
+
gamma_star_new_i: Array, # (n_genes,)
|
|
412
|
+
n_i: float, # scalar
|
|
413
|
+
lambda_bar_i: float, # scalar
|
|
414
|
+
) -> Array: # (n_genes,)
|
|
415
|
+
num = theta_bar_i + 0.5 * np.sum((Z_i - gamma_star_new_i) ** 2, axis=0)
|
|
416
|
+
den = 0.5 * n_i + lambda_bar_i - 1
|
|
417
|
+
return num / den
|
|
418
|
+
|
|
419
|
+
def _parametric_update(
|
|
420
|
+
self,
|
|
421
|
+
gamma_star_i: Array, # (n_genes,)
|
|
422
|
+
delta_star_squared_i: Array, # (n_genes,)
|
|
423
|
+
n_i: float, # scalar
|
|
424
|
+
tau_bar_squared_i: float, # scalar
|
|
425
|
+
gamma_hat_i: Array, # (n_genes,)
|
|
426
|
+
gamma_bar_i: float, # scalar
|
|
427
|
+
theta_bar_i: float, # scalar
|
|
428
|
+
lambda_bar_i: float, # scalar
|
|
429
|
+
Z_i: Array, # (n_i, n_genes)
|
|
430
|
+
) -> tuple[Array, Array]: # ((n_genes,), (n_genes,))
|
|
431
|
+
iterations = 0
|
|
432
|
+
convergence = self.conv_criterion + 1
|
|
433
|
+
while convergence > self.conv_criterion and iterations < self.max_iter:
|
|
434
|
+
gamma_star_new_i = self._new_gamma(n_i, tau_bar_squared_i, gamma_hat_i, delta_star_squared_i, gamma_bar_i)
|
|
435
|
+
delta_star_squared_new_i = self._new_delta_star_squared(theta_bar_i, Z_i, gamma_star_new_i, n_i, lambda_bar_i)
|
|
436
|
+
convergence = max(
|
|
437
|
+
np.max(np.abs(gamma_star_new_i - gamma_star_i) / gamma_star_i),
|
|
438
|
+
np.max(np.abs(delta_star_squared_new_i - delta_star_squared_i) / delta_star_squared_i),
|
|
439
|
+
)
|
|
440
|
+
gamma_star_i, delta_star_squared_i = gamma_star_new_i, delta_star_squared_new_i
|
|
441
|
+
iterations += 1
|
|
442
|
+
if iterations >= self.max_iter:
|
|
443
|
+
warnings.warn("Maximum number of iterations reached in the parametric optimization.", RuntimeWarning, stacklevel=2)
|
|
444
|
+
return gamma_star_i, delta_star_squared_i
|
|
445
|
+
|
|
446
|
+
def _parametric_optimization(self, Z: Array, batches_one_hot: Array) -> None:
|
|
447
|
+
gamma_hat, gamma_bar, delta_hat_squared, tau_bar_squared, lambda_bar, theta_bar = self._parametric_initial_values(Z, batches_one_hot)
|
|
448
|
+
n = batches_one_hot.sum(axis=0)
|
|
449
|
+
gamma_star = gamma_hat.copy()
|
|
450
|
+
delta_star_squared = delta_hat_squared.copy()
|
|
451
|
+
for i in range(batches_one_hot.shape[1]):
|
|
452
|
+
if self.mean_only:
|
|
453
|
+
gamma_star[i] = self._new_gamma(1, tau_bar_squared[i], gamma_hat[i], 1.0, gamma_bar[i])
|
|
454
|
+
delta_star_squared[i] = np.ones_like(delta_hat_squared[i])
|
|
455
|
+
else:
|
|
456
|
+
gamma_star[i], delta_star_squared[i] = self._parametric_update(
|
|
457
|
+
gamma_star[i], delta_star_squared[i], n[i], tau_bar_squared[i],
|
|
458
|
+
gamma_hat[i], gamma_bar[i], theta_bar[i], lambda_bar[i],
|
|
459
|
+
Z[batches_one_hot[:, i] == 1],
|
|
460
|
+
)
|
|
461
|
+
self.gamma_star_hat_ = gamma_star
|
|
462
|
+
self.delta_star_squared_hat_ = delta_star_squared
|
|
463
|
+
logger.info("Optimization finished.")
|
|
464
|
+
|
|
465
|
+
# ------------------------------------------------------------------
|
|
466
|
+
# Non-parametric optimization
|
|
467
|
+
# ------------------------------------------------------------------
|
|
468
|
+
|
|
469
|
+
@staticmethod
|
|
470
|
+
def _weights_for_gene(
|
|
471
|
+
g: int,
|
|
472
|
+
Z_ig: Array, # (n_i,)
|
|
473
|
+
gamma_hat_i: Array, # (n_genes,)
|
|
474
|
+
delta_hat_squared_i: Array, # (n_genes,)
|
|
475
|
+
) -> Array: # (n_genes - 1,)
|
|
476
|
+
tmp = (Z_ig.reshape(-1, 1) - np.delete(gamma_hat_i, g)) ** 2 / np.delete(delta_hat_squared_i, g)
|
|
477
|
+
return np.prod((1 / np.sqrt(2 * np.pi * np.delete(delta_hat_squared_i, g))) * np.exp(-0.5 * tmp), axis=0)
|
|
478
|
+
|
|
479
|
+
def _compute_weights(
|
|
480
|
+
self,
|
|
481
|
+
Z_i: Array, # (n_i, n_genes)
|
|
482
|
+
gamma_hat_i: Array, # (n_genes,)
|
|
483
|
+
delta_hat_squared_i: Array, # (n_genes,)
|
|
484
|
+
) -> Array: # (n_genes, n_genes - 1)
|
|
485
|
+
return np.vstack(
|
|
486
|
+
Parallel(n_jobs=self.n_jobs)(
|
|
487
|
+
delayed(self._weights_for_gene)(g, Z_i[:, g], gamma_hat_i, delta_hat_squared_i)
|
|
488
|
+
for g in range(Z_i.shape[1])
|
|
489
|
+
)
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
def _non_parametric_optimization(self, Z: Array, batches_one_hot: Array) -> None:
|
|
493
|
+
gamma_hat, delta_hat_squared = self._initial_values(Z, batches_one_hot)
|
|
494
|
+
gamma_star = np.zeros_like(gamma_hat)
|
|
495
|
+
delta_star_squared = np.zeros_like(delta_hat_squared)
|
|
496
|
+
for i in tqdm(range(batches_one_hot.shape[1]), desc="Non-parametric optimization", disable=not logger.isEnabledFor(logging.INFO)):
|
|
497
|
+
if self.mean_only:
|
|
498
|
+
delta_hat_squared[i] = np.ones_like(delta_hat_squared[i])
|
|
499
|
+
Z_i = Z[batches_one_hot[:, i] == 1]
|
|
500
|
+
weights = self._compute_weights(Z_i, gamma_hat[i], delta_hat_squared[i])
|
|
501
|
+
gamma_star[i] = (
|
|
502
|
+
np.vstack([weights[j] * np.delete(gamma_hat[i], j) for j in range(Z.shape[1])]).sum(axis=1)
|
|
503
|
+
/ weights.sum(axis=1)
|
|
504
|
+
)
|
|
505
|
+
delta_star_squared[i] = (
|
|
506
|
+
np.vstack([weights[j] * np.delete(delta_hat_squared[i], j) for j in range(Z.shape[1])]).sum(axis=1)
|
|
507
|
+
/ weights.sum(axis=1)
|
|
508
|
+
)
|
|
509
|
+
self.gamma_star_hat_ = gamma_star
|
|
510
|
+
self.delta_star_squared_hat_ = delta_star_squared
|
|
511
|
+
logger.info("Optimization finished.")
|
|
512
|
+
|
|
513
|
+
# ------------------------------------------------------------------
|
|
514
|
+
# Adjustment
|
|
515
|
+
# ------------------------------------------------------------------
|
|
516
|
+
|
|
517
|
+
def _adjust_data(self, Z: Array, batches_one_hot: Array, X: Array | None) -> Array:
|
|
518
|
+
adjusted = np.zeros_like(Z)
|
|
519
|
+
for i in range(batches_one_hot.shape[1]):
|
|
520
|
+
mask = batches_one_hot[:, i] == 1
|
|
521
|
+
adjusted[mask] = (Z[mask] - self.gamma_star_hat_[i]) / np.sqrt(self.delta_star_squared_hat_[i])
|
|
522
|
+
adjusted = np.sqrt(self.sigma_) * adjusted + self.alpha_
|
|
523
|
+
if X is not None: # desired variation is added back
|
|
524
|
+
adjusted += np.asarray(X, dtype=float) @ self.beta_x_
|
|
525
|
+
return adjusted
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
# ----------------------------------------------------------------------
|
|
529
|
+
# Preprocessing helpers
|
|
530
|
+
# ----------------------------------------------------------------------
|
|
531
|
+
|
|
532
|
+
def build_config(config: dict | None, model: str) -> dict:
|
|
533
|
+
recombat_config = dict(DEFAULT_CONFIG)
|
|
534
|
+
if config is not None:
|
|
535
|
+
recombat_config.update(config)
|
|
536
|
+
# inspecting the model function signature to check if it accepts all params
|
|
537
|
+
sig = inspect.signature(_MODELS[model])
|
|
538
|
+
# cast config values to the dtypes declared in CONFIG_DTYPES
|
|
539
|
+
return {
|
|
540
|
+
key: CONFIG_DTYPES[key](value) if key in CONFIG_DTYPES else value
|
|
541
|
+
for key, value in recombat_config.items()
|
|
542
|
+
if key in sig.parameters
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
def find_orphan_samples(batches: npt.NDArray[Any]) -> npt.NDArray[np.int64]:
|
|
546
|
+
"""Return indices of samples belonging to a batch containing a single sample."""
|
|
547
|
+
batches = np.asarray(batches)
|
|
548
|
+
values, counts = np.unique(batches, return_counts=True)
|
|
549
|
+
orphans = np.flatnonzero(np.isin(batches, values[counts == 1]))
|
|
550
|
+
return orphans
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def drop_orphan_samples(
|
|
554
|
+
data: Array, batches: npt.NDArray[Any]
|
|
555
|
+
) -> tuple[Array, npt.NDArray[Any], npt.NDArray[np.int64]]:
|
|
556
|
+
"""Drop samples that are alone in their batch.
|
|
557
|
+
|
|
558
|
+
Returns (data, batches, dropped_indices)."""
|
|
559
|
+
orphans = find_orphan_samples(batches)
|
|
560
|
+
keep = np.ones(batches.shape[0], dtype=bool)
|
|
561
|
+
keep[orphans] = False
|
|
562
|
+
return data[:, keep], batches[keep], orphans
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
# ------------------------------------------------------------------
|
|
566
|
+
# Post-processing helpers
|
|
567
|
+
# ------------------------------------------------------------------
|
|
568
|
+
|
|
569
|
+
def clip_negative_values(data: Array) -> tuple[Array, int]:
|
|
570
|
+
"""Clip negative values to 0. Returns (clipped_data, n_clipped_values)."""
|
|
571
|
+
n_clipped = int((data < 0).sum())
|
|
572
|
+
return np.clip(data, 0.0, None), n_clipped
|
maxcombat/utils.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import gzip
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import polars as pl
|
|
4
|
+
import numpy as np
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
TEXTUAL_ALLOWED_FILE_FORMATS_TO_EXTENSIONS = {
|
|
9
|
+
".csv": ",",
|
|
10
|
+
".tsv": "\t"
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_header(file: Path, sep: str) -> list[str]:
|
|
15
|
+
"""Parse the header of a file, and return it as a list of strings."""
|
|
16
|
+
if file.suffix == ".gz":
|
|
17
|
+
fin = gzip.open(file, "rt")
|
|
18
|
+
else:
|
|
19
|
+
fin = open(file)
|
|
20
|
+
header = fin.readline().strip().split(sep)
|
|
21
|
+
first_row = fin.readline().strip().split(sep)
|
|
22
|
+
|
|
23
|
+
fin.close()
|
|
24
|
+
|
|
25
|
+
if len(header) != len(first_row):
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"Header has length: {len(header)} while first row has length: {len(first_row)}. Header: {header} / first row: {first_row}",
|
|
28
|
+
)
|
|
29
|
+
return header
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_table(file: Path, gene_id_col: str | None) -> tuple[pl.DataFrame, str]:
|
|
34
|
+
"""Parse a table file into a Polars DataFrame."""
|
|
35
|
+
# parsing header first
|
|
36
|
+
ext = file.suffixes[-2] if file.suffix == ".gz" else file.suffix
|
|
37
|
+
|
|
38
|
+
if ext == ".parquet":
|
|
39
|
+
df = pl.read_parquet(file)
|
|
40
|
+
if gene_id_col is None:
|
|
41
|
+
gene_id_col = df.columns[0]
|
|
42
|
+
|
|
43
|
+
elif ext in TEXTUAL_ALLOWED_FILE_FORMATS_TO_EXTENSIONS:
|
|
44
|
+
# parsing header manually
|
|
45
|
+
sep = TEXTUAL_ALLOWED_FILE_FORMATS_TO_EXTENSIONS[ext]
|
|
46
|
+
header = parse_header(file, sep)
|
|
47
|
+
if gene_id_col is None:
|
|
48
|
+
gene_id_col = header[0]
|
|
49
|
+
df = pl.read_csv(
|
|
50
|
+
file,
|
|
51
|
+
schema_overrides={gene_id_col: pl.String()},
|
|
52
|
+
separator=sep,
|
|
53
|
+
has_header=False,
|
|
54
|
+
skip_rows=1,
|
|
55
|
+
new_columns=header,
|
|
56
|
+
null_values=["NA", "N/A", "na", "n/a"],
|
|
57
|
+
)
|
|
58
|
+
else:
|
|
59
|
+
raise ValueError(f"Unsupported file format: {ext}")
|
|
60
|
+
|
|
61
|
+
return df, gene_id_col
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def build_covariates(covariates_file: Path, samples: list[str]) -> np.ndarray:
|
|
66
|
+
"""Load a covariates CSV, align it on the counts samples and one-hot
|
|
67
|
+
encode the categorical columns (first level dropped, as in the pandas
|
|
68
|
+
version of reComBat). Returns a (n_samples, k) float array."""
|
|
69
|
+
df = pl.read_csv(covariates_file)
|
|
70
|
+
if "sample" not in df.columns:
|
|
71
|
+
raise ValueError(f"{covariates_file} must contain a 'sample' column.")
|
|
72
|
+
covariate_cols = [c for c in df.columns if c != "sample"]
|
|
73
|
+
|
|
74
|
+
# Align on the counts samples, same order, missing = error.
|
|
75
|
+
df = pl.DataFrame({"sample": samples}).join(df, on="sample", how="left")
|
|
76
|
+
missing = df.filter(pl.any_horizontal(pl.col(c).is_null() for c in covariate_cols))["sample"].to_list()
|
|
77
|
+
if missing:
|
|
78
|
+
raise ValueError(f"Covariates are missing for samples: {missing}.")
|
|
79
|
+
|
|
80
|
+
blocks = []
|
|
81
|
+
for col in covariate_cols:
|
|
82
|
+
s = df[col]
|
|
83
|
+
if s.dtype == pl.String or s.dtype == pl.Categorical:
|
|
84
|
+
levels = s.unique().sort().to_list()
|
|
85
|
+
# one-hot with first level dropped (reference level)
|
|
86
|
+
one_hot = np.column_stack([(s == level).to_numpy() for level in levels[1:]]).astype(float)
|
|
87
|
+
blocks.append(one_hot)
|
|
88
|
+
else:
|
|
89
|
+
blocks.append(s.cast(pl.Float64).to_numpy().reshape(-1, 1))
|
|
90
|
+
return np.hstack(blocks).astype(float) if blocks else np.zeros((len(samples), 0))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse_config(config_file: Path | None) -> dict | None:
|
|
94
|
+
if config_file is None:
|
|
95
|
+
return None
|
|
96
|
+
with open(config_file) as f:
|
|
97
|
+
return json.load(f)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def export(df: pl.DataFrame, output_file: Path) -> None:
|
|
101
|
+
ext = output_file.suffix
|
|
102
|
+
if ext == ".csv":
|
|
103
|
+
df.write_csv(output_file, include_header=True)
|
|
104
|
+
if ext == ".tsv":
|
|
105
|
+
df.write_csv(output_file, separator="\t", include_header=True)
|
|
106
|
+
elif ext == ".parquet":
|
|
107
|
+
df.write_parquet(output_file)
|
|
108
|
+
else:
|
|
109
|
+
raise ValueError(f"Unhandled output format: {ext}. Use .csv, .tsv, or .parquet.")
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: maxcombat
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Scalable batch-effect correction largely based on reComBat
|
|
5
|
+
Author: Olivier Coen
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/OlivierCoen/maxcombat
|
|
8
|
+
Project-URL: Repository, https://github.com/OlivierCoen/maxcombat
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: numpy>=1.23
|
|
18
|
+
Requires-Dist: scikit-learn>=1.2
|
|
19
|
+
Requires-Dist: joblib>=1.2
|
|
20
|
+
Requires-Dist: tqdm>=4.64
|
|
21
|
+
Requires-Dist: polars>=0.21
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
24
|
+
Requires-Dist: ruff>=0.4; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# maxcombat
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/maxcombat/)
|
|
30
|
+
[]()
|
|
31
|
+
|
|
32
|
+
Scalable batch-effect correction largely based on [reComBat](https://github.com/BorgwardtLab/reComBat) (Michael F. Adamer, BSD-3-Clause).
|
|
33
|
+
|
|
34
|
+
This package is meant as a drop-in replacement for `reComBat`, whenever users need a high level of scalability.
|
|
35
|
+
|
|
36
|
+
## Features
|
|
37
|
+
|
|
38
|
+
- NumPy-only: no pandas dependency, arrays in, arrays out
|
|
39
|
+
- Genes as rows, samples as columns (the usual omics convention, unlike reComBat)
|
|
40
|
+
- All reComBat features: parametric and non-parametric empirical Bayes,
|
|
41
|
+
- linear / ridge / lasso / elastic net (default) standardization, covariates of desired (X) and unwanted (C) variation, reference batch, mean-only adjustment
|
|
42
|
+
- Automatic removal of orphan samples (samples alone in their batch)
|
|
43
|
+
- Optional clipping of negative output values (safety net for count data)
|
|
44
|
+
- Sensible default parallelism: min(8, number of CPUs) jobs
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install maxcombat
|
|
51
|
+
# or
|
|
52
|
+
conda install -c bioconda maxcombat
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Usage
|
|
56
|
+
|
|
57
|
+
### From Python
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
import numpy as np
|
|
62
|
+
from maxcombat import ReComBat
|
|
63
|
+
|
|
64
|
+
data = ... # (n_genes, n_samples) array
|
|
65
|
+
batches = ... # (n_samples,) array of batch labels
|
|
66
|
+
|
|
67
|
+
model = ReComBat(model="elastic_net")
|
|
68
|
+
corrected = model.fit_transform(data, batches)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Optional: with covariates and a reference batch:
|
|
72
|
+
```python
|
|
73
|
+
X = ... # (n_samples, k) covariates of desired variation, already encoded
|
|
74
|
+
C = ... # (n_samples, k) covariates of unwanted variation, already encoded
|
|
75
|
+
|
|
76
|
+
model = ReComBat(model="elastic_net", reference_batch="batch_1")
|
|
77
|
+
corrected = model.fit_transform(data, batches, X=X, C=C)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Categorical covariates must be one-hot encoded beforehand
|
|
81
|
+
(e.g. sklearn.preprocessing.OneHotEncoder(drop="first")); numerical
|
|
82
|
+
covariates are passed as is.
|
|
83
|
+
|
|
84
|
+
Non-parametric empirical Bayes (leave-one-out, more expensive):
|
|
85
|
+
```python
|
|
86
|
+
model = ReComBat(parametric=False, model="linear", n_jobs=8)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### From the command line
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
maxcombat \
|
|
94
|
+
--counts counts.parquet \
|
|
95
|
+
--design design.csv \
|
|
96
|
+
--out <path/to/output.file>
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
#### Mandatory arguments:
|
|
100
|
+
|
|
101
|
+
`--counts`: file in `parquet`, or `csv` / `tsv` (possibly gzipped) formats. The format is automatically detected. Genes must be provided as rows, samples as columns.
|
|
102
|
+
|
|
103
|
+
`--design`: CSV with sample and batch columns.
|
|
104
|
+
|
|
105
|
+
`--out`: path to output file; the format is parsed from the output file extension. Supported extensions: `.parquet`, `.csv`, `.tsv`.
|
|
106
|
+
|
|
107
|
+
#### Optional arguments:
|
|
108
|
+
|
|
109
|
+
`--model` (optional): sklearn model to use. Choose between: `linear`, `ridge`, `lasso`, `elastic_net`. Default: `elastic_net`.
|
|
110
|
+
|
|
111
|
+
`--no-parametric` (optional): switch to the non-parametric empirical Bayes optimization (default: false, ie. use the parametric mode)
|
|
112
|
+
|
|
113
|
+
`--gene-id-col` (optional): name of the column containing gene IDs (default: first column)
|
|
114
|
+
|
|
115
|
+
`--conv-criterion` (optional): Relative convergence criterion (default 1e-4)
|
|
116
|
+
|
|
117
|
+
`--max-iter` (optional): Maximum number of iterations (default 1000)
|
|
118
|
+
|
|
119
|
+
`--mean-only` (optional): Adjust the mean only, no scaling
|
|
120
|
+
|
|
121
|
+
`--x-covariates` / `--c-covariates` (optional): CSVs with a sample column plus covariate columns; categorical columns are one-hot encoded automatically (first level dropped).
|
|
122
|
+
|
|
123
|
+
`--reference-batch` (optional): batch label left unadjusted.
|
|
124
|
+
|
|
125
|
+
`--no-optimize-params` (optional): skip the empirical Bayes optimization.
|
|
126
|
+
|
|
127
|
+
`--cpus` : parallelism for the numerical backends / joblib.
|
|
128
|
+
|
|
129
|
+
`--clip-negative-values` (optional): clip negative values to 0 after correction (useful for specific downstream analyses requiring only positive values)
|
|
130
|
+
|
|
131
|
+
`--out-f32` (optional): convert corrected data to float32 before export
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
## Citation
|
|
135
|
+
|
|
136
|
+
If you use `maxcombat` for your analysis, please cite [the original reComBat paper](https://academic.oup.com/bioinformaticsadvances/article/2/1/vbac071/6728137?login=false).
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
MIT. This package incorporates code from reComBat (BSD-3-Clause),
|
|
141
|
+
see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
maxcombat/__init__.py,sha256=Io5V3DeaeHNYgdGRmZS-MSVaPoE9yXshDS4R4R_m9aI,96
|
|
2
|
+
maxcombat/cli.py,sha256=PUP8QKaeDyq5F0h9xeSp04atqT24ZnWqn-XMV_5HWUM,7613
|
|
3
|
+
maxcombat/core.py,sha256=3sfF67_wLMhTpakXXY0WqqXPMZ74kF1VllTF2AnTbhg,24509
|
|
4
|
+
maxcombat/utils.py,sha256=B5zH_xdgL8jQdo8v3nT30ayvLBwY26oxq1FuTOlciZo,3769
|
|
5
|
+
maxcombat-0.1.2.dist-info/licenses/LICENSE,sha256=Xr1zQCdehWiwBXTAIZ1vOemE8ipchzcMzLq_7gR_5c4,1069
|
|
6
|
+
maxcombat-0.1.2.dist-info/METADATA,sha256=lNC29SWGDXcbxx7MvV20Ewc3ntkCdM4OH5is03jf4Yk,4940
|
|
7
|
+
maxcombat-0.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
maxcombat-0.1.2.dist-info/entry_points.txt,sha256=zQgUwgamsapdeP_LS1yHLsHWLqnF6SPdqNkdiEQMNrs,49
|
|
9
|
+
maxcombat-0.1.2.dist-info/top_level.txt,sha256=yZIvsp8bV-P1htsP9fsc81hhpnjnjGWMcAPnyZanxp0,10
|
|
10
|
+
maxcombat-0.1.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Olivier Coen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
maxcombat
|