maxcombat 0.2.3__tar.gz → 0.2.6__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: maxcombat
3
- Version: 0.2.3
3
+ Version: 0.2.6
4
4
  Summary: Scalable batch-effect correction based on reComBat
5
5
  Author: Olivier Coen
6
6
  License: MIT
@@ -59,6 +59,8 @@ pip install maxcombat
59
59
 
60
60
  ### From the command line
61
61
 
62
+ #### Basic usage
63
+
62
64
  ```bash
63
65
  maxcombat \
64
66
  --counts counts.parquet \
@@ -91,7 +93,18 @@ sample_E,batch_2
91
93
  > - the design dataframe may contain other columns, but only the `sample` and `batch` columns will be parsed
92
94
  > - batches containing only one sample are removed from the analysis
93
95
 
94
- Example of preserved covariates file:
96
+ #### Add preserved and dropped covariates
97
+
98
+ ```bash
99
+ maxcombat \
100
+ --counts counts.csv \
101
+ --design design.csv \
102
+ --out corrected_counts.csv \
103
+ --preserved-covariates preserved_covariate.csv \
104
+ --dropped-covariates dropped_covariate.csv
105
+ ```
106
+
107
+ Example of preserved (desired) covariates file:
95
108
 
96
109
  ```csv title=preserved_covariate.csv
97
110
  sample,condition,age
@@ -102,7 +115,7 @@ sample_D,control,29
102
115
  sample_E,control,63
103
116
  ```
104
117
 
105
- Example of unwated (dropped) covariates file:
118
+ Example of unwanted (dropped) covariates file:
106
119
 
107
120
  ```csv title=dropped_covariate.csv
108
121
  sample,rin
@@ -160,12 +173,12 @@ sample_E,6.9
160
173
  ```python
161
174
  from maxcombat import MaxCombat
162
175
 
163
- data = ... # (n_genes, n_samples) array
164
- batches = ... # (n_samples,) array of batch labels
176
+ data = ... # (n_genes, n_samples) array
177
+ batches = ... # (n_samples,) array of batch labels
165
178
 
166
- model = MaxCombat() # default model: elastic_net
167
- model.fit(data,batches)
168
- model.transform(data,batches)
179
+ model = MaxCombat() # default model: elastic_net
180
+ model.fit(data, batches)
181
+ model.transform(data, batches)
169
182
  ```
170
183
 
171
184
  or:
@@ -28,6 +28,8 @@ pip install maxcombat
28
28
 
29
29
  ### From the command line
30
30
 
31
+ #### Basic usage
32
+
31
33
  ```bash
32
34
  maxcombat \
33
35
  --counts counts.parquet \
@@ -60,7 +62,18 @@ sample_E,batch_2
60
62
  > - the design dataframe may contain other columns, but only the `sample` and `batch` columns will be parsed
61
63
  > - batches containing only one sample are removed from the analysis
62
64
 
63
- Example of preserved covariates file:
65
+ #### Add preserved and dropped covariates
66
+
67
+ ```bash
68
+ maxcombat \
69
+ --counts counts.csv \
70
+ --design design.csv \
71
+ --out corrected_counts.csv \
72
+ --preserved-covariates preserved_covariate.csv \
73
+ --dropped-covariates dropped_covariate.csv
74
+ ```
75
+
76
+ Example of preserved (desired) covariates file:
64
77
 
65
78
  ```csv title=preserved_covariate.csv
66
79
  sample,condition,age
@@ -71,7 +84,7 @@ sample_D,control,29
71
84
  sample_E,control,63
72
85
  ```
73
86
 
74
- Example of unwated (dropped) covariates file:
87
+ Example of unwanted (dropped) covariates file:
75
88
 
76
89
  ```csv title=dropped_covariate.csv
77
90
  sample,rin
@@ -129,12 +142,12 @@ sample_E,6.9
129
142
  ```python
130
143
  from maxcombat import MaxCombat
131
144
 
132
- data = ... # (n_genes, n_samples) array
133
- batches = ... # (n_samples,) array of batch labels
145
+ data = ... # (n_genes, n_samples) array
146
+ batches = ... # (n_samples,) array of batch labels
134
147
 
135
- model = MaxCombat() # default model: elastic_net
136
- model.fit(data,batches)
137
- model.transform(data,batches)
148
+ model = MaxCombat() # default model: elastic_net
149
+ model.fit(data, batches)
150
+ model.transform(data, batches)
138
151
  ```
139
152
 
