API Reference
This page provides detailed documentation of the metabintools Python API for programmatic use.
Core Data Structures
BinSet
- class metabintools.dataclasses.binset.BinSet(*, contigs, bins=None)[source]
Bases:
BaseModel- classmethod validate_bin_contigs(bins, info)[source]
Validate that all bin contigs are present in the assembly.
- classmethod read_binsfile(file)[source]
Read a BinSet from a binary stream, automatically detecting zstd compression.
- Parameters:
file (IO) – Binary input stream (file-like object)
- Returns:
BinSet instance
- Raises:
ValueError – If the data is invalid or decompression fails
- Return type:
- add_contig_annotations(gff, overwrite=False)[source]
Annotate the contigs in the BinSet with the given GFF file.
- add_bins_from_fasta(fasta, group, binsplit_separator)[source]
Add bins from a FASTA file to the BinSet.
- Parameters:
- Returns:
A new BinSet with the bins added and sorted by length
- Return type:
- add_contig_coverage(coverage_file, coverage_tool, column_regex)[source]
Add coverage data to the BinSet from a coverage file.
- Parameters:
coverage_file (Path) – Path to the coverage file
coverage_tool (CoverageTool) – Tool used to generate the coverage file
column_regex (str)
- Returns:
A new BinSet with the coverage data added and contigs sorted by length
- Return type:
- add_bin_quality_scores(quality_file, qc_tool)[source]
- Parameters:
quality_file (Path)
qc_tool (QualityTool)
- Return type:
- rename_bins(template)[source]
Rename bins using a template with field name injection.
Template placeholders are replaced with bin field values. If multiple bins end up with the same name, numeric suffixes are appended (_1, _2, etc.).
- Parameters:
template (str) – A template string with field placeholders like “bin_{taxon_name}” Available placeholders: id, group, completeness, contamination, phylum, taxon_name, and other bin/statistics/taxonomy fields.
- Returns:
A new BinSet with renamed bins sorted by length
- Raises:
ValueError – If the template contains invalid field references
- Return type:
Examples
binset.rename_bins(“bin_{taxon_name}”) # Returns: bin_Bacteroides sp., bin_Firmicutes sp., etc.
binset.rename_bins(“bin_{group}_{id}”) # Returns: bin_group1_original_id, etc.
- remove_unreferenced_contigs()[source]
Trim the BinSet to remove contigs not used by any bin.
- Return type:
- update_statistics()[source]
Update the statistics for each bin in the BinSet.
- Returns:
A new BinSet instance with updated bin statistics and sorted by length.
- Return type:
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
The main class representing a collection of contigs and bins.
Bin
- class metabintools.dataclasses.bin.Bin(*, id, import_name, group, contigs, statistics=None, taxonomy=None)[source]
Bases:
BaseModel- Parameters:
id (str)
import_name (str)
group (str)
statistics (BinStatistics | None)
taxonomy (BinTaxonomy | None)
- statistics: BinStatistics | None
- taxonomy: BinTaxonomy | None
- export_fasta(contig_dict, output_dir, preserve_headers=False, compress=True)[source]
Writes the bin as a FASTA file.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Represents a single metagenomic bin with statistics and taxonomy.
BinStatistics
- class metabintools.dataclasses.bin_statistics.BinStatistics(*, length=None, longest=None, n_contigs=None, n_circular=None, n50=None, coverage=None, completeness=None, contamination=None, quality_tool=None, n_unique_trnas=None, has_5s=None, has_16s=None, has_23s=None, mimag=None)[source]
Bases:
BaseModel- Parameters:
- quality_tool: QualityTool | None
- update_mimag()[source]
Update the MiMAG level of the bin based on the number of contigs, circularity, completeness, contamination, and unique tRNAs.
- Return type:
None
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Statistics computed for a bin.
BinTaxonomy
- class metabintools.dataclasses.bin_taxonomy.BinTaxonomy(*, tax_source, tax_classification, tax_kingdom=None, tax_phylum=None, tax_class=None, tax_order=None, tax_family=None, tax_genus=None, tax_species=None, taxon_name=None, taxid=None)[source]
Bases:
BaseModel- Parameters:
tax_source (str)
tax_classification (Annotated[str, StringConstraints(strip_whitespace=None, to_upper=None, to_lower=None, strict=None, min_length=None, max_length=None, pattern=^[dk]__.*;p__.*;c__.*;o__.*;f__.*;g__.*;s__.*$|^unknown$, ascii_only=None)])
tax_kingdom (str | None)
tax_phylum (str | None)
tax_class (str | None)
tax_order (str | None)
tax_family (str | None)
tax_genus (str | None)
tax_species (str | None)
taxon_name (str | None)
- tax_classification: *$|^unknown$, ascii_only=None)]
- model_post_init(_BinTaxonomy__context, /)[source]
Parse lineage and populate taxonomy fields if not provided.
- Parameters:
__context – The context for the model post-init.
- Return type:
None
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Taxonomy information for a bin.
Contig
- class metabintools.dataclasses.contig.Contig(*, id, header, sequence, sequence_length, topology=None, coverage=None, annotations=None, gc=None)[source]
Bases:
BaseModel- Parameters:
id (str)
header (str)
sequence (Annotated[str, StringConstraints(strip_whitespace=None, to_upper=None, to_lower=None, strict=None, min_length=None, max_length=None, pattern=^[ACGTN]+$, ascii_only=None)])
topology (Literal['linear', 'circular'] | None)
coverage (Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0)])] | None)
annotations (list[Annotation] | None)
gc (float | None)
- sequence: StringConstraints(strip_whitespace=None, to_upper=None, to_lower=None, strict=None, min_length=None, max_length=None, pattern=^[ACGTN]+$, ascii_only=None)]
- sequence_length: Annotated[int, FieldInfo(annotation=NoneType, required=True, metadata=[Gt(gt=0)])]
- coverage: Annotated[float, FieldInfo(annotation=NoneType, required=True, metadata=[Ge(ge=0)])] | None
- annotations: list[Annotation] | None
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Represents a single contig sequence.
Annotation
- class metabintools.dataclasses.annotation.Annotation(*, seqname, source, feature, start, end, score=None, strand, frame, attributes=<factory>)[source]
Bases:
BaseModel- Parameters:
- classmethod validate_end_greater_than_start(v, info)[source]
Validate that the end position is greater than or equal to the start position.
- Parameters:
v – The end position to validate.
info – The field info for the end position.
- Raises:
ValueError – If the end position is less than the start position.
- Returns:
The validated end position.
- to_gff_record()[source]
Formats the annotation as a GFF record (tab-delimited line).
- Returns:
A GFF-formatted string ready to write to file.
- Return type:
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
GFF-format annotation for a contig.
Import Functions
Assembly Parsing
Bin Parsing
Annotation Processing
- class metabintools.import_data.annotation.ContigAnnotator[source]
Bases:
object- static read_gff(gff)[source]
Parse a GFF3 file into a list of Annotation objects.
- Parameters:
gff (Path) – The path to the GFF3 file.
- Returns:
A dictionary mapping seqnames to lists of annotations.
- Return type:
dict[str, list[Annotation]]
Coverage Data
Quality Scores
- class metabintools.import_data.quality.QualityReader[source]
Bases:
object- add_quality_scores(bins, quality_file, qc_tool)[source]
Add quality information to the bins based on the quality file and QC tool.
- Parameters:
quality_file (Path) – The path to the quality file.
qc_tool (QualityTool) – The QC tool used to generate the quality file.
- Returns:
The updated list of bins with quality information.
- Return type:
Taxonomy
Export Functions
- class metabintools.export.binset_exporter.BinSetExporter(binset)[source]
Bases:
object- write_binsfile(file, compress=False, level=3)[source]
Write the BinSet to a binary stream, optionally compressing it with zstd.
The JSON is streamed one contig or bin at a time, so the full document is never held in memory.
- export_fasta(outdir, compress, preserve_headers=False, group_fasta=False)[source]
Export FASTA files for each bin in the BinSet.
- summarise_bins(include_statistics=True, include_taxonomy=True)[source]
Flatten the bins in the BinSet into a list of dictionaries.
- write_contig_summary_tsv(output_path)[source]
Write a TSV file from the summarised contigs.
- Parameters:
output_path (Path) – Path to write the TSV file to.
- Return type:
None
Query and Filtering
Query parser for filtering bins using expressions.
Supports filtering by bin properties, statistics, and taxonomy. .. rubric:: Examples
group == “high_quality”
completeness >= 90 and contamination <= 5
phylum == “Bacteroidetes” or phylum == “Firmicutes”
length > 1000000
- class metabintools.query.query_parser.FilterContext(bin)[source]
Bases:
objectContext for evaluating filter expressions.
- Parameters:
bin (Bin)
- class metabintools.query.query_parser.ContextDict(context)[source]
Bases:
dictDict-like object that delegates to FilterContext for attribute access.
- Parameters:
context (FilterContext) – The FilterContext to delegate to.
- metabintools.query.query_parser.parse_filter_query(query)[source]
Parse a filter query string and return a filter function.
- Parameters:
query (str) – A filter expression using Python comparison operators and boolean logic (and, or, not)
- Returns:
A callable that takes a Bin and returns True if it matches the filter
- Raises:
ValueError – If the query is invalid
- Return type:
- metabintools.query.query_parser.get_available_fields()[source]
Get a dictionary of all available fields that can be used in filters.
Dynamically extracts field descriptions from Pydantic model schemas.
- metabintools.query.query_parser.parse_rename_template(template)[source]
Parse a rename template string and return a function that generates bin names.
Allows injecting field values into the template using the format {field_name}. Field names are resolved from bin properties, statistics, and taxonomy.
- Parameters:
template (str) – A template string with field placeholders like “bin_{taxon_name}”
- Returns:
A callable that takes a Bin and returns the generated name
- Raises:
ValueError – If the template contains invalid field references
- Return type:
Operations
Merging
Renaming
Bin renaming operations.
- metabintools.operations.rename.rename_bins(bins, template)[source]
Rename bins using a template with field name injection.
Template placeholders are replaced with bin field values. If multiple bins end up with the same name, numeric suffixes are appended (_1, _2, etc.).
- Parameters:
- Returns:
A list of renamed bins
- Raises:
ValueError – If the template contains invalid field references
- Return type:
Examples
renamed = rename_bins(bins, “bin_{taxon_name}”) # Returns bins renamed to: bin_Bacteroides sp., bin_Firmicutes sp., etc.
renamed = rename_bins(bins, “bin_{group}_{id}”) # Returns bins renamed with group and original id
Enumerations
- class metabintools.enums.Strand(*values)[source]
Bases:
StrEnumStrand of a genomic feature.
- FORWARD = '+'
- REVERSE = '-'
- UNSTRANDED = '.'
- class metabintools.enums.Frame(*values)[source]
Bases:
StrEnumGTF frames
- ZERO = '0'
- ONE = '1'
- TWO = '2'
- UNSPECIFIED = '.'
- class metabintools.enums.Assembler(*values)[source]
Bases:
StrEnumList of supported assemblers.
- spades = 'spades'
- megahit = 'megahit'
- flye = 'flye'
- metamdbg = 'metamdbg'
- myloasm = 'myloasm'
- hifiasm_meta = 'hifiasm_meta'
- class metabintools.enums.MiMAG(*values)[source]
Bases:
StrEnumMiMAG quality annotations
- HIGH = 'high'
- MEDIUM = 'medium'
- LOW = 'low'
- class metabintools.enums.QualityTool(*values)[source]
Bases:
StrEnumSupported bin QC tools
- checkm = 'checkm'
- checkm2 = 'checkm2'
- busco = 'busco'
- manual = 'manual'
Utilities
Bin Statistics Calculation
- class metabintools.binstatistics.CalculateBinStatistics[source]
Bases:
object- static bin_longest_contig(contig_dict)[source]
Calculate the length of the longest contig in the bin.
File Utilities
Example Usage
Programmatic Workflow
Here’s an example of using metabintools as a Python library:
from pathlib import Path
from metabintools.dataclasses.binset import BinSet
from metabintools.import_data.assembly import parse_assembly_fasta
from metabintools.import_data.binset import parse_fasta_bins
from metabintools.enums import Assembler
# Load assembly
assembly_path = Path("metagenome.fasta")
contigs = parse_assembly_fasta(assembly_path, Assembler.metamdbg)
# Load bins
bin_paths = [Path("bins/bin1.fa"), Path("bins/bin2.fa")]
bins = parse_fasta_bins(bin_paths, group="metabat", asm_contigs=contigs)
# Create BinSet
binset = BinSet(contigs=contigs, bins=bins)
# Filter bins
filtered = binset.filter_bins("completeness >= 0.9")
# Export to FASTA
from metabintools.export.binset_exporter import BinSetExporter
exporter = BinSetExporter(filtered)
exporter.export_fasta(Path("output/"), compress=False)
Reading and Writing BINS files
from metabintools.dataclasses.binset import BinSet
from metabintools.export.binset_exporter import BinSetExporter
# Read a BINS file
with open("project.bins", "rb") as f:
binset = BinSet.read_binsfile(f)
# Perform operations
filtered = binset.filter_bins("tax_phylum == 'Bacteroidetes'")
# Write back (optionally compressed)
with open("output.bins.zstd", "wb") as f:
exporter = BinSetExporter(filtered)
exporter.write_binsfile(f, compress=True)