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

Parameters:
contigs: dict[str, Contig]
bins: list[Bin] | None
property bin_contig_ids: set[str]

Get the set of all contig IDs in the bins.

property assembly_contig_ids: set[str]

Get the set of all contig IDs in the assembly.

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:

BinSet

add_contig_annotations(gff, overwrite=False)[source]

Annotate the contigs in the BinSet with the given GFF file.

Parameters:
  • gff (Path) – Path to the GFF file

  • overwrite (bool) – Whether to overwrite existing annotations

Returns:

A new BinSet with annotated contigs sorted by length

Return type:

BinSet

add_bins_from_fasta(fasta, group, binsplit_separator)[source]

Add bins from a FASTA file to the BinSet.

Parameters:
  • fasta (list[Path]) – List of paths to FASTA files

  • group (str) – Group name for the bins

  • rename_prefix – Prefix to use for renaming contigs

  • binsplit_separator (str | None) – Separator to use for splitting contigs

Returns:

A new BinSet with the bins added and sorted by length

Return type:

BinSet

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:

BinSet

add_bin_quality_scores(quality_file, qc_tool)[source]
Parameters:
Return type:

BinSet

add_bin_taxonomy(taxonomy_file, taxonomy_source)[source]
Parameters:
  • taxonomy_file (Path)

  • taxonomy_source (str | None)

Return type:

BinSet

filter_bins(query)[source]
Parameters:

query (str)

Return type:

BinSet

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:

BinSet

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:

BinSet

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:

BinSet

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
contigs: list[str]
statistics: BinStatistics | None
taxonomy: BinTaxonomy | None
update_statistics(contig_dict)[source]

Updates all bin statistics.

Parameters:

contig_dict (dict[str, Contig]) – Dictionary mapping contig IDs to Contig instances.

Returns:

The updated Bin instance with populated statistics.

Return type:

Bin

export_fasta(contig_dict, output_dir, preserve_headers=False, compress=True)[source]

Writes the bin as a FASTA file.

Parameters:
  • contig_dict (dict[str, Contig]) – Dictionary of contigs.

  • output_dir (Path) – Path to the directory to write FASTA files.

  • preserve_headers (bool) – Whether to preserve the contig headers in the output.

  • compress (bool) – Whether to compress the output file using gzip.

Return type:

None

export_gff(contig_dict, output_dir)[source]

Writes the bin annotations to a GFF file.

Parameters:
  • contig_dict (dict[str, Contig]) – Dictionary of contigs.

  • output_dir (Path) – Path to the directory to write GFF files.

Return type:

None

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:
length: int | None
longest: int | None
n_contigs: int | None
n_circular: int | None
n50: int | None
coverage: float | None
completeness: float | None
contamination: float | None
quality_tool: QualityTool | None
n_unique_trnas: int | None
has_5s: bool | None
has_16s: bool | None
has_23s: bool | None
mimag: MiMAG | 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)

  • taxid (Annotated[int | None, Ge(ge=1)])

tax_source: str
tax_classification: *$|^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
taxid: int | 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)])

  • sequence_length (Annotated[int, Gt(gt=0)])

  • 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)

id: str
header: str
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)])]
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
property trnas: list[str]
property has_5s: bool
property has_16s: bool
property has_23s: bool
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:
seqname: str
source: str
feature: str
start: int
end: int
score: float | None
strand: Strand
frame: Frame
attributes: dict[str, Any]
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:

str

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

metabintools.import_data.assembly.parse_assembly_fasta(assembly, assembler)[source]

Parse an assembly FASTA file into a list of Contig objects.

Parameters:
  • assembly (Path) – The path to the assembly FASTA file.

  • assembler (Assembler | None) – The assembler used to generate the assembly.

Returns:

A dict of Contig objects sorted by sequence length (longest first).

Return type:

dict[str, Contig]

Bin Parsing

metabintools.import_data.binset.parse_fasta_bins(fasta, group, asm_contigs, binsplit_separator=None)[source]

Parse a list of bin files into a list of Bin objects.

Parameters:
  • bins – A list of paths to the bin files.

  • group (str) – The group to assign to the bins.

  • binsplit_separator (str | None) – If binsplitting was used to generate the contigs, the separator to use to split the contig id and sample id.

  • fasta (list[Path])

  • asm_contigs (dict[str, Contig])

Returns:

A list of Bin objects.

Return type:

list[Bin]

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]]

annotate_contigs(contigs, gff, overwrite=False)[source]

Annotate contigs with GFF3 annotations.

Parameters:
  • contigs (dict[str, Contig]) – The contigs to annotate.

  • gff (Path) – The path to the GFF3 file.

  • overwrite (bool) – Whether to overwrite existing annotations.

Returns:

Contigs with annotations.

Return type:

dict[str, Contig]

Coverage Data

class metabintools.import_data.coverage.CoverageReader[source]

Bases: object

add_coverage(contigs, coverage_file, coverage_tool, column_regex)[source]
Parameters:
Return type:

dict[str, Contig]

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:
  • bins (list[Bin]) – The list of bins to update.

  • 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:

list[Bin]

Taxonomy

class metabintools.import_data.taxonomy.TaxonomyReader[source]

Bases: object

add_taxonomy(bins, taxonomy_file, taxonomy_source)[source]

Annotate bins with taxonomy information from a taxonomy file.

Parameters:
Return type:

list[Bin]

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.

Parameters:
  • file (IO) – Binary output stream (file-like object)

  • compress (bool) – Whether to compress the output

  • level (int) – Compression level (default: 3)

export_fasta(outdir, compress, preserve_headers=False, group_fasta=False)[source]

Export FASTA files for each bin in the BinSet.

