maxcombat 0.1.2__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.

Potentially problematic release.


This version of maxcombat might be problematic. Click here for more details.

@@ -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,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
+ [![Version](https://img.shields.io/pypi/v/recombat)](https://pypi.org/project/maxcombat/)
30
+ [![PythonVersion](https://img.shields.io/pypi/pyversions/maxcombat)]()
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,115 @@
1
+ # maxcombat
2
+
3
+ [![Version](https://img.shields.io/pypi/v/recombat)](https://pypi.org/project/maxcombat/)
4
+ [![PythonVersion](https://img.shields.io/pypi/pyversions/maxcombat)]()
5
+
6
+ Scalable batch-effect correction largely based on [reComBat](https://github.com/BorgwardtLab/reComBat) (Michael F. Adamer, BSD-3-Clause).
7
+
8
+ This package is meant as a drop-in replacement for `reComBat`, whenever users need a high level of scalability.
9
+
10
+ ## Features
11
+
12
+ - NumPy-only: no pandas dependency, arrays in, arrays out
13
+ - Genes as rows, samples as columns (the usual omics convention, unlike reComBat)
14
+ - All reComBat features: parametric and non-parametric empirical Bayes,
15
+ - linear / ridge / lasso / elastic net (default) standardization, covariates of desired (X) and unwanted (C) variation, reference batch, mean-only adjustment
16
+ - Automatic removal of orphan samples (samples alone in their batch)
17
+ - Optional clipping of negative output values (safety net for count data)
18
+ - Sensible default parallelism: min(8, number of CPUs) jobs
19
+
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install maxcombat
25
+ # or
26
+ conda install -c bioconda maxcombat
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ### From Python
32
+
33
+
34
+ ```python
35
+ import numpy as np
36
+ from maxcombat import ReComBat
37
+
38
+ data = ... # (n_genes, n_samples) array
39
+ batches = ... # (n_samples,) array of batch labels
40
+
41
+ model = ReComBat(model="elastic_net")
42
+ corrected = model.fit_transform(data, batches)
43
+ ```
44
+
45
+ Optional: with covariates and a reference batch:
46
+ ```python
47
+ X = ... # (n_samples, k) covariates of desired variation, already encoded
48
+ C = ... # (n_samples, k) covariates of unwanted variation, already encoded
49
+
50
+ model = ReComBat(model="elastic_net", reference_batch="batch_1")
51
+ corrected = model.fit_transform(data, batches, X=X, C=C)
52
+ ```
53
+
54
+ Categorical covariates must be one-hot encoded beforehand
55
+ (e.g. sklearn.preprocessing.OneHotEncoder(drop="first")); numerical
56
+ covariates are passed as is.
57
+
58
+ Non-parametric empirical Bayes (leave-one-out, more expensive):
59
+ ```python
60
+ model = ReComBat(parametric=False, model="linear", n_jobs=8)
61
+ ```
62
+
63
+ ### From the command line
64
+
65
+
66
+ ```bash
67
+ maxcombat \
68
+ --counts counts.parquet \
69
+ --design design.csv \
70
+ --out <path/to/output.file>
71
+ ```
72
+
73
+ #### Mandatory arguments:
74
+
75
+ `--counts`: file in `parquet`, or `csv` / `tsv` (possibly gzipped) formats. The format is automatically detected. Genes must be provided as rows, samples as columns.
76
+
77
+ `--design`: CSV with sample and batch columns.
78
+
79
+ `--out`: path to output file; the format is parsed from the output file extension. Supported extensions: `.parquet`, `.csv`, `.tsv`.
80
+
81
+ #### Optional arguments:
82
+
83
+ `--model` (optional): sklearn model to use. Choose between: `linear`, `ridge`, `lasso`, `elastic_net`. Default: `elastic_net`.
84
+
85
+ `--no-parametric` (optional): switch to the non-parametric empirical Bayes optimization (default: false, ie. use the parametric mode)
86
+
87
+ `--gene-id-col` (optional): name of the column containing gene IDs (default: first column)
88
+
89
+ `--conv-criterion` (optional): Relative convergence criterion (default 1e-4)
90
+
91
+ `--max-iter` (optional): Maximum number of iterations (default 1000)
92
+
93
+ `--mean-only` (optional): Adjust the mean only, no scaling
94
+
95
+ `--x-covariates` / `--c-covariates` (optional): CSVs with a sample column plus covariate columns; categorical columns are one-hot encoded automatically (first level dropped).
96
+
97
+ `--reference-batch` (optional): batch label left unadjusted.
98
+
99
+ `--no-optimize-params` (optional): skip the empirical Bayes optimization.
100
+
101
+ `--cpus` : parallelism for the numerical backends / joblib.
102
+
103
+ `--clip-negative-values` (optional): clip negative values to 0 after correction (useful for specific downstream analyses requiring only positive values)
104
+
105
+ `--out-f32` (optional): convert corrected data to float32 before export
106
+
107
+
108
+ ## Citation
109
+
110
+ 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).
111
+
112
+ ## License
113
+
114
+ MIT. This package incorporates code from reComBat (BSD-3-Clause),
115
+ see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "maxcombat"
7
+ version = "0.1.2"
8
+ description = "Scalable batch-effect correction largely based on reComBat"
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ authors = [{ name = "Olivier Coen" }]
12
+ requires-python = ">=3.10"
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Science/Research",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
19
+ ]
20
+ dependencies = [
21
+ "numpy>=1.23",
22
+ "scikit-learn>=1.2",
23
+ "joblib>=1.2",
24
+ "tqdm>=4.64",
25
+ "polars>=0.21"
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ dev = ["pytest>=7", "ruff>=0.4"]
30
+
31
+ [project.scripts]
32
+ maxcombat = "maxcombat.cli:main"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/OlivierCoen/maxcombat"
36
+ Repository = "https://github.com/OlivierCoen/maxcombat"
37
+
38
+ [tool.setuptools.packages.find]
39
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """maxcombat: scalable version of reComBat (batch effect correction)."""
2
+
3
+ __version__ = "0.1.0"
@@ -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()