140
153
  or:
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "maxcombat"
7
- version = "0.2.3"
7
+ version = "0.2.6"
8
8
  description = "Scalable batch-effect correction based on reComBat"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -27,7 +27,7 @@ dependencies = [
27
27
  "scikit-learn>=1.2",
28
28
  "joblib>=1.2",
29
29
  "tqdm>=4.64",
30
- "polars>=0.21"
30
+ "polars>=0.21",
31
31
  ]
32
32
 
33
33
  [project.optional-dependencies]
@@ -0,0 +1,7 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ def get_version() -> str:
4
+ try:
5
+ return version("maxcombat")
6
+ except PackageNotFoundError:
7
+ return "unknown"
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env python3
2
1
  # Written by Olivier Coen. Released under the MIT license.
3
2
 
4
3
  """cli.py: thin command-line interface around maxcombat."""
@@ -7,11 +6,13 @@ from __future__ import annotations
7
6
 
8
7
  import argparse
9
8
  import logging
10
- import sys
11
9
  import os
10
+ import sys
12
11
  from multiprocessing import cpu_count
13
12
  from pathlib import Path
14
13
 
14
+ from . import get_version
15
+
15
16
  # ------------------------------------------------------------
16
17
  # CONSTANTS
17
18
  # ------------------------------------------------------------
@@ -22,79 +23,120 @@ DEFAULT_NJOBS = 8
22
23
  # PARSE ARGUMENTS
23
24
  # --------------------------------------------------------------
24
25
 
26
+
25
27
  def parse_args() -> argparse.Namespace:
26
- parser = argparse.ArgumentParser(description="maxcombat: scalable batch-effect correction based on reComBat")
27
- parser.add_argument(
28
- "--counts", type=Path, dest="count_file", required=True,
29
- help="Parquet gathering all count data (genes as rows, samples as columns). The column containing gene IDs should be the first column, or should be specified with --gene-id-colname"
28
+ parser = argparse.ArgumentParser(
29
+ prog="maxcombat",
30
+ description="maxcombat: scalable batch-effect correction based on reComBat"
30
31
  )
31
32
  parser.add_argument(
32
- "--design", type=Path, dest="design_file", required=True,
33
- help="CSV design file with 'sample' and 'batch' columns"
33
+ "--counts",
34
+ type=Path,
35
+ dest="count_file",
36
+ required=True,
37
+ help="Parquet gathering all count data (genes as rows, samples as columns). The column containing gene IDs should be the first column, or should be specified with --gene-id-colname",
34
38
  )
35
39
  parser.add_argument(
36
- "--gene-id-colname", type=str, dest="gene_id_col",
37
- help="Name of the gene ID column in the counts file (default: first column)",
40
+ "--design",
41
+ type=Path,
42
+ dest="design_file",
43
+ required=True,
44
+ help="CSV design file with 'sample' and 'batch' columns",
38
45
  )
39
46
  parser.add_argument(
40
- "--model", help="Regression model used to standardize the data"
47
+ "--gene-id-colname",
48
+ type=str,
49
+ dest="gene_id_col",
50
+ help="Name of the gene ID column in the counts file (default: first column)",
41
51
  )
52
+ parser.add_argument("--model", help="Regression model used to standardize the data")
42
53
  parser.add_argument(
43
- "--parametric", action=argparse.BooleanOptionalAction, default=True,
44
- help="Parametric (default) or --no-parametric empirical Bayes optimization"
54
+ "--parametric",
55
+ action=argparse.BooleanOptionalAction,
56
+ default=True,
57
+ help="Parametric (default) or --no-parametric empirical Bayes optimization",
45
58
  )
46
59
  parser.add_argument(
47
- "--config", type=Path, dest="config_file",
48
- help="JSON file with keyword arguments for the scikit-learn regressor"
60
+ "--config",
61
+ type=Path,
62
+ dest="config_file",
63
+ help="JSON file with keyword arguments for the scikit-learn regressor",
49
64
  )
50
65
  parser.add_argument(
51
- "--conv-criterion", dest="conv_criterion", type=float,
52
- help="Relative convergence criterion (default 1e-4)"
66
+ "--conv-criterion",
67
+ dest="conv_criterion",
68
+ type=float,
69
+ help="Relative convergence criterion (default 1e-4)",
53
70
  )
54
71
  parser.add_argument(
55
- "--max-iter", dest="max_iter", type=int,
56
- help="Maximum number of iterations (default 1000)"
72
+ "--max-iter",
73
+ dest="max_iter",
74
+ type=int,
75
+ help="Maximum number of iterations (default 1000)",
57
76
  )
58
77
  parser.add_argument(
59
- "--mean-only", dest="mean_only", action="store_true",
60
- help="Adjust the mean only, no scaling"
78
+ "--mean-only",
79
+ dest="mean_only",
80
+ action="store_true",
81
+ help="Adjust the mean only, no scaling",
61
82
  )
62
83
  parser.add_argument(
63
- "--clip-negative-values", dest="clip_negative_values", action="store_true",
64
- help="Clip negative output values to 0"
84
+ "--clip-negative-values",
85
+ dest="clip_negative_values",
86
+ action="store_true",
87
+ help="Clip negative output values to 0",
65
88
  )
66
89
  parser.add_argument(
67
- "--reference-batch", dest="reference_batch", default=None,
90
+ "--reference-batch",
91
+ dest="reference_batch",
92
+ default=None,
68
93
  help="Batch label left unadjusted. Defaults to None (all batches adjusted)",
69
94
  )
70
95
  parser.add_argument(
71
- "--optimize-params", dest="optimize_params",
72
- action=argparse.BooleanOptionalAction, default=True,
96
+ "--optimize-params",
97
+ dest="optimize_params",
98
+ action=argparse.BooleanOptionalAction,
99
+ default=True,
73
100
  help="Perform empirical Bayes optimization (default). Use --no-optimize-params to skip it",
74
101
  )
75
102
  parser.add_argument(
76
- "--preserved-covariates", dest="preserved_covariates_file", type=Path, default=None,
103
+ "--preserved-covariates",
104
+ dest="preserved_covariates_file",
105
+ type=Path,
106
+ default=None,
77
107
  help="CSV with a 'sample' column plus covariates of desired variation (ie. conditions that should be considered when computing the batch effect correction).",
78
108
  )
79
109
  parser.add_argument(
80
- "--dropped-covariates", dest="dropped_covariates_file", type=Path, default=None,
110
+ "--dropped-covariates",
111
+ dest="dropped_covariates_file",
112
+ type=Path,
113
+ default=None,
81
114
  help="CSV with a 'sample' column plus covariates of unwanted variation (e.g. RIN, sex) other than batch (e.g. batch-related confounders).",
82
115
  )
83
116
  parser.add_argument(
84
- "--out", type=Path, dest="outfile", required=True,
85
- help="Output Parquet file"
117
+ "--out", type=Path, dest="outfile", required=True, help="Output Parquet file"
86
118
  )
87
119
  parser.add_argument(
88
- "--out-float32", action="store_true", dest="cast_output_to_float32",
120
+ "--out-float32",
121
+ action="store_true",
122
+ dest="cast_output_to_float32",
89
123
  help="Cast corrected data to float32 before export to save memory",
90
124
  )
91
125
  parser.add_argument(
92
- "--out-ndigits", dest="nb_digits_output", type=int,
126
+ "--out-ndigits",
127
+ dest="nb_digits_output",
128
+ type=int,
93
129
  help="Number of digits to keep in the output. Defaults to all digits",
94
130
  )
95
131
  parser.add_argument(
96
- "--cpus", type=int,
97
- help="Number of threads for numpy/polars. Defaults to min(8, <number of available cores>"
132
+ "--cpus",
133
+ type=int,
134
+ help="Number of threads for numpy/polars. Defaults to min(8, <number of available cores>",
135
+ )
136
+ parser.add_argument(
137
+ "--version",
138
+ action="version",
139
+ version=f"%(prog)s {get_version()}"
98
140
  )
99
141
  return parser.parse_args()
100
142
 
@@ -107,31 +149,31 @@ args = parse_args()
107
149
 
108
150
  # Limit thread usage; must be set before importing numpy-heavy libs.
109
151
  n_cpus = args.cpus or min(DEFAULT_NJOBS, cpu_count())
110
- os.environ.update({
111
- "OMP_NUM_THREADS": str(n_cpus),
112
- "OPENBLAS_NUM_THREADS": str(n_cpus),
113
- "MKL_NUM_THREADS": str(n_cpus),
114
- "NUMEXPR_NUM_THREADS": str(n_cpus),
115
- "POLARS_MAX_THREADS": str(n_cpus),
116
- })
152
+ os.environ.update(
153
+ {
154
+ "OMP_NUM_THREADS": str(n_cpus),
155
+ "OPENBLAS_NUM_THREADS": str(n_cpus),
156
+ "MKL_NUM_THREADS": str(n_cpus),
157
+ "NUMEXPR_NUM_THREADS": str(n_cpus),
158
+ "POLARS_MAX_THREADS": str(n_cpus),
159
+ }
160
+ )
117
161
 
118
- import polars as pl # noqa: E402
162
+ import polars as pl # noqa: I001
119
163
 
120
- from maxcombat.core import MaxCombat, SingleBatchException # noqa: E402
121
- from maxcombat.utils import parse_count_table, build_covariates, parse_config, export
122
164
 
165
+ from maxcombat.core import MaxCombat, SingleBatchException
166
+ from maxcombat.utils import build_covariates, export, parse_config, parse_count_table
123
167
 
124
168
  # --------------------------------------------------------------
125
169
  # MAIN
126
170
  # --------------------------------------------------------------
127
171
 
172
+
128
173
  def main() -> None:
129
-
130
174
 
131
175
  logging.basicConfig(
132
- level=logging.INFO,
133
- stream=sys.stdout,
134
- format="[%(levelname)s] %(message)s"
176
+ level=logging.INFO, stream=sys.stdout, format="[%(levelname)s] %(message)s"
135
177
  )
136
178
  logger = logging.getLogger("maxcombat-cli")
137
179
 
@@ -149,21 +191,29 @@ def main() -> None:
149
191
  counts = counts.drop(gene_id_col)
150
192
 
151
193
  # taking only the subpart of the design that corresponds to the count data
152
- design = design.filter(pl.col('sample').is_in(samples))
153
-
154
- data = counts.to_numpy() # (n_genes, n_samples)
194
+ design = design.filter(pl.col("sample").is_in(samples))
195
+
196
+ data = counts.to_numpy() # (n_genes, n_samples)
155
197
  batches = design["batch"].to_numpy()
156
198
 
157
199
  # parsing covariates if provided
158
- preserved_covariates = build_covariates(args.preserved_covariates_file, samples) if args.preserved_covariates_file else None
159
- dropped_covariates = build_covariates(args.dropped_covariates_file, samples) if args.dropped_covariates_file else None
160
-
200
+ preserved_covariates = (
201
+ build_covariates(args.preserved_covariates_file, samples)
202
+ if args.preserved_covariates_file
203
+ else None
204
+ )
205
+ dropped_covariates = (
206
+ build_covariates(args.dropped_covariates_file, samples)
207
+ if args.dropped_covariates_file
208
+ else None
209
+ )
210
+
161
211
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162
212
  # BATCH CORRECTION
163
213
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
164
214
 
165
215
  model = MaxCombat(
166
- parametric=args.parametric, # False if --no-parametric is provided
216
+ parametric=args.parametric, # False if --no-parametric is provided
167
217
  model=args.model,
168
218
  config=parse_config(args.config_file),
169
219
  conv_criterion=args.conv_criterion,
@@ -172,16 +222,16 @@ def main() -> None:
172
222
  optimize_params=args.optimize_params,
173
223
  reference_batch=args.reference_batch,
174
224
  clip_negative_values=args.clip_negative_values,
175
- n_jobs=n_cpus
225
+ n_jobs=n_cpus,
176
226
  )
177
227
 
178
228
  try:
179
229
  corrected = model.fit_transform(
180
- data,
181
- batches,
230
+ data,
231
+ batches,
182
232
  preserved_covariates,
183
233
  dropped_covariates,
184
- sample_names=samples
234
+ sample_names=samples,
185
235
  ) # (n_genes, n_samples)
186
236
  # update new samples, removing orphans that were dropped
187
237
  samples = [s for s, k in zip(samples, model.keep_mask_) if k]
@@ -190,20 +240,20 @@ def main() -> None:
190
240
  corrected = data
191
241
 
192
242
  assert corrected.shape[1] == len(samples)
193
-
243
+
194
244
  # post-processing (clipping negative values if needed)
195
245
  corrected = model.post_process(corrected)
196
246
 
197
247
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198
248
  # POSTPROCESSING AND EXPORT
199
249
  # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
200
-
250
+
201
251
  out_df = pl.DataFrame(corrected, schema=samples)
202
252
 
203
253
  if args.nb_digits_output is not None:
204
254
  logger.info(f"Rounding output to {args.nb_digits_output} digits")
205
255
  out_df = out_df.select(pl.all().round(args.nb_digits_output))
206
-
256
+
207
257
  if args.cast_output_to_float32:
208
258
  logger.info("Casting output to float32")
209
259
  out_df = out_df.select(pl.all().cast(pl.Float32))
@@ -212,9 +262,8 @@ def main() -> None:
212
262
 
213
263
  logger.info(f"Exporting corrected counts to {args.outfile}")
214
264
  export(out_df, args.outfile)
215
-
216
- logger.info("Done")
217
265
 
266
+ logger.info("Done")
218
267
 
219
268
 
220
269
  if __name__ == "__main__":