Parameters:
  • outdir (Path) – Directory to save FASTA files

  • compress (bool) – Whether to compress the output

  • preserve_headers (bool) – Whether to preserve FASTA headers

  • group_fasta (bool)

export_gff(outdir, group_gff)[source]

Export GFF files for each bin in the BinSet.

Parameters:
  • outdir (Path) – Directory to save FASTA files

  • group_gff (bool)

export_contig2bin(path, group)[source]

Export a contig-to-bin mapping file in DAS_Tool format.

Parameters:
  • path (Path) – Path to save the contig-to-bin mapping

  • group (str | None)

summarise_bins(include_statistics=True, include_taxonomy=True)[source]

Flatten the bins in the BinSet into a list of dictionaries.

Parameters:
  • include_statistics (bool) – Whether to include statistics in the output.

  • include_taxonomy (bool) – Whether to include taxonomy in the output.

Returns:

A dictionary summarising the bins

Return type:

list[dict[str, str | int | float | None]]

summarise_contigs()[source]

Summarise the contigs in the binset.

Returns:

A list of dictionaries, each representing a contig.

Return type:

list[dict[str, str | int | float | None]]

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

write_bin_summary_tsv(output_path, include_statistics=True, include_taxonomy=True)[source]

Write a TSV file from the summarised bins.

Parameters:
  • output_path (Path) – Path to write the TSV file to.

  • include_statistics (bool) – Whether to include statistics in the output.

  • include_taxonomy (bool) – Whether to include taxonomy in the output.

Return type:

None

write_group_summary_tsv(output_path)[source]

Write a TSV file summarising bins at the group level.

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: object

Context for evaluating filter expressions.

Parameters:

bin (Bin)

bin: Bin
class metabintools.query.query_parser.ContextDict(context)[source]

Bases: dict

Dict-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:

Callable[[Bin], bool]

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.

Returns:

Dictionary mapping field names to their descriptions

Return type:

dict[str, str]

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:

Callable[[Bin], str]

Operations

Merging

metabintools.operations.merge.merge_binsets(binsets)[source]

Merge multiple BinSet objects into a single BinSet.

Parameters:

binsets (list[BinSet]) – A list of BinSet objects to merge.

Returns:

The merged BinSet object.

Return type:

BinSet

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:
  • bins (list[Bin]) – List of bins to rename

  • 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 list of renamed bins

Raises:

ValueError – If the template contains invalid field references

Return type:

list[Bin]

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: StrEnum

Strand of a genomic feature.

FORWARD = '+'
REVERSE = '-'
UNSTRANDED = '.'
class metabintools.enums.Frame(*values)[source]

Bases: StrEnum

GTF frames

ZERO = '0'
ONE = '1'
TWO = '2'
UNSPECIFIED = '.'
class metabintools.enums.Assembler(*values)[source]

Bases: StrEnum

List of supported assemblers.

spades = 'spades'
megahit = 'megahit'
flye = 'flye'
metamdbg = 'metamdbg'
myloasm = 'myloasm'
hifiasm_meta = 'hifiasm_meta'
class metabintools.enums.MiMAG(*values)[source]

Bases: StrEnum

MiMAG quality annotations

HIGH = 'high'
MEDIUM = 'medium'
LOW = 'low'
class metabintools.enums.QualityTool(*values)[source]

Bases: StrEnum

Supported bin QC tools

checkm = 'checkm'
checkm2 = 'checkm2'
busco = 'busco'
manual = 'manual'
class metabintools.enums.TaxonomyTool(*values)[source]

Bases: StrEnum

Supported taxonomy tools.

gtdbtk = 'gtdbtk'
gtdbtk_ncbi = 'gtdbtk_ncbi'
manual = 'manual'
class metabintools.enums.CoverageTool(*values)[source]

Bases: StrEnum

Supported coverage tools.

metabat = 'metabat'

Utilities

Bin Statistics Calculation

class metabintools.binstatistics.CalculateBinStatistics[source]

Bases: object

static bin_size(contig_dict)[source]

Calculate the total size of the bin.

Parameters:

contig_dict (dict[str, Contig])

Return type:

int

static bin_n50(contig_dict)[source]

Calculate the N50 of the bin.

Parameters:

contig_dict (dict[str, Contig])

Return type:

int

static bin_longest_contig(contig_dict)[source]

Calculate the length of the longest contig in the bin.

Parameters:

contig_dict (dict[str, Contig])

Return type:

int

static bin_n_circular(contig_dict)[source]

Calculate the number of circular contigs in the bin.

Parameters:

contig_dict (dict[str, Contig])

Return type:

int

static bin_n_unique_trnas(contig_dict)[source]

Extract unique tRNA products from the bin.

Parameters:

contig_dict (dict[str, Contig])

Return type:

int

static bin_has_5s(contig_dict)[source]

Check if the bin contains 5S rRNA.

Parameters:

contig_dict (dict[str, Contig])

Return type:

bool

static bin_has_16s(contig_dict)[source]

Check if the bin contains 16S rRNA.

Parameters:

contig_dict (dict[str, Contig])

Return type:

bool

static bin_has_23s(contig_dict)[source]

Check if the bin contains 23S rRNA.

Parameters:

contig_dict (dict[str, Contig])

Return type:

bool

static bin_coverage(contig_dict)[source]

Calculate the average coverage of the bin.

Parameters:

contig_dict (dict[str, Contig])

Return type:

float | None

File Utilities

metabintools.bin_utils.get_extension(file)[source]
Parameters:

file (Path)

Return type:

str

metabintools.bin_utils.get_basename(file)[source]
Parameters:

file (Path | str)

Return type:

str

metabintools.bin_utils.find_binsfiles(directory)[source]
Parameters:

directory (Path)

Return type:

list[Path]

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)