Skip to main content

gapHACk - Gap-Optimized Hierarchical Agglomerative Clustering

A Python package for DNA barcode clustering that optimizes for the barcode gap between intra-species and inter-species genetic distances.

Overview

gapHACk implements a two-phase clustering algorithm designed for DNA barcoding applications:

  1. Phase 1: Fast greedy lumping up to the min-split threshold (default 6 mismatches on full ITS, about 1%)
  2. Phase 2: Gap-aware optimization using gap-based heuristic to find optimal clustering

The algorithm focuses on maximizing the "barcode gap" - the separation between intra-species and inter-species distances at a specified percentile (default P95) to handle outliers robustly.

gapHACk provides four complementary tools:

  • gaphack: Core clustering for medium-sized datasets (up to ~1,000 sequences)
  • gaphack-refine: Iterative refinement to optimize cluster boundaries
  • gaphack-analyze: Quality assessment for pre-clustered FASTA files
  • gaphack-blast: Analyze BLAST results to identify conspecific sequences

Clustering Workflows

gapHACk supports two main workflows depending on your use case:

Workflow 1: Large-Scale Clustering

For datasets with 1,000+ sequences, combine fast external clustering with gap-based refinement:

# Step 1: Fast initial clustering with vsearch (or CD-HIT, MMseqs2, etc.)
# vsearch names its files cluster_0, cluster_1, ...; gaphack-refine reads *.fasta
mkdir clusters
vsearch --cluster_fast input.fasta --id 0.97 --clusters clusters/cluster_
for f in clusters/cluster_*; do mv "$f" "$f.fasta"; done

# Step 2: Refine cluster boundaries with gapHACk
gaphack-refine --input-dir clusters/ \
               --output-dir refined/

# Step 3: Assess quality
gaphack-analyze refined/latest/*.fasta -o analysis/

This workflow leverages fast external tools for initial approximate clustering, then applies gapHACk's gap optimization to refine boundaries between closely related groups.

Workflow 2: Focused Expert Investigation

For targeted analysis or moderate-sized datasets:

# Analyze existing clusters to understand distance distributions
gaphack-analyze existing_clusters/*.fasta -o analysis/

# Extract and cluster sequences related to specific targets
gaphack full_dataset.fasta --target reference_seqs.fasta -o target_cluster

# Full gap-optimized clustering on focused dataset
gaphack focused_dataset.fasta -o clusters/

This workflow is useful for taxonomic investigations, quality control, or detailed analysis of specific groups.

Features

Core Clustering (gaphack)

  • Local Gap Optimization: Evaluates each cluster relative to its nearest neighbor using multi-percentile calculation [90, 95, 100] for robust species delimitation
  • Global Gap Support: Optional global gap method for comparison to literature (e.g., Wilson et al. 2023)
  • Context-free Distances: Every pair of sequences is aligned on its own, so a distance does not depend on the other sequences or on input order (--distance spoa for one SPOA alignment of the input, as before 0.8.0)
  • Target Mode: Single-cluster focused clustering from seed sequences with --target parameter
  • Percentile-based Linkage: Uses percentile-based complete linkage (default 95th percentile) for robust merge decisions
  • Two-phase Algorithm: Fast initial clustering followed by gap-aware optimization to completion
  • Multiprocessing: The pairwise alignments and the local gap search use all available CPU cores (configurable with -t)
  • Progress Tracking: Real-time progress bar with gap and cluster information
  • Size-ordered Output: Clusters numbered by size (largest first) for consistent results

Iterative Refinement (gaphack-refine)

  • Neighborhood-based Refinement: Iteratively refines cluster boundaries using proximity graphs
  • Context-free Distances: Affine pairwise alignment, so a pair's distance does not depend on which sequences share its scope or on input order
  • Guaranteed Stopping Point: After a few exploratory iterations, a scope's result is kept only if it improves one whole-set objective
  • Final Stages: A gap-checked split pass, then placement of singletons into a clearly nearest cluster
  • Convergence Detection: AMI-based convergence tracking to detect stable clustering states
  • Iteration Checkpointing: Saves state every N iterations for long-running jobs
  • Auto-resume: Automatically detects and resumes from saved checkpoints
  • Global Gap Metrics: Tracks barcode gap quality across iterations for progress monitoring
  • Deterministic Ordering: Seeds are taken in a fixed order, so the same input always gives the same result
  • Flexible Configuration: Control scope size, iteration limits, and convergence thresholds

Analysis Tools (gaphack-analyze)

  • Pre-clustered Analysis: Evaluate existing clustering results
  • Distance Distributions: Calculate intra-cluster and inter-cluster distances
  • Barcode Gap Metrics: Assess gap quality at P90/P95 levels
  • Visualization: Generate histograms with percentile markers
  • Multiple Output Formats: Text reports, JSON data, or TSV tables

BLAST Analysis (gaphack-blast)

  • Conspecific Classification: Identify which BLAST hits are same-species as your query
  • Barcode Gap Detection: Find natural boundaries between species in search results
  • Structured Output: JSON, TSV, or text formats for easy integration
  • Web-Service Ready: Single-threaded design suitable for concurrent web requests, and no external program needed
  • Stdin/Stdout Support: Pipe-friendly for workflow integration

Performance

Multiprocessing Capabilities

gaphack uses worker processes for the two expensive steps: aligning every pair of sequences, and the gap-aware clustering phase with the local gap (the default):

  • Automatic Parallelization: Uses all available CPU cores by default (releases before 0.8.0 used at most 4)
  • Single-process Mode: Use -t 0 for single-threaded operation (ideal for library usage)
  • Custom Thread Count: Use -t N to specify number of worker processes
  • Scalable Performance: Achieves ~4x speedup with 8 cores (200→800 steps/second)
  • Memory Efficient: Persistent worker caches reduce initialization overhead
  • Global gap: --gap-method global clusters in one process whatever -t says; it is fast without workers. The alignments still use them
  • Target mode: aligns only the pairs the growing cluster needs, also on the worker processes
# Use all available cores (default)
gaphack input.fasta

# Use 4 worker processes
gaphack input.fasta -t 4

# Single-threaded mode (for library usage or debugging)
gaphack input.fasta -t 0

Performance Characteristics

  • Small datasets (< 100 sequences): Single-process mode may be faster due to reduced overhead
  • Medium datasets (100-1000 sequences): Multiprocessing provides significant speedup
  • Large datasets (> 1000 sequences): Use vsearch + gaphack-refine workflow for best performance

Aligning a pair of full ITS sequences takes about 2.3 ms on one core, and gaphack aligns every pair: 124,750 pairs for 500 sequences, half a million for 1,000. On an 18-core machine the 500-sequence test file took 50 seconds in all, 26 of them aligning (32 seconds with --distance spoa); with 4 worker processes it took 103. gaphack-refine aligns only the pairs it needs (about 2% of them on a 21,839-sequence set), which is what makes the two-stage workflow practical for large datasets. The gap-aware clustering phase scales with O(n³) complexity.

--distance spoa replaces the pairwise alignments by one SPOA alignment of the input. It is many times faster, and gives up what the pairwise alignments are for: see How Pairs Are Aligned.

Installation

From PyPI

pip install gaphack

On macOS and on Linux x86-64 every dependency installs as a prebuilt package. On Windows and on Linux ARM, pip compiles one of them (edlib), which needs a C++ compiler and the Python headers (on Debian/Ubuntu: sudo apt-get install build-essential python3-dev).

External Tools

gaphack, gaphack-blast and gaphack-analyze need nothing beyond the Python package at their defaults. gaphack-refine needs vsearch. Some options run other programs, which pip does not install; they must be on your PATH:

Program Needed for
SPOA Only --distance spoa, in any of the commands. The default distances need no external program
BLAST+ (makeblastdb, blastn) gaphack-refine --search-method blast
vsearch gaphack-refine with its defaults: the pairwise distances (--distance affine), the acceptance rule, the split pass and placement, the proximity graph (--search-method vsearch), and --set-aside-partials. Without vsearch, --search-method blast --distance spoa --accept all --no-split-pass --no-placement runs on BLAST+ and SPOA

For example, conda install -c bioconda spoa blast vsearch, or on Debian/Ubuntu sudo apt-get install spoa ncbi-blast+ vsearch.

Optional: pip install "gaphack[orientation]" adds pyitsx, which --organism uses to put all sequences on one strand (see Strand Orientation).

From Source

git clone https://github.com/joshuaowalker/gaphack.git
cd gaphack
pip install -e .

Quick Start

Try gapHACk with example data:

# Install the package
pip install gaphack

# Download example data
wget https://raw.githubusercontent.com/joshuaowalker/gaphack/main/examples/data/collybia_nuda_test.fasta

# Standard clustering (creates collybia_nuda_test.cluster_001.fasta, collybia_nuda_test.cluster_002.fasta, etc.)
gaphack collybia_nuda_test.fasta

# With detailed output and custom parameters
gaphack collybia_nuda_test.fasta \
    -o output/clusters \
    --export-metrics metrics.json \
    --verbose

The example dataset contains 91 Collybia nuda ITS sequences from iNaturalist with known clustering structure. See examples/README.md for more details.

For larger datasets, use the two-stage workflow:

# Stage 1: Fast initial clustering with vsearch (one FASTA file per cluster)
mkdir clusters
vsearch --cluster_fast large_dataset.fasta --id 0.97 --clusters clusters/cluster_
for f in clusters/cluster_*; do mv "$f" "$f.fasta"; done

# Stage 2: Gap-optimized refinement
gaphack-refine --input-dir clusters/ --output-dir refined/

# Stage 3: Quality assessment
gaphack-analyze refined/latest/*.fasta -o analysis/

Usage

Core Clustering (gaphack)

Basic usage:

# Creates input.cluster_001.fasta, input.cluster_002.fasta, etc.
gaphack input.fasta

# Custom output base path
gaphack input.fasta -o results/myclusters

# Multiple input files (treated as concatenated)
gaphack file1.fasta file2.fasta file3.fasta -o combined

# Target mode clustering
gaphack input.fasta --target seeds.fasta -o target_cluster

# Distances from a matrix you computed yourself, instead of aligning the sequences
gaphack input.fasta --distance-matrix distances.csv -o myclusters

--distance-matrix takes a CSV file with one row and one column per input sequence, in the order of the input. The input FASTA is still read: for the names in the output, for FASTA output, and to find the --target sequences. A matrix of another size is refused. --organism is ignored with a matrix, since nothing is aligned and no sequence may be left out.

With custom parameters:

# Local gap with custom thresholds and parsimony
gaphack input.fasta \
    --min-split-mismatches 4 \
    --max-lump-mismatches 16 \
    --alpha 0.5 \
    --export-metrics gap_analysis.json \
    --threads 8 \
    --verbose

# Global gap for literature comparison
gaphack input.fasta \
    --gap-method global \
    --target-percentile 90 \
    --export-metrics gap_analysis.json \
    --verbose

Target Mode Clustering

Use --target to grow a single cluster from seed sequences:

# Basic target mode with seed sequences
gaphack input.fasta --target seeds.fasta -o target_results

# Target mode produces:
# - target_results.cluster_001.fasta (sequences in the target cluster)
# - target_results.unclustereds.fasta (sequences not processed for clustering)

Target mode focuses on growing one cluster from the provided seed sequences, making it suitable for cases where you want to extract sequences similar to specific targets without attempting to cluster all remaining sequences.

The cluster grows one sequence at a time, closest first, up to --max-lump-mismatches. The result is the size with the widest gap among those that include every merge made within --min-split-mismatches: sequences that close to the cluster always join it.

Iterative Refinement (gaphack-refine)

The gaphack-refine tool optimizes cluster boundaries through iterative neighborhood-based refinement. It works with any input clustering (vsearch, CD-HIT, MMseqs2, or gaphack output).

Basic Usage

# Refine existing clusters
gaphack-refine --input-dir clusters/ \
               --output-dir refined/

Input Format: Directory containing one FASTA file per cluster (e.g., cluster_001.fasta, cluster_002.fasta, etc.). Only files ending in .fasta or .fa are read, and at least two clusters are needed. A file named unassigned.fasta holds sequences that belong to no cluster: they take no part in refinement and are written to the output unchanged.

Output: Timestamped directory with refined clusters and detailed summary report

Key Features

Context-free Distances

By default (--distance affine), gaphack-refine scores each pair with an affine-gap pairwise alignment with free end gaps, using the same adjusted-identity scoring as the rest of gapHACk:

  • A pair's distance depends only on the two sequences, not on which other sequences share a scope
  • Results do not depend on input order, on what the sequences are called, or on the names of the input cluster files
  • Only the pairs refinement needs are aligned (about 2% of all pairs on a 21,839-sequence set), and --distance-cache DIR reuses them across runs

A saved cache is used only for the same sequences and settings, and only under the versions of adjusted-identity and Biopython that wrote it, because another version of either may score a pair differently. Its lists of near neighbors also depend on vsearch and edlib, which choose the candidate pairs: under another version of either, the lists are built again from the saved distances. In each case the run says so.

--distance spoa uses a SPOA multiple alignment for each scope instead.

Thresholds in Mismatches

gaphack-refine sets its distance thresholds as whole numbers of mismatches, because its distances are mismatches divided by the median length and a fractional threshold can land on a different count at nearby lengths.

Option Default Meaning
--min-split-mismatches 4 Sequences this close merge before the gap search
--max-lump-mismatches 12 Clusters farther apart are never merged
--close-mismatches --max-lump-mismatches Clusters within this distance are found as neighbors
--placement-margin-mismatches 4 How much closer a singleton must be to its nearest cluster than to the runner-up
--fallback-cut-mismatches 8 Where a neighborhood shows no barcode gap, clusters up to this far apart merge

These defaults are for full ITS (median lengths of 500 to 699 bp). At other median lengths they scale with length and a warning asks you to set counts for that locus. Counts you give are used as they are. --set-aside-partials applies the max-lump threshold as a proportion, because a partial's distances are measured over its own overlap.

These options replace --min-split and --max-lump in gaphack-refine. --close-threshold still works but is deprecated: it is rounded to mismatches at the median length and is never below --max-lump-mismatches. gaphack and gaphack-blast set their two thresholds the same way, with a default min-split of 6 (see Default thresholds). gaphack-refine's default is lower, 4, because it was tuned together with its later stages, such as the cut at 8 mismatches described below, which the other tools do not have.

Neighborhoods Without a Barcode Gap

gapHACk keeps the partition with the widest barcode gap. Some neighborhoods have none: a single species wider than --min-split-mismatches, or close species whose distances overlap. There the widest "gap" is only the least negative one, which in practice belongs to the partition from the first merge step, so a wide species comes out as dozens of small clusters.

gaphack-refine handles such a neighborhood in two steps, and reports the result at two levels.

  1. Cut. The neighborhood is cut at a fixed distance: clusters up to --fallback-cut-mismatches apart (at the target percentile) merge, and the rest stay apart. A neighborhood that merged into a single cluster stays whole. The count must lie from --min-split-mismatches to --max-lump-mismatches.
  2. Merge. No fixed cut suits every lineage: one that keeps close species apart also breaks a species wider than the cut. So the pieces are merged again wherever no barcode gap separates two of them. The gap between two clusters is the 5th percentile of the distances between them minus the larger of their widths (the 95th percentile of the distances within each). While some pair has a gap under one mismatch and a 95th-percentile linkage within --max-lump-mismatches, the pair with the smallest gap is merged.

ITS distances alone cannot tell one wide species from a group of close species: in both, the pieces overlap. So the output has two levels:

  • Clusters (the FASTA files): groups that no barcode gap divides. On a test set from a family with wide species, this level agreed far better with curated names (adjusted Rand index 0.955, against 0.725 for the cut alone).
  • Pieces (cluster_pieces.tsv): what the cut makes of each cluster taken alone. On a test set from a family with a group of close species, the clusters lumped that group (0.801) and the pieces kept it apart (0.874).

cluster_pieces.tsv has one row per sequence: sequence, cluster, piece (numbered within the cluster, largest first). cluster_summary.tsv has one row per cluster, with distances in mismatches: sequences, pieces, largest_piece, width (95th percentile of the distances within the cluster), nearest_cluster, nearest_distance (5th percentile of the distances to it) and gap (that distance minus the larger of the two widths). A gap of at least 1 means a barcode gap separates the cluster from its nearest neighbor. A cluster with one piece is not divided by the cut.

--no-fallback-merge skips the merge, so the clusters of such a neighborhood are the pieces. --no-fallback-cut skips both steps and keeps the least negative gap. Both steps are used with the default --gap-method global.

Acceptance and Final Stages

Each iteration re-clusters many overlapping scopes, and gapHACk's answer for a set of sequences depends on which neighbors share its scope, so simply applying every result can cycle forever. --accept hybrid:3 (the default) applies every result for three iterations, then keeps a result only if it raises the local barcode gap summed over all clusters, so refinement reaches a stable state. --accept improve skips the exploratory iterations and --accept all applies every result.

After refinement, two final stages run:

  • Split pass (--no-split-pass to skip): re-clusters each cluster alone and keeps a split only if its parts are separated by a real P95 barcode gap. This recovers species that one scope-wide threshold kept together. It looks at clusters of up to --split-max-size sequences (default 300): it uses the local gap, which slows steeply with size, so this limit does not follow --max-scope-size.
  • Singleton placement (--no-placement to skip): moves a singleton into its nearest cluster when it is within --max-lump-mismatches and clearly closer to that cluster than to any other.
The Previous Algorithm

The nearest thing to gaphack-refine 0.7.x is:

gaphack-refine --input-dir clusters/ --output-dir refined/ \
    --distance spoa --accept all --no-split-pass --no-placement --no-fallback-cut \
    --max-scope-size 300 \
    --search-method blast --max-iterations 10 --min-split-mismatches 3 \
    --hp-normalize-min-length 1 --tie-break-epsilon 0

The first two lines of options turn off what 0.8.0 added to gaphack-refine and restore the earlier scope limit. The last two restore the other 0.7.x defaults: BLAST for the proximity graph, 10 iterations, a --min-split of 0.005 (3 mismatches on full ITS), the earlier homopolymer setting, and no tie-breaking. The command needs SPOA and BLAST+, not vsearch.

In the library, RefinementConfig.previous_algorithm() is the same configuration (with fractional min_split and max_lump).

This does not reproduce 0.7.x results. Thresholds are whole numbers of mismatches at each scope's median length, and the fixes of this release to the clustering algorithm and to cluster medoids still apply. On a 334-sequence test set, 0.7.2 gave 32 clusters and this command 36, with an adjusted Rand index of 0.915 between the two results. Without the last five options the index was 0.541.

Partial Sequences

A short sequence covers few of the sites that separate species, so it can bridge species during clustering. --set-aside-partials leaves sequences shorter than 75% of the median length (or another fraction, --set-aside-partials 0.6) out of refinement, then places each in its clearly nearest cluster, using distances over the pair's own overlap. A partial without a clear nearest cluster stays a singleton, so a short type sequence is not attached to a name on weak evidence. Decisions are written to partial_placements.tsv. This is off by default because a length rule can also catch taxa whose full ITS is naturally short.

Gap Method

Refinement scopes default to the global gap (--gap-method global), while gaphack defaults to the local gap. On test sets of 4,610 sequences and up, the global gap agreed better with supertree clades and curated names during refinement. The global gap of a scope is computed from counts of each distinct distance, so a scope of a thousand sequences clusters in about a second. --gap-method local still sorts lists of all distances and slows steeply as scopes grow.

Iteration Checkpointing and Auto-Resume

A run saves a checkpoint after every iteration by default: a folder <timestamp>_iterNNN in the output directory with every cluster as it stood, and a state.json. To continue a run that was stopped, or that reached --max-iterations, give the last checkpoint folder as the input:

# Resume from a checkpoint (state.json in the input directory is detected)
gaphack-refine --input-dir refined/20251013_143022_iter012/ \
               --output-dir refined_continued/

# Checkpoint every 5 iterations, or not at all
gaphack-refine --input-dir clusters/ --output-dir refined/ --checkpoint-frequency 5
gaphack-refine --input-dir clusters/ --output-dir refined/ --checkpoint-frequency 0

Each checkpoint is a full copy of the clusters, and a large run can take dozens of iterations, so raise --checkpoint-frequency or set it to 0 where disk space matters. The final result folder (latest) is not a checkpoint: starting from it begins a new run on the finished clusters.

Checkpoints include:

  • Current cluster assignments
  • Iteration state and convergence tracking
  • Refinement statistics and timing
  • FASTA files for each iteration
Convergence Tracking

The tool tracks three things from iteration to iteration:

  • AMI (Adjusted Mutual Information): Measures clustering stability between iterations (0-1 scale). This is what decides convergence
  • Global gap metrics: Tracks barcode gap quality across all clusters, for the summary report
  • Unchanged neighborhoods: A neighborhood whose result was unchanged is not clustered again until it changes

Refinement continues until an iteration changes nothing (AMI = 1.0) or the maximum number of iterations is reached. Within an iteration, a cluster whose neighborhood another scope already covers waits for the next one, so an unchanged iteration is followed by one more that examines the clusters still waiting. The run is converged when that iteration changes nothing either. (With --accept all, the first unchanged iteration ends the run.)

Advanced Options

# Custom convergence parameters
gaphack-refine --input-dir clusters/ \
               --output-dir refined/ \
               --max-iterations 40 \
               --max-scope-size 500

# Use BLAST instead of vsearch for proximity graph
gaphack-refine --input-dir clusters/ \
               --output-dir refined/ \
               --search-method blast

# Short forms, 8 worker processes, no progress bars, debug log
gaphack-refine -i clusters/ -o refined/ -t 8 --no-progress -v

Output Organization

refined/
├── 20251013_143055_final/              # Timestamped results
│   ├── cluster_00001.fasta             # Refined clusters (by size)
│   ├── cluster_00002.fasta
│   ├── ...
│   ├── unassigned.fasta                # Only if the input had one; passed through unchanged
│   ├── cluster_mapping.txt             # Original → final cluster ID mapping
│   ├── cluster_summary.tsv             # Per cluster: size, pieces, width, nearest cluster, gap
│   ├── cluster_pieces.tsv              # Per sequence: its cluster and its piece of that cluster
│   └── refine_summary.txt              # Detailed summary report
├── latest -> 20251013_143055_final/    # Symlink to most recent
├── 20251013_143022_iter001/            # Checkpoint after iteration 1: clusters and state.json
├── 20251013_143022_iter002/
└── ...

With --no-timestamp the result files are written directly into the output directory.

The summary report includes:

  • Iteration statistics and convergence metrics
  • Global gap metrics at each iteration
  • Cluster count changes and AMI scores
  • Per-iteration timing breakdown

Analysis Tool (gaphack-analyze)

The gaphack-analyze tool evaluates pre-clustered FASTA files to assess distance distributions and barcode gap quality:

# Analyze pre-clustered files (each FASTA = one cluster)
gaphack-analyze cluster1.fasta cluster2.fasta cluster3.fasta

# Save results to custom directory with JSON format
gaphack-analyze *.fasta -o analysis_results --format json

# Skip plots and use TSV output (-o is a folder; this writes tables/analysis_report.tsv)
gaphack-analyze clusters/*.fasta --no-plots --format tsv -o tables/

# Orient the sequences first, and measure distances as releases before 0.8.0 did
gaphack-analyze clusters/*.fasta --organism F --hp-normalize-min-length 1 --distance spoa

--organism, --hp-normalize-min-length and --distance work as in the other commands (see Strand Orientation, Homopolymer Run Length and How Pairs Are Aligned). Analyze clusters with the settings they were made with. Every pair of sequences is aligned once, within clusters and between them, on all cores unless -t says otherwise: allow for about 2.3 ms per pair per core.

Every distance in the report is a pair's mismatches divided by one length, the median length of all the sequences analyzed, which the report states. Distances within a cluster and distances between clusters are therefore on one scale, and the barcode gap is their plain difference. Before 0.8.0 each cluster was divided by its own median length. The JSON report records both settings, and how many sequences of each cluster orientation left out.

Analysis Output:

  • Individual cluster histograms: Distance distributions within each cluster
  • Global distance histogram: Combined intra-cluster vs inter-cluster distances
  • Percentile analysis: P5, P25, P50, P75, P95 values for all distance sets
  • Barcode gap metrics: Gap size and existence at P90/P95 levels
  • Multiple formats: Text reports, JSON data, or TSV tables

BLAST Analysis (gaphack-blast)

The gaphack-blast tool analyzes BLAST search results to identify conspecific sequences - hits that belong to the same species/OTU as your query:

# Basic usage - query is first sequence in FASTA
cat query.fa blast_hits.fa | gaphack-blast > results.json

# From file
gaphack-blast combined_sequences.fasta -o results.json

# Human-readable output
gaphack-blast sequences.fasta --format text

# Tab-separated for spreadsheets
gaphack-blast sequences.fasta --format tsv

# Also find the cluster nearest to the query's and compare the two
gaphack-blast sequences.fasta --nearest-cluster

# One SPOA alignment of the page instead of aligning each pair: about ten times faster
gaphack-blast sequences.fasta --distance spoa

The query's cluster grows as in gaphack --target, with the same defaults: a hit joins when the 95th percentile of its distances to the cluster's members allows it (--target-percentile). Before 0.8.0 gaphack-blast used the largest distance instead; --target-percentile 100 still does.

Key output fields:

  • in_query_cluster: Boolean indicating if sequence is conspecific with query
  • identity_to_query: MycoBLAST-adjusted identity percentage
  • barcode_gap_found: Whether a clear species boundary was detected
  • gap_size_percent: Magnitude of the barcode gap
  • nearest_cluster (with --nearest-cluster): the cluster grown from the closest sequence outside the query cluster, and the barcode gap between the two at P90, P95 and P100

For detailed field documentation and integration patterns, see docs/blast_analysis_integration.md.

Python API

Basic Usage

import numpy as np
from gaphack import GapOptimizedClustering, resolve_core_thresholds
from gaphack import load_sequences_from_fasta, calculate_distance_matrix


def main():
    # Load sequences
    sequences, headers, _ = load_sequences_from_fasta("input.fasta")

    # Calculate the distance matrix: every pair aligned on its own, with MycoBLAST-style
    # adjustments. This aligns in the current process. For more than a few hundred sequences
    # pass num_threads (None for every core). distance_method="spoa" gives the faster SPOA
    # distances.
    distance_matrix = calculate_distance_matrix(sequences)

    # The thresholds of the gaphack command: 6 and 12 mismatches at the median length, as the
    # distances that implement them (resolve_core_thresholds(length, 4, 16) for other counts)
    thresholds = resolve_core_thresholds(int(np.median([len(s) for s in sequences])))

    # Initialize clustering with custom parameters
    clustering = GapOptimizedClustering(
        min_split=thresholds.min_split,   # sequences up to 6 mismatches apart are lumped
        max_lump=thresholds.max_lump,     # clusters more than 12 mismatches apart stay split
        gap_method='local',      # Use local gap (default)
        alpha=0.5,               # Moderate parsimony (0.0=no penalty, 1.0=strong penalty)
        num_threads=None,        # Auto-detect cores (default), 0 for single-process
        show_progress=True,      # Show progress bar (default True)
        logger=None              # Use default logger (default None)
    )

    # Perform clustering
    clusters, singletons, metrics = clustering.cluster(distance_matrix)

    # Process results
    for i, cluster in enumerate(clusters):
        print(f"Cluster {i+1}: {[headers[idx] for idx in cluster]}")

    print(f"Singletons: {[headers[idx] for idx in singletons]}")
    print(f"Best gap size: {metrics['best_config']['gap_size']:.4f}")


# Worker processes start by importing this script again (on macOS and Windows), so whatever
# starts them must run under this guard. Here that is the clustering, with num_threads=None.
# With num_threads=0 everywhere nothing starts a process and the guard is not needed.
if __name__ == "__main__":
    main()

Using Pre-computed Distance Matrix (for Web Applications)

import numpy as np
from gaphack import GapOptimizedClustering

# If you have a pre-computed distance matrix (e.g., from a caching layer)
distance_matrix = np.array([...])  # Your distance matrix

# Cluster directly without calculating distances. num_threads=0 keeps it in this process:
# the default starts worker processes, which a web request should not do
clustering = GapOptimizedClustering(num_threads=0)
clusters, singletons, metrics = clustering.cluster(distance_matrix)

# The returned values use Python native types (no numpy) for JSON serialization
print(f"Gap size: {metrics['best_config']['gap_size']}")

Library Integration (Headless/Web Applications)

import logging
from gaphack import GapOptimizedClustering

# Configure for library usage - no progress bars, single-process, custom logger
app_logger = logging.getLogger("my_app.clustering")
clustering = GapOptimizedClustering(
    num_threads=0,        # Single-process mode for library integration
    show_progress=False,  # Disable progress bars in headless environment
    logger=app_logger     # Use your application's logger
)

# Silent clustering for web APIs or batch processing
clusters, singletons, metrics = clustering.cluster(distance_matrix)

# Results include cluster sizes in descending order
print(f"Created {len(clusters)} clusters: {[len(c) for c in clusters]}")

Input Expectations

gapHACk expects locus-trimmed sequences — for fungal ITS work, reads trimmed to the full ITS region (ITS1+5.8S+ITS2), e.g. via pyitsx/ITSx at intake. The algorithm itself is span-agnostic, but conserved SSU/LSU flanks left on some sequences dilute distances unevenly (flank match inflates identity for flanked pairs relative to trimmed ones), which distorts comparisons within a dataset. Trim once at intake with a pinned extractor version rather than at comparison time. Low-coverage fragments should also be excluded (see Known Limitation: Low-Coverage "Bridge" Sequences below).

Strand Orientation

All sequences must be on the same strand. A record on the reverse strand looks unrelated to its own species: in tests/test_data/russula_diverse_50.fasta two of the seven records of one species are reverse-complemented, and they come out as a cluster of their own.

--organism CODE (on all four commands) orients the sequences before anything else, using pyitsx with the ITSx profiles of that group (F for fungi). On that test file, --organism F puts all seven records in one cluster.

  • Sequences found on the reverse strand are reverse-complemented.
  • Sequences that pyitsx reports as chimeric, or cannot orient, are left out of the run and of the output. A warning names each one.
  • It needs the optional dependency, pip install "gaphack[orientation]", and the ITSx HMM profiles that pyitsx reads.

Distance Calculation

gapHACk uses the adjusted-identity package with standardized MycoBLAST-style adjustment parameters:

  • Homopolymer normalization: a length difference between two homopolymer runs that are both 6 bases or longer is not counted (AAAAAA vs AAAAAAA). Where either run is shorter, it is a mismatch (AAA vs AAAA, AAAAA vs AAAAAA). --hp-normalize-min-length N sets the run length; see below
  • IUPAC overlap handling: Enabled - ambiguity codes treated as matches when they overlap (e.g., R matches A or G)
  • Indel normalization: Enabled - contiguous indels counted as single evolutionary events
  • End skip distance: 0 bases - no terminal region trimming
  • Repeat motifs: only homopolymers (motif length 1) are normalized, not longer repeats

Only the homopolymer run length can be set from the command line. The other parameters are fixed, based on empirical validation with fungal ITS sequences.

Homopolymer Run Length

Sequencing errors in homopolymers grow with the length of the run, so a length difference in a long run says little, while one in a short run is as reliable as any other difference. --hp-normalize-min-length (default 6, on all four commands) is the shortest run whose length differences are ignored.

Releases before 0.8.0 ignored every homopolymer length difference, which is --hp-normalize-min-length 1. Distances are larger under the new setting, about 2 mismatches for close pairs of ITS sequences, so thresholds chosen for 0.7.x do not carry over (see Default thresholds).

How Pairs Are Aligned

Every command aligns each pair of sequences on its own by default (--distance affine): an affine-gap pairwise alignment with free end gaps, scored as above. A distance is the number of adjusted mismatches divided by the median length of the sequences in the run.

  • A pair's mismatches depend only on the two sequences. They are the same in gaphack, gaphack-blast, gaphack-analyze and gaphack-refine, whatever else is in the input and in whatever order
  • Distances do not depend on input order. The clusters still can, a little: where two merges are equally good, gaphack takes the one it meets first in the input. The 17 test groups described under Default thresholds split 42, 44 and 41 well-supported clades in three input orders
  • No external program is needed
  • It costs time. A pair of full ITS sequences takes about 2.3 ms on one core. gaphack and gaphack-analyze align every pair, on all cores (-t). gaphack --target and gaphack-blast align only the pairs the growing cluster needs, about half the pairs of a page of BLAST hits; gaphack-blast does it in one process

--distance spoa, on any of the commands, reads all distances from one SPOA multiple sequence alignment of the input instead, as every release before 0.8.0 did (gaphack-refine makes one alignment per scope):

  • Much faster: for 500 ITS sequences SPOA took about 9 seconds, against about 290 core-seconds for all the pairs
  • A pair's distance depends on the other sequences and on input order: SPOA adds sequences one at a time. The same 17 test groups split between 64 and 78 well-supported clades in three input orders
  • SPOA must be installed, and if it fails the run stops with an error

What this means for each command:

Command Clusters, pairwise against SPOA Time, pairwise against SPOA
gaphack Fewer well-supported clades split (42 against 71; 39 against 55 on two held-out families). Agreement with curated names is better on the first (per-name F1 0.928 against 0.905) and level on the second (0.814 against 0.818) 500 sequences on 18 cores: 50 s against 32 s (26 s against 9 s with --gap-method global)
gaphack --target, gaphack-blast Equal at the default --target-percentile 95 (F1 0.899 both; 0.887 both on pages from two held-out families); level at 100 too (0.906 against 0.902) A page of 50 hits: 1.5 s against 0.1 s. 100 hits: 3.5 s, up to 14 s, against 0.3 s
gaphack-analyze The distances of the clusters it reports on, if they were made with the defaults The same 500 sequences in 37 clusters: 32 s against 10 s
gaphack-refine See Context-free Distances Only the pairs it needs are aligned, and --distance-cache keeps them

For gaphack --target and gaphack-blast the gain is consistency with the other commands, not better clusters, and the page takes about ten times as long. Where that time matters more, as in a web service, --distance spoa (BlastAnalyzer(distance_method="spoa")) gives the earlier behavior.

For Library Users

If you're integrating gapHACk into a web application or need custom distance calculations:

import numpy as np
from gaphack import GapOptimizedClustering

# Calculate your own distance matrix
# (e.g., using cached alignments, custom algorithms, etc.)
distance_matrix = your_distance_calculation(sequences)

# Pass directly to the clustering algorithm
clustering = GapOptimizedClustering()
clusters, singletons, metrics = clustering.cluster(distance_matrix)

This approach is useful for:

  • Web applications with caching layers
  • Integration with existing alignment pipelines
  • Using specialized distance metrics
  • Avoiding redundant distance calculations

Parameters

Algorithm Parameters

  • --min-split-mismatches (default: 6 on full ITS): Sequences and clusters up to this many mismatches apart are lumped together (assumed intraspecific). See Default thresholds for why it is 6.
  • --max-lump-mismatches (default: 12 on full ITS): Clusters more than this many mismatches apart are kept split (assumed interspecific).
  • min_split, max_lump (library classes; defaults 0.01 and 0.02): the same two thresholds as distances, for GapOptimizedClustering and TargetModeClustering, which cluster a distance matrix and know no lengths. resolve_core_thresholds(length) gives the distances for the commands' counts. On the command line --min-split and --max-lump take such fractions and are deprecated.
  • gap_method (default: 'local'): Gap calculation method - 'local' (recommended) or 'global' (for literature comparison). The global gap is computed from counts of each distinct distance, which is far faster than the local gap on inputs of several hundred sequences and gives the same result as before.
  • alpha (default: 0.0): Parsimony parameter for local gap method. Controls cluster count preference (0.0=maximize total gap, 1.0=mean gap per cluster).
  • target_percentile (default: 95): Which percentile to use for gap optimization. In target mode (--target) it is the percentile for linkage and gap; in full clustering it is only used with the global gap method.
  • hp_normalize_min_length (default: 6): Shortest homopolymer run whose length differences are ignored. See Homopolymer Run Length.
  • tie_break_epsilon (default: "auto"): Candidate merges whose gap scores fall in the same bucket of this width are ranked by merge distance, the closer pair first. "auto" is half of one mismatch at the median length, 1/(2 × median length). 0 turns it off, as before 0.8.0.

Refinement Parameters (gaphack-refine)

  • close_threshold (default: max_lump): Distance within which clusters are found as neighbors. On the command line it is --close-mismatches; --close-threshold is deprecated The RefinementConfig and refine_clusters defaults of the library are those of the command, except that the library writes no checkpoints unless asked. RefinementConfig.previous_algorithm() gives the configuration of releases before 0.8.0.

  • max_iterations (default: 100; 10 with accept="all"): Maximum refinement iterations before stopping. A run stopped by the limit has not settled: on a 8,808-sequence test set the result at iteration 20 differed visibly from the settled one at iteration 26

  • max_scope_size (default: 1000; max_full_gaphack_size in the library): Maximum sequences for full gapHACk refinement within a single scope

  • split_max_size (default: 300): Largest cluster the split pass examines

  • checkpoint_frequency (CLI default: 1, library default: 0): Checkpoint every N iterations (0=disabled). Each checkpoint is a full copy of the clusters

  • knn_neighbors (default: 20): K for K-NN cluster proximity graph

  • search_method (default: "vsearch"): Search method for proximity graph ("blast" or "vsearch")

  • threads (default: every core; num_threads in the library): Worker processes for the pairwise alignments and threads for the searches. 0 runs in a single process. Results do not depend on it

  • random_seed: ignored. Seeds are taken in a fixed order, so the same input always gives the same result (--random-seed is deprecated and has no effect)

  • fallback_cut (default: on, at 8 mismatches): Cut a scope with no barcode gap at a fixed distance

  • fallback_merge (default: on whenever the cut is): After that cut, merge clusters that no barcode gap separates, and report each cluster's pieces

Options the Commands Share

Option gaphack gaphack-blast gaphack-analyze gaphack-refine
--distance affine affine affine affine
--hp-normalize-min-length 6 6 6 6
--organism off off off off
--min-split-mismatches 6 6 4
--max-lump-mismatches 12 12 12
--target-percentile 95 95 95
--gap-method local global
-t, --threads every core one process, by design every core every core
-v, --verbose yes yes (and -q) yes yes (and --log-level)
-o base path of the cluster files, or a folder if it ends in / the result file (default: standard output) the report folder the output folder (--output-dir)

Two defaults differ on purpose. Min-split is 4 in gaphack-refine and 6 elsewhere because refinement has stages after its fast merge that the other commands lack (see Thresholds in Mismatches). The gap method differs for the reason given under When to Use Which Method.

Output Formats

  • FASTA format (default): Creates separate FASTA files for each cluster
    • basename.cluster_001.fasta, basename.cluster_002.fasta, etc.
    • basename.singletons.fasta for unclustered sequences (or basename.unclustereds.fasta in target mode)
    • Clusters ordered by size (001 = largest, 002 = second largest, etc.)
    • Cluster numbers are zero-padded for proper sorting
    • Uses two-line format (header + sequence on single line)
  • TSV format: Tab-separated values with columns sequence_id and cluster_id
  • Text format: Human-readable clustering report

Gap Calculation Methods

gapHACk provides two gap calculation methods that optimize for different scenarios:

The local gap method evaluates each cluster relative to its nearest neighbor cluster, using a multi-percentile calculation across percentiles [90, 95, 100]. This approach shares conceptual foundations with silhouette coefficients (Rousseeuw, 1987), a well-established cluster quality metric.

Relationship to Silhouette Coefficients

Both local gap and silhouette coefficients recognize that cluster quality should be evaluated locally rather than globally:

Silhouette Coefficient (Rousseeuw, 1987):

  • For each data point: s(i) = (b(i) - a(i)) / max{a(i), b(i)}
    • a(i) = mean distance to points in same cluster
    • b(i) = mean distance to nearest neighboring cluster
  • Averaged across all points
  • Range: -1 (poor) to +1 (excellent)

Local Gap (gapHACk):

  • For each cluster: gap = inter_lower - intra_upper
    • intra_upper = upper percentile of intra-cluster distances (e.g., P95)
    • inter_lower = lower percentile to nearest neighboring cluster (e.g., P5)
  • Multi-percentile [90, 95, 100] for robustness
  • Summed across clusters (or divided by num_clusters^alpha)

Both methods avoid the pitfall of global metrics where distant well-separated clusters can mask problems with nearby poorly-separated clusters. The key insight: a good cluster should be tight within itself AND well-separated from its nearest neighbor.

gapHACk's local gap adapts this principle for DNA barcoding by:

  • Using percentiles instead of means (more robust to outliers common in genetic data)
  • Operating at cluster level (biologically meaningful units) rather than individual sequences
  • Using raw genetic distances (interpretable as percent divergence) rather than normalized scores
  • Incorporating multi-percentile calculation [90, 95, 100] for additional robustness

How it works:

  • For each cluster, identifies its nearest neighbor cluster
  • Calculates gap at three percentiles (90th, 95th, 100th/max)
  • Sums these three gap values for each cluster
  • Total local gap = sum of all per-cluster gap scores

Advantages:

  • Robust to dataset heterogeneity: Each cluster only compares to its nearest neighbor, not all distant clusters
  • Handles high variance: Resistant to the variance problems that eliminate global gaps in many fungal genera (Wilson et al. 2023 found global gaps fail in >50% of macrofungal genera)
  • Multi-percentile robustness: Using [90, 95, 100] reduces sensitivity to arbitrary percentile choice and captures separation quality across the distribution
  • Prevents over-lumping: The 100th percentile (max) ensures outliers aren't ignored
  • Theoretically grounded: Builds on established cluster quality metrics from the statistical literature

Use when:

  • Working with real-world fungal datasets (recommended default)
  • Dataset may have heterogeneous divergence patterns
  • You want robust results across different taxonomic groups

Tuning with alpha parameter:

# Default: maximize total gap (no parsimony penalty)
gaphack sequences.fasta --gap-method local --alpha 0.0

# Moderate balance between gap size and cluster count
gaphack sequences.fasta --gap-method local --alpha 0.5

# Favor fewer, larger clusters (mean gap per cluster)
gaphack sequences.fasta --gap-method local --alpha 1.0

The alpha parameter controls cluster count preference via score = local_gap / (num_clusters^alpha):

  • α = 0.0 (default): No parsimony penalty - maximizes sum of gaps (favors more clusters/splitting)
  • α = 0.5: Moderate balance - scales gap by square root of cluster count
  • α = 1.0: Strong parsimony - uses mean gap per cluster (favors fewer clusters/lumping)

Global Gap Method (For Literature Comparison)

The global gap method pools all intra-cluster distances and all inter-cluster distances, then calculates the gap at a single percentile (default 95th):

How it works:

  • Pools ALL intra-cluster distances across all clusters
  • Pools ALL inter-cluster distances across all cluster pairs
  • Gap = 5th percentile of inter - 95th percentile of intra (for P95)

Use when:

  • Comparing results to published barcode gap studies (Wilson et al. 2023, etc.)
  • Running diagnostic comparisons between methods
  • Dataset has low variance and well-separated groups

Important limitations (from Wilson et al. 2023):

  • Sensitive to dataset composition - one distant cluster pair can mask close pairs
  • Fails to find gaps in many real-world datasets (>50% of macrofungal genera)
  • High variance in either distribution can eliminate the gap
# Global gap for literature comparison
gaphack sequences.fasta --gap-method global --target-percentile 95

When to Use Which Method

Scenario Recommended Method Why
Default/General use Local (α=0.0) Most robust for real datasets
Conservative clustering Local (α=0.5 to 1.0) Favors fewer, larger clusters
Literature comparison Global Match published studies
Clean, simple dataset Either Both should work
High variance dataset Local Global will likely fail
Diagnostic/validation Run both Compare results

gaphack defaults to the local gap and gaphack-refine to the global gap inside its scopes, and both were measured. On whole inputs of a few hundred sequences the local gap split fewer well-supported clades than the global gap (44 against 67 on 17 test groups), and the global gap could not separate the two close species of tests/test_data/russula_kat_oly_191.fasta at any setting. Inside refinement, where a scope is one small neighborhood, the global gap agreed better with supertree clades and curated names on test sets of 4,610 sequences and up, and the handling of neighborhoods without a gap is built on it.

Algorithm Details

Note: Throughout this documentation, "species" refers to Operational Taxonomic Units (OTUs) - clusters of sequences that are presumed to represent biological species based on genetic similarity, but have not been formally taxonomically validated.

Core Algorithm (gaphack)

Distance Matrix Calculation

gapHACk begins by calculating a pairwise distance matrix from input sequences:

  1. Alignment: Each pair of sequences is aligned on its own (affine gaps, free end gaps). With --distance spoa, one SPOA alignment of all sequences is made instead
  2. Distance Scoring: The aligned pair is scored using adjusted identity

A distance is the number of adjusted mismatches between two sequences divided by the median sequence length. See How Pairs Are Aligned.

Distance calculation: gapHACk scores alignments with MycoBLAST-style adjusted identity parameters. This applies corrections for sequencing artifacts (long homopolymer runs), ambiguous bases (IUPAC codes), and indel events to produce cleaner distance estimates that better reflect biological relationships.

The distance matrix forms the foundation for all subsequent clustering decisions.

Barcode Gap

The barcode gap is the separation between the maximum intra-species distance and the minimum inter-species distance. A clear gap indicates good species delimitation, allowing confident assignment of sequences to species clusters.

Percentile Gaps

Instead of using absolute max/min values (which are sensitive to outliers), gapHACk uses percentile-based gaps for robustness:

  • P95 gap: 95th percentile of intra-species distances vs 5th percentile of inter-species distances
  • P90 gap: 90th percentile of intra-species distances vs 10th percentile of inter-species distances

This approach compares the "worst case" within species (upper percentile of intra-species distances) against the "best case" between species (lower percentile of inter-species distances), creating a conservative measure of separation that is robust to outliers.

The target_percentile parameter (default: 95) determines which percentile gap to optimize during clustering.

Two-Phase Clustering Strategy

Phase 1: Fast Greedy Merging

  1. Start with each sequence as its own cluster
  2. Merge all clusters up to min_split apart (default: 6 mismatches, about 1% of full ITS)
  3. No gap calculation needed - assumes these are all intraspecific variation
  4. Provides rapid initial clustering of clearly related sequences

Phase 2: Gap-Optimized Merging Between min_split and max_lump (default: 12 mismatches, about 2%):

  1. Merge evaluation: For each potential cluster merge, calculate the resulting gap metrics
  2. Percentile linkage: Use a high percentile (the 95th by default) of the pairwise distances between clusters for merge decisions - more conservative than average linkage
  3. Gap tracking: Monitor the target_percentile gap size and record the configuration with the best gap
  4. Gap-based heuristic: At each step, choose the merge that maximizes the barcode gap
  5. Termination condition: Stop when all remaining merges exceed max_lump
  6. Best tracking: Track and return the clustering configuration that achieved the best gap

Parameter Roles

  • min_split: Defines the boundary between Phase 1 (fast lumping) and Phase 2 (gap optimization). Sequences closer than this are assumed to represent intraspecific variation and are lumped together.

  • max_lump: Upper limit for cluster lumping. Distances beyond this are assumed to represent interspecific divergence and clusters are kept split. Enforced via percentile linkage on the distances between the two clusters being considered, so a small fraction of pairs (above the linkage percentile) may exceed it within a merged cluster.

  • target_percentile: Which percentile to use for gap optimization and linkage decisions (e.g., 95 = P95 gap). Higher percentiles are more robust to outliers but may be less sensitive to true gaps.

Default thresholds

gaphack (full and target mode) and gaphack-blast take two thresholds, as whole numbers of mismatches at the median sequence length:

Option Default Meaning
--min-split-mismatches 6 Sequences and clusters up to this many mismatches apart are always merged
--max-lump-mismatches 12 Clusters more than this many mismatches apart are never merged

These defaults are for full ITS (median lengths of 500 to 699 bp). At other median lengths they scale with the length, and a warning asks you to set counts for that locus. Counts you give are used as they are. gaphack-refine sets its thresholds the same way; its min-split is 4 (see Thresholds in Mismatches).

Releases before 0.8.0 took fractions of the median length instead (--min-split 0.005 --max-lump 0.02). A distance is a number of mismatches divided by that length, so a fraction means different counts at nearby lengths: 0.01 is 5 mismatches at a median of 582 bp and 6 at 600. Full mode also merged strictly below the fraction and target mode at or below it, so the same number meant one mismatch less in one than in the other. From counts, both merge pairs of up to that many mismatches. --min-split and --max-lump still work and are deprecated: if either is given both thresholds are fractions, the other at 0.01 or 0.02, and the run says how many mismatches they come to.

In 0.7.x the default --min-split was 0.005, about 3 mismatches. That value suited the earlier distance measure, which ignored every difference in homopolymer length. Since 0.8.0 a length difference in a homopolymer run shorter than 6 counts as a mismatch (--hp-normalize-min-length, default 6), so the same two sequences are now farther apart. Among close pairs in our ITS test data the difference is about 2 mismatches: pairs that were 3 mismatches apart now average 4.3, and pairs that were 12 apart average 16. With --min-split left at 0.005, the fast merge stopped too early and species were split.

The new default comes from a sweep of both thresholds at the new homopolymer setting, compared with release 0.7.2. The last two columns are 0.8.0 at its default thresholds, with the two ways of aligning (see How Pairs Are Aligned). This first table is from the data the thresholds were chosen on; a held-out check follows it:

0.7.2 0.8.0 with --distance spoa 0.8.0 (default)
Full mode: well-supported supertree clades split 127 71 42
Full mode: agreement with curated names (mean per-name F1) 0.894 0.905 0.928
Target mode, --target-percentile 95 (the default): F1 against the query's curated name 0.882 0.899 0.899
Target mode, --target-percentile 100: F1 against the query's curated name 0.880 0.902 0.906
  • Full mode (local gap) was run on 17 groups of 161 to 438 ITS sequences, 4,795 in all, from Russulaceae, Polyporales, Mycenaceae and Cortinariaceae. Each group is a whole clade of a supertree of the same sequences, so every finer clade lies inside one group; fewer clades split is better. With --min-split 0.005 --max-lump 0.02, the thresholds of 0.7.x, the same groups split 224 clades with SPOA distances and 136 with pairwise ones.
  • Target mode was run on 480 simulated BLAST result pages: 240 query sequences from the same four families, each with its 50 or 100 nearest sequences. With 0.005 the F1 was unchanged but the clusters were tighter (recall fell by 0.04).
  • The range that works is wide. Results were steady for a min-split of 5 to 8 mismatches and a max-lump of 12 or more. Higher values start to merge distinct species: the two close Russula species in tests/test_data/russula_kat_oly_191.fasta merge at 9 mismatches (at 10 with SPOA distances).
  • Input order. With SPOA distances the alignment depends on input order, and so do the results: three orders of the 17 groups split between 64 and 78 clades. With the default, three orders split 42, 44 and 41. On tests/test_data/russula_diverse_500.fasta, with the records sorted by identifier, agreement with the names in the headers (adjusted Rand index) is 0.943, 0.941 and 0.971 for the three columns.
  • The thresholds were chosen on these same groups and pages, so the table above is not a held-out check.

A held-out check was made afterwards, once, on two families that took no part in any of these choices: Hymenogastraceae and Pezizales. The groups and pages were picked by the same rules: 7 groups of 240 to 427 sequences (2,230 in all) and 240 pages.

Two held-out families 0.7.2 0.8.0 with --distance spoa 0.8.0 (default)
Full mode: well-supported supertree clades split 58 55 39
Full mode: agreement with curated names (mean per-name F1) 0.835 0.818 0.814
Target mode, --target-percentile 95 (the default): F1 against the query's curated name 0.882 0.887 0.887

It repeats the gain over 0.7.2 only in part:

  • Fewer clades are split, but less surely. The difference from 0.7.2 is 19 clades, and its 95% interval runs from 41 fewer to none.
  • Agreement with names is not better. Mean per-name F1 is 0.022 lower than for 0.7.2, a difference inside its interval (-0.049 to +0.005). Counting only published names, without provisional ones, it is 0.043 lower (0.816 against 0.859), which is outside its interval.
  • The two families differ. In Pezizales the default split 10 clades against 21, with the same agreement with names (0.856 against 0.849). In Hymenogastraceae it split 29 against 37, a difference inside its interval, and agreed less well with names (0.791 against 0.828): it merges some close species that 0.7.2 kept apart, for example in Psilocybe and Deconica. Across both families, the 17 names that lost 0.1 or more of F1 this way lie a median of 4 to 8 mismatches from the names they were merged with.
  • Target mode is level with 0.7.2, not ahead of it. At --target-percentile 100, the default of gaphack-blast in 0.7.2, release 0.7.2 scored 0.888.

Min-split must stay below max-lump: a run whose thresholds contradict each other stops before anything is aligned. The library classes do not stop; they log a warning when min_split is above max_lump.

--distance spoa --hp-normalize-min-length 1 --min-split 0.005 gives the alignment, distance measure and thresholds of 0.7.x; for gaphack-blast add --target-percentile 100.

Known Limitation: Low-Coverage "Bridge" Sequences

Partial sequences covering only conserved regions can distort clustering. A sequence that spans few of the sites discriminating two divergent lineages appears near-identical to both, so the agglomerative merge path can join lineages through it — after which no partition on the path can separate them. If clustering unexpectedly lumps groups you believe are distinct, check for short or low-coverage members sitting at high identity to multiple groups; prefiltering such sequences (e.g. scored span below ~90% of the cluster median) and assigning them afterward by identity margin typically restores the expected structure. This artifact is not specific to gapHACk — the same sequences also produce spurious results in phylogenetic tree methods.

Iterative Refinement (gaphack-refine)

The gaphack-refine tool optimizes cluster boundaries through iterative neighborhood-based refinement. This approach is designed to work with any initial clustering, whether from vsearch, CD-HIT, MMseqs2, or gaphack itself.

Refinement Process

  1. Build Proximity Graph: Create K-NN graph of cluster medoids using vsearch or BLAST
  2. Select Seed Clusters: Process each cluster as a seed, in a fixed order (see below)
  3. Build Refinement Scope: For each seed, up to max_scope_size sequences in all:
    • The seed and the clusters within max_lump of it: these may be merged or split
    • Context clusters from there out to close_threshold: these take part in the gap calculation and are never changed. At the defaults close_threshold equals max_lump, so there are none
  4. Apply Full gapHACk: Run complete gap-optimized clustering on the scope
  5. Update Clusters: Replace the scope's clusters with the result if it differs, and if the acceptance rule keeps it
  6. Check Convergence: Repeat iterations until one changes nothing (AMI = 1.0) and every cluster's own neighborhood has been examined on the final clusters, or the maximum number of iterations is reached

Distances in Refinement

By default every pair is aligned on its own (an affine-gap pairwise alignment with free end gaps), so its distance is the same in every scope it appears in, and in every run. Only the pairs that refinement needs are aligned, and --distance-cache DIR keeps them for later runs. See Context-free Distances.

With --distance spoa, each scope gets one SPOA multiple sequence alignment of its sequences instead, as in releases before 0.8.0. A pair's distance then depends on which other sequences share its scope, and on their order.

Convergence Criteria

  • AMI = 1.0: Perfect agreement between input and output (no changes), confirmed by an iteration that examines every neighborhood the unchanged iteration skipped
  • Iteration Limit: Maximum of 100 iterations by default (10 with --accept all, in the library). A run stopped by the limit has not converged, and says so

Two more things are tracked along the way, and neither decides convergence:

  • Per-scope Results: A neighborhood whose result was unchanged is not clustered again until its sequences or clusters change
  • Global Gap Metrics: Barcode gap quality across all clusters (each against its 3 nearest), reported per iteration to follow progress

Deterministic Seed Prioritization

Seeds are processed in a fixed order:

  • Clusters whose sequences have been reclustered fewer times come first, which gives every neighborhood its turn
  • Among those, larger clusters come first, and remaining ties are decided by the sequences themselves, not by names or input order
  • Nothing is random, so the same input always gives the same result. --random-seed is deprecated and has no effect

Prior Art in Barcode Gap Discovery

gapHACk shares conceptual similarities with ABGD (Automatic Barcode Gap Discovery; Puillandre et al., 2012), which also automatically identifies the barcode gap for species delimitation. Both methods:

  • Seek to identify the threshold between intraspecific and interspecific genetic variation
  • Use pairwise distance matrices as input
  • Apply recursive partitioning to handle heterogeneity across taxa

Key differences in gapHACk's approach:

  • Clustering algorithm: gapHACk uses hierarchical agglomerative clustering with dynamic gap optimization, while ABGD uses graph-based partitioning with fixed thresholds
  • Gap-based optimization: gapHACk uses a gap-based heuristic that directly optimizes for the barcode gap at each merge, rather than recursive application of fixed thresholds
  • Distance calculation: gapHACk implements the adjusted identity algorithm (Russell, 2025), which systematically corrects for sequencing artifacts and biological complexity that can obscure true genetic distances
  • Percentile-based robustness: gapHACk uses percentile gaps (e.g., P95) to handle outliers, rather than absolute min/max values
  • Refinement at scale: gaphack-refine re-clusters overlapping neighborhoods of an existing clustering, so the gap optimization reaches datasets far too large to cluster in one piece

Empirical Support for Dynamic Thresholds

Wilson et al. (2023) demonstrated substantial variation in barcode gaps across 11 macrofungal genera, with the middle of barcode gaps ranging from <2% to nearly 6%. Their findings validate gapHACk's approach of dynamically optimizing thresholds within user-specified ranges (default: 1-2% distance) rather than relying on fixed universal cutoffs. The --min-split-mismatches and --max-lump-mismatches parameters allow users to adjust these ranges based on their knowledge of the taxonomic group being studied.

Adjusted Identity Algorithm

The adjusted identity algorithm (Russell, 2025) addresses critical issues with raw NCBI BLAST identity scores. As published, it makes several key corrections:

  • Homopolymer normalization: Differences in homopolymer run lengths (e.g., AAA vs AAAA) are not counted as mismatches, addressing common sequencing artifacts
  • Ambiguity code handling: IUPAC codes are treated as matches when they overlap (e.g., R matches A or G)
  • End trimming: Mismatches within the first and last 20 bases are excluded, as these regions often contain editing artifacts
  • Gap event counting: Indels are counted as single evolutionary events rather than per-base penalties

gapHACk applies two of these differently: it ignores homopolymer length differences only in runs of 6 bases or more, and it trims no bases at the ends. Distance Calculation lists the settings it uses.

These adjustments can substantially improve identity scores, resulting in clearer barcode gaps and more reliable species delimitation. This is particularly important for fungal ITS sequences where sequencing artifacts are common.

For implementation details, see: https://github.com/joshuaowalker/adjusted-identity

Theoretical Foundations

Randriamihamison et al. (2021) provided theoretical support for using hierarchical clustering with general distance data. They showed that hierarchical clustering methods remain mathematically valid even when working with non-standard distance measures. This supports gapHACk's approach of dynamically adjusting thresholds to find meaningful gaps, rather than using fixed cutoffs.

Project Structure

gaphack/
├── gaphack/                     # Main package code
│   ├── __init__.py
│   ├── core.py                 # Core clustering algorithm
│   ├── gap_histogram.py        # Global gap from counts of each distinct distance
│   ├── target_clustering.py    # Target mode clustering
│   ├── cluster_refinement.py   # Iterative refinement
│   ├── refine_distances.py     # Context-free pairwise distances and their cache
│   ├── refine_thresholds.py    # Refinement thresholds in whole mismatches
│   ├── refine_acceptance.py    # Which scope results refinement keeps
│   ├── refine_nogap.py         # Neighborhoods without a barcode gap: merge and pieces
│   ├── refine_final.py         # Split pass and singleton placement
│   ├── refine_partials.py      # Setting aside and placing partial sequences
│   ├── refinement_types.py     # Refinement tracking types
│   ├── cluster_graph.py        # Cluster proximity graph
│   ├── blast_neighborhood.py   # BLAST neighborhood finder
│   ├── vsearch_neighborhood.py # vsearch neighborhood finder
│   ├── neighborhood_finder.py  # Neighborhood finding utilities
│   ├── distance_providers.py   # Distance calculation providers
│   ├── utils.py                # Utility functions and alignment
│   ├── version.py              # Package version
│   ├── cli.py                  # Main gaphack CLI
│   ├── refine_cli.py           # Refinement CLI
│   ├── analyze.py              # Analysis functions
│   ├── analyze_cli.py          # Analysis tool CLI
│   ├── blast_analysis.py       # BLAST result analysis
│   └── blast_cli.py            # BLAST analysis CLI
├── docs/                        # Documentation
│   └── blast_analysis_integration.md  # BLAST integration guide
├── tests/                       # Unit and integration tests
├── examples/                    # Example datasets and documentation
│   ├── data/                   # Sample FASTA files
│   └── README.md               # Examples documentation
├── pyproject.toml              # Package configuration
└── README.md                   # This file

Development

Running Tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run with coverage
pytest --cov=gaphack

Code Style

# Format code
black gaphack tests

# Check style
flake8 gaphack tests

# Type checking
mypy gaphack

Citation

If you use gapHACk in your research, please cite:

Walker, J. (2025). gapHACk: Gap-Optimized Hierarchical Agglomerative Clustering
for DNA barcoding. https://github.com/joshuaowalker/gaphack

Key References

  • Puillandre, N., Lambert, A., Brouillet, S., & Achaz, G. (2012). ABGD, Automatic Barcode Gap Discovery for primary species delimitation. Molecular Ecology, 21(8), 1864-1877.
  • Randriamihamison, N., Vialaneix, N., & Neuvial, P. (2021). Applicability and interpretability of Ward's hierarchical agglomerative clustering with or without contiguity constraints. Journal of Classification, 38, 363-389.
  • Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53-65. https://doi.org/10.1016/0377-0427(87)90125-7
  • Russell, S. (2025). Why NCBI BLAST Identity Scores Can Mislead Fungal Identifications — And How to Improve Them. MycotaLab Substack. https://mycotalab.substack.com/p/why-ncbi-blast-identity-scores-can
  • Wilson, A.W., Eberhardt, U., Nguyen, N., et al. (2023). Does One Size Fit All? Variations in the DNA Barcode Gaps of Macrofungal Genera. Journal of Fungi, 9(8), 788. https://doi.org/10.3390/jof9080788

License

BSD 2-Clause License - see LICENSE file for details.

Acknowledgments

This tool was developed to provide practical, empirically validated approaches for DNA barcode clustering. The combination of gap-based optimization, context-free pairwise distances, and iterative refinement has proven effective for fungal ITS sequence datasets in our use cases. Example dataset includes Collybia nuda ITS sequences from public iNaturalist observations, used for testing and demonstration purposes.

Metadata

Release files for gaphack 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gaphack 0.8.0
File Size Uploaded Provenance Actions
gaphack-0.8.0.tar.gz 320.0 kB With provenance Details for gaphack-0.8.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gaphack 0.8.0
File Interpreter ABI Platform Actions
gaphack-0.8.0-py3-none-any.whl Python 3 none any Details for gaphack-0.8.0-py3-none-any.whl

Total release size: 506.5 kB

Release files / gaphack-0.8.0.tar.gz

Download URL gaphack-0.8.0.tar.gz
Size 320.0 kB
Tags Source
SHA-256 checksum
How to use checksums
6e603464152cd6c4c554a26545f2b0ff9875d03a16db24ac73b42f4d2c474bac
BLAKE2b-256 checksum
How to use checksums
4870904335aa39d3a2acaacc1fa2a0408a7fcb6693165a837e947ca28eeca3cf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Release files / gaphack-0.8.0-py3-none-any.whl

Download URL gaphack-0.8.0-py3-none-any.whl
Size 186.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b42b1df64b2838f7b4b3e7e75e772d45c30640149edc7fcd9ce82adee95c22b1
BLAKE2b-256 checksum
How to use checksums
431d39ac6d0db3c6a88954963071eb69992240f2ca1baf910aef78e60af51ec1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

Security for gaphack 0.8.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for gaphack-0.8.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 30, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page