Coverage for binette/main.py: 70%
76 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 13:33 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 13:33 +0000
1#!/usr/bin/env python
2"""
3Module : Main
4Description : Command line interface of Binette.
5Copyright : (c) Jean Mainguy, 28 nov. 2022
6License : GPL-3.0
7Maintainer : Jean Mainguy
8Portability : POSIX
9"""
11import logging
12import sys
13from pathlib import Path
14from typing import Annotated
16import typer
17from rich.console import Console
18from rich.logging import RichHandler
20import binette as binette_init
21from binette import checkpoint, diamond, pipeline
22from binette.config import RunConfig
24logger = logging.getLogger(__name__)
25err_console = Console(stderr=True)
28def version_callback(
29 value: bool,
30 ctx: typer.Context,
31):
32 """Prints the version and exits if --version is passed."""
33 if ctx.resilient_parsing:
34 return
36 if value:
37 typer.echo(f"Binette {binette_init.__version__}")
38 raise typer.Exit()
41def setup_logging(verbose: bool = False, quiet: bool = False):
42 """Sets up logging configuration based on verbosity flags."""
43 if quiet and verbose:
44 raise typer.BadParameter("Cannot specify both --verbose and --quiet")
46 if quiet:
47 lvl = logging.WARNING
48 elif verbose:
49 lvl = logging.DEBUG
50 else:
51 lvl = logging.INFO
53 # Set up logging
54 logging.basicConfig(
55 level=lvl,
56 format="%(message)s",
57 datefmt="[%X]",
58 handlers=[RichHandler(console=err_console)],
59 )
61 # Only log startup messages if not in quiet mode
62 if not quiet:
63 logger.info("Program started")
64 logger.info(f"Command line: {' '.join(sys.argv)}")
67def verbose_callback(
68 verbose: bool,
69):
70 """Sets the logging level to DEBUG if --verbose is passed."""
71 # This is a placeholder - actual setup happens in the main function
72 return verbose
75def quiet_callback(
76 quiet: bool,
77):
78 """Sets the logging level to WARNING if --quiet is passed."""
79 # This is a placeholder - actual setup happens in the main function
80 return quiet
83def preprocess_args():
84 """
85 Typer doesn't support whitespace-separated multi-value options.
87 We preprocess the sysargv so that:
88 - python3 app.py some_command --filters filter1 filter2 filter3 \
89 --environments env1 env2 env3
91 becomes:
92 - python3 app.py some_command --filters filter1 --filters filter2 --filters filter3 --environments env1 --environments env2 --environments env3
94 """
96 logger.debug(f"Initial CLI command is: {sys.argv}")
98 # get main cmd
99 final_cmd = []
100 for _, arg in enumerate(sys.argv):
101 if any(arg.startswith(_) for _ in ["-", "--"]):
102 break
103 else:
104 final_cmd.append(arg)
105 logger.debug(f"Main command is: {final_cmd}")
107 # get options and their values
108 for idx, arg in enumerate(sys.argv):
109 if any(arg.startswith(_) for _ in ["-", "--"]):
110 opt_values = []
111 for value in sys.argv[idx + 1 :]:
112 if any(value.startswith(_) for _ in ["-", "--"]):
113 break
114 else:
115 opt_values.append(value)
117 if len(opt_values) >= 1:
118 [final_cmd.extend([arg, opt_value]) for opt_value in opt_values]
119 else:
120 final_cmd.append(arg)
122 # replace by reformatted
123 logger.debug(f"Final command is: {final_cmd}")
124 sys.argv = final_cmd
127def validate_bin_inputs(
128 bin_dirs: list[Path] | None, contig2bin_tables: list[Path] | None
129) -> None:
130 """Validate that exactly one of bin_dirs or contig2bin_tables is provided."""
131 if bin_dirs is None and contig2bin_tables is None:
132 raise typer.BadParameter(
133 "Error: Either --bin-dirs or --contig2bin_tables must be provided. None were given."
134 )
136 if bin_dirs is not None and contig2bin_tables is not None:
137 raise typer.BadParameter(
138 "Error: Either --bin-dirs or --contig2bin_tables must be provided, but not both."
139 )
142# Create the Typer app with no args help enabled and rich formatting
143app = typer.Typer(
144 name="binette",
145 help=f"Binette: binning refinement tool to constructs high quality MAGs. Version: {binette_init.__version__}",
146 add_completion=False,
147 context_settings={"help_option_names": ["-h", "--help"]},
148 rich_markup_mode="rich",
149)
152@app.command(
153 help=f"Binette {binette_init.__version__}: fast and accurate binning refinement tool to constructs high quality MAGs from the output of multiple binning tools.",
154 no_args_is_help=True,
155)
156def binette(
157 # Input arguments - Mutually exclusive group (handled in code)
158 bin_dirs: Annotated[
159 list[Path] | None,
160 typer.Option(
161 "--bin_dirs",
162 "-d",
163 help="List of bin folders containing each bin in a fasta file.",
164 # callback=lambda x: [is_valid_file(str(p)) for p in x] if x else None,
165 exists=True,
166 rich_help_panel="Input Arguments",
167 ),
168 ] = None,
169 contig2bin_tables: Annotated[
170 list[Path] | None,
171 typer.Option(
172 "--contig2bin_tables",
173 "-b",
174 help="List of contig2bin tables with two columns: contig, bin.",
175 exists=True,
176 rich_help_panel="Input Arguments",
177 ),
178 ] = None,
179 contigs: Annotated[
180 Path,
181 typer.Option(
182 "--contigs",
183 "-c",
184 help="Contigs in FASTA format.",
185 exists=True,
186 rich_help_panel="Input Arguments",
187 ),
188 ] = ..., # Required
189 proteins: Annotated[
190 Path | None,
191 typer.Option(
192 "--proteins",
193 "-p",
194 help="FASTA file of predicted proteins in Prodigal format (>contigID_geneID). Skips the gene prediction step if provided.",
195 exists=True,
196 rich_help_panel="Input Arguments",
197 ),
198 ] = None,
199 # Output & runtime control
200 outdir: Annotated[
201 Path,
202 typer.Option(
203 "--outdir",
204 "-o",
205 help="Output directory.",
206 rich_help_panel="Output and Runtime Control",
207 ),
208 ] = Path("results"),
209 prefix: Annotated[
210 str,
211 typer.Option(
212 "--prefix",
213 help="Prefix to add to final bin names (e.g. '--prefix sample1' will produce 'sample1_bin1.fa', 'sample1_bin2.fa').",
214 rich_help_panel="Output and Runtime Control",
215 ),
216 ] = "binette",
217 threads: Annotated[
218 int,
219 typer.Option(
220 "--threads",
221 "-t",
222 help="Number of threads to use.",
223 rich_help_panel="Output and Runtime Control",
224 ),
225 ] = 1,
226 verbose: Annotated[
227 bool,
228 typer.Option(
229 "--verbose",
230 "-v",
231 help="Enable verbose mode (show detailed debug information).",
232 callback=verbose_callback,
233 rich_help_panel="Output and Runtime Control",
234 ),
235 ] = False,
236 quiet: Annotated[
237 bool,
238 typer.Option(
239 "--quiet",
240 "-q",
241 help="Enable quiet mode (only show warnings and errors).",
242 callback=quiet_callback,
243 rich_help_panel="Output and Runtime Control",
244 ),
245 ] = False,
246 debug: Annotated[
247 bool,
248 typer.Option(
249 help="Activate debug mode.",
250 rich_help_panel="Output and Runtime Control",
251 ),
252 ] = False,
253 # Bin filtering & scoring
254 min_completeness: Annotated[
255 int,
256 typer.Option(
257 "--min_completeness",
258 help="Minimum completeness required for intermediate bin creation and final bin selection.",
259 rich_help_panel="Bin Filtering and Scoring",
260 ),
261 ] = 40,
262 max_contamination: Annotated[
263 int,
264 typer.Option(
265 "--max_contamination",
266 help="Maximum contamination allowed for intermediate bin creation and final bin selection.",
267 rich_help_panel="Bin Filtering and Scoring",
268 ),
269 ] = 10,
270 min_length: Annotated[
271 int,
272 typer.Option(
273 "--min_length",
274 help="Minimum length (bp) required for intermediate bin creation and final bin selection.",
275 rich_help_panel="Bin Filtering and Scoring",
276 ),
277 ] = 200_000,
278 max_length: Annotated[
279 int,
280 typer.Option(
281 "--max_length",
282 help="Maximum length (bp) allowed for intermediate bin creation and final bin selection.",
283 rich_help_panel="Bin Filtering and Scoring",
284 ),
285 ] = 10_000_000,
286 contamination_weight: Annotated[
287 float,
288 typer.Option(
289 "--contamination_weight",
290 "-w",
291 help="Bins are scored as: completeness - weight * contamination. A lower weight favors completeness over low contamination.",
292 rich_help_panel="Bin Filtering and Scoring",
293 ),
294 ] = 2.0,
295 # Advanced options
296 fasta_extensions: Annotated[
297 list[str],
298 typer.Option(
299 "--fasta_extensions",
300 "-e",
301 help="FASTA file extensions to search for in bin directories (used with --bin_dirs).",
302 rich_help_panel="Advanced Options",
303 ),
304 ] = [ # noqa: B006
305 ".fasta",
306 ".fa",
307 ".fna",
308 ],
309 checkm2_db: Annotated[
310 Path | None,
311 typer.Option(
312 "--checkm2_db",
313 help="Path to CheckM2 diamond database. By default the database set via <checkm2 database> is used.",
314 rich_help_panel="Advanced Options",
315 ),
316 ] = None,
317 low_mem: Annotated[
318 bool,
319 typer.Option(
320 "--low_mem",
321 help="Enable low-memory mode for Diamond.",
322 rich_help_panel="Advanced Options",
323 ),
324 ] = False,
325 resume: Annotated[
326 bool,
327 typer.Option(
328 help=(
329 "Reuse intermediate results (proteins, DIAMOND hits) "
330 "from a previous run with the same inputs "
331 "(disable with --no-resume)."
332 ),
333 rich_help_panel="Advanced Options",
334 ),
335 ] = True,
336 force: Annotated[
337 bool,
338 typer.Option(
339 "--force",
340 help=(
341 "Allow using an output directory that contains results of a run with "
342 "different inputs. Previous intermediate "
343 "files are discarded and results are overwritten."
344 ),
345 rich_help_panel="Advanced Options",
346 ),
347 ] = False,
348 version: Annotated[
349 bool,
350 typer.Option(
351 "--version",
352 help="Show version and exit.",
353 callback=version_callback,
354 ),
355 ] = None,
356 progress: Annotated[
357 bool,
358 typer.Option(
359 help="Show progress bar while fetching pangenomes (disable with --no-progress).",
360 rich_help_panel="Output and Runtime Control",
361 ),
362 ] = True,
363 write_fasta_bins: Annotated[
364 bool,
365 typer.Option(
366 help="Write final selected bins as FASTA files (disable with --no-write-fasta-bins).",
367 rich_help_panel="Output and Runtime Control",
368 ),
369 ] = True,
370) -> int:
371 """Orchestrate the execution of the program"""
373 # Set up logging based on verbosity flags
374 setup_logging(verbose=verbose, quiet=quiet)
376 validate_bin_inputs(bin_dirs, contig2bin_tables)
378 config = RunConfig(
379 contigs=contigs,
380 bin_dirs=bin_dirs,
381 contig2bin_tables=contig2bin_tables,
382 proteins=proteins,
383 outdir=outdir,
384 prefix=prefix,
385 threads=threads,
386 min_completeness=min_completeness,
387 max_contamination=max_contamination,
388 min_length=min_length,
389 max_length=max_length,
390 contamination_weight=contamination_weight,
391 fasta_extensions=tuple(fasta_extensions),
392 checkm2_db=checkm2_db,
393 low_mem=low_mem,
394 resume=resume,
395 force=force,
396 debug=debug,
397 write_fasta_bins=write_fasta_bins,
398 show_progress=progress and not quiet,
399 )
401 try:
402 return pipeline.run(config)
403 except checkpoint.OutputDirConflictError as exc:
404 logger.error(str(exc))
405 raise typer.Exit(code=1) from exc
406 except diamond.DiamondError as exc:
407 logger.error(str(exc))
408 raise typer.Exit(code=exc.exit_code) from exc
411def main():
412 preprocess_args()
414 app()