Benchmark structural variants with Truvari
Two structural variant records can describe similar changes without carrying identical allele sequences. A benchmark therefore needs a matching rule as well as a truth VCF. Truvari compares variant type, position, size, and sequence, then assigns matches before it calculates precision and recall.
This lesson uses real HG002 insertions and deletions from the GIAB Tier 1 v0.6 benchmark on GRCh37. The comparison file is deliberately constructed from those records. We omit two variants, duplicate one record, and alter part of one insertion sequence. The resulting scores describe these controlled changes; they do not measure the accuracy of a variant caller.
Define the sample, reference, and regions
Section titled “Define the sample, reference, and regions”The example selects six insertions and six deletions on chromosome 20, each
between 50 and 500 bases. Every record has FILTER=PASS, an explicit allele
sequence, and a nonreference HG002 genotype. Each analysis window lies inside
the corrected GIAB v0.6.2 Tier 1 BED file, which excludes VDJ regions and the
sex chromosomes. These small, isolated windows keep the match assignments
inspectable. They do not represent genome wide performance.
VCF positions count the first reference base as one. BED starts count it as zero, and a BED interval excludes its end coordinate. The preparation script uses that conversion when it places each reference allele inside its window.
Download the lesson bundle.
It contains the source VCF subset, both BED files, the
source manifest, and the
executable example. The execution notes
also appear in the bundle as execution_notes.md. The run.sh command requires
the bti-advanced-dna:0.1.0 Podman image, whose build recipe is in the private
companion repository. That image recipe is not part of the public bundle.
The Python analysis requires Truvari 5.5.0, pysam 0.24.1, NumPy, and Matplotlib.
The source manifest records the upstream files, their SHA256 values, and the original identifier for every selected variant. The original VCF header names HG002 as the sample. Some variant identifiers contain another trio member’s name because they preserve a discovery record’s identifier; those prefixes must not replace the VCF sample column.
import csvimport hashlibfrom importlib.metadata import versionimport jsonfrom operator import itemgetterfrom pathlib import Pathimport shutilimport subprocessimport tempfile
import matplotlib.pyplot as pltimport numpy as npimport pysam
inputs = Path("inputs")output = Path("outputs")output.mkdir(exist_ok=True)manifest = json.loads((inputs / "source_manifest.json").read_text())for filename, expected in manifest["files"].items(): observed = hashlib.sha256((inputs / filename).read_bytes()).hexdigest() assert observed == expected, filenameregions = np.loadtxt(inputs / "hg002_analysis_regions.bed", dtype=int)tier1 = np.loadtxt(inputs / "hg002_tier1_chr20.bed", dtype=int)for chrom, start, end in regions: contained = (tier1[:, 0] == chrom) & (tier1[:, 1] <= start) contained &= tier1[:, 2] >= end assert contained.any()with pysam.VariantFile(inputs / "hg002_source_truth.vcf") as source: assert list(source.header.samples) == ["HG002"] assert "##reference=GRCh37\n" in str(source.header) source_records = list(source)assert len(source_records) == len(regions) == 12assert {item.info["SVTYPE"] for item in source_records} == {"INS", "DEL"}print("Sample: HG002; assembly: GRCh37; contig: 20")print("Source records:", len(source_records))print("Contained Tier 1 windows:", len(regions))print("Truvari:", version("truvari"))Sample: HG002; assembly: GRCh37; contig: 20Source records: 12Contained Tier 1 windows: 12Truvari: 5.5.0The reference bases remain those in the published GRCh37 VCF. Every variant is
sequence resolved, so this comparison does not require a FASTA to resolve
symbolic alleles. A VCF with <DEL> or <INS> records needs the appropriate
reference and, for insertions, sufficient allele information. Do not compare
these GRCh37 records directly with calls on GRCh38.
Construct a comparison with known changes
Section titled “Construct a comparison with known changes”We retain the real reference and alternate alleles for the baseline. The comparison omits its final two records and adds an extra copy of one retained deletion. The first insertion keeps its position, size, anchor base, and genotype, but selected bases within its inserted sequence change.
These changes have different consequences. An omitted baseline record creates a false negative. An extra copy must not match the same baseline record twice. The altered insertion tests whether sequence similarity, rather than exact text identity, determines a match.
def write_variants(records, destination): """Write and index a small VCF with explicit HG002 alleles.
Args: records: Dictionaries with VCF coordinates, alleles, and provenance. destination: Path for the BGZF VCF. """ header = pysam.VariantHeader() header.add_meta("reference", "GRCh37") header.contigs.add("20", length=63025520) header.add_meta("INFO", items=[ ("ID", "SVTYPE"), ("Number", 1), ("Type", "String"), ("Description", "Structural variant type"), ]) header.add_meta("INFO", items=[ ("ID", "SVLEN"), ("Number", 1), ("Type", "Integer"), ("Description", "Alternate length minus reference length"), ]) header.add_meta("INFO", items=[ ("ID", "SOURCE_ID"), ("Number", 1), ("Type", "String"), ("Description", "Identifier in the GIAB source VCF"), ]) header.add_meta("FORMAT", items=[ ("ID", "GT"), ("Number", 1), ("Type", "String"), ("Description", "Genotype"), ]) header.add_sample("HG002") with pysam.VariantFile(destination, "wz", header=header) as stream: for item in sorted(records, key=itemgetter("pos", "id")): record = stream.new_record( contig="20", start=item["pos"] - 1, stop=item["pos"] - 1 + len(item["ref"]), alleles=(item["ref"], item["alt"]), id=item["id"], filter="PASS", ) record.info["SVTYPE"] = item["type"] record.info["SVLEN"] = len(item["alt"]) - len(item["ref"]) record.info["SOURCE_ID"] = item["source_id"] record.samples["HG002"]["GT"] = item["gt"] stream.write(record) pysam.tabix_index(str(destination), preset="vcf", force=True)
baseline = []for index, record in enumerate(source_records, start=1): assert list(record.filter) == ["PASS"] assert len(record.alts) == 1 and record.contig == "20" gt = record.samples["HG002"]["GT"] assert gt in ((0, 1), (1, 0), (1, 1)) size = abs(len(record.alts[0]) - len(record.ref)) assert 50 <= size <= 500 baseline.append({ "id": f"truth_{index:02d}", "source_id": record.id, "pos": record.pos, "ref": record.ref, "alt": record.alts[0], "type": record.info["SVTYPE"], "gt": gt, })comparison = [dict(item, id=item["id"].replace("truth", "call")) for item in baseline[:-2]]assert comparison[0]["type"] == "INS"changed_allele = list(comparison[0]["alt"])substitution = {"A": "C", "C": "G", "G": "T", "T": "A"}for index in range(1, len(changed_allele), 10): changed_allele[index] = substitution[changed_allele[index]]comparison[0]["alt"] = "".join(changed_allele)assert comparison[2]["type"] == "DEL"comparison.append(dict(comparison[2], id="call_duplicate"))write_variants(baseline, output / "baseline.vcf.gz")write_variants(comparison, output / "comparison.vcf.gz")(output / "controlled_changes.json").write_text(json.dumps({ "omitted_truth_ids": [item["id"] for item in baseline[-2:]], "duplicated_truth_id": baseline[2]["id"], "altered_truth_id": baseline[0]["id"], "caller_performance": False,}, indent=2) + "\n")print("Baseline records:", len(baseline))print("Comparison records:", len(comparison))print("Controlled changes: two omissions, one duplicate, one altered allele")Baseline records: 12Comparison records: 11Controlled changes: two omissions, one duplicate, one altered alleleRun Truvari with explicit thresholds
Section titled “Run Truvari with explicit thresholds”Both runs require the same variant type, at most 500 bases of reference
distance, and at least 70% size similarity. They retain variants between 50
and 500 bases in both files. --pick single permits one match per record.
--passonly, --no-ref a, and the HG002 sample arguments make the filters
explicit. The BED file restricts both denominators to the selected windows.
The first run requires a sequence score of at least 0.9. The second requires 1.0. Truvari defines this score as one minus edit distance divided by the sum of the two allele lengths; it is not the fraction of matching bases in a fixed alignment. We disable sequence rotation here because corresponding records have the same position and the exercise isolates sequence changes.
def run_benchmark(label, sequence_threshold, input_dir, output_dir): """Run Truvari and preserve its result files from a fresh directory.
Args: label: Directory name for the retained output files. sequence_threshold: Minimum Truvari sequence similarity. input_dir: Directory containing the analysis BED file. output_dir: Directory containing both evaluated VCFs.
Returns: The Truvari summary dictionary. """ destination = output_dir / label destination.mkdir(exist_ok=True) with tempfile.TemporaryDirectory(prefix="bti_sv_") as scratch: run_path = Path(scratch) / "benchmark" command = [ "truvari", "bench", "--base", str(output_dir / "baseline.vcf.gz"), "--comp", str(output_dir / "comparison.vcf.gz"), "--output", str(run_path), "--bSample", "HG002", "--cSample", "HG002", "--includebed", str(input_dir / "hg002_analysis_regions.bed"), "--refdist", "500", "--pctseq", str(sequence_threshold), "--pctsize", "0.7", "--pctovl", "0", "--pick", "single", "--sizemin", "50", "--sizefilt", "50", "--sizemax", "500", "--passonly", "--no-ref", "a", "--no-roll", ] completed = subprocess.run( command, check=True, capture_output=True, text=True ) (destination / "command.json").write_text( json.dumps(command, indent=2) + "\n" ) (destination / "stderr.log").write_text(completed.stderr) for filename in ( "summary.json", "tp-base.vcf.gz", "tp-comp.vcf.gz", "fp.vcf.gz", "fn.vcf.gz", ): shutil.copyfile(run_path / filename, destination / filename) return json.loads((destination / "summary.json").read_text())
summaries = {}for label, threshold in (("sequence_090", 0.9), ("sequence_100", 1.0)): summaries[label] = run_benchmark(label, threshold, inputs, output) summary = summaries[label] print(label, "TP", summary["TP-base"], "FP", summary["FP"], "FN", summary["FN"]) print(f" Precision {summary['precision']:.4f}; " f"recall {summary['recall']:.4f}; F1 {summary['f1']:.4f}")sequence_090 TP 10 FP 1 FN 2 Precision 0.9091; recall 0.8333; F1 0.8696sequence_100 TP 9 FP 2 FN 3 Precision 0.8182; recall 0.7500; F1 0.7826The duplicate remains an extra comparison record under the one match rule. The stricter sequence threshold also changes whether the altered insertion matches. A higher score obtained by changing matching thresholds would describe a different benchmark rule, not an improvement in the calls themselves.
Verify assignments and denominators separately
Section titled “Verify assignments and denominators separately”Counting records in the result VCFs checks the reported denominators. A second calculation checks which isolated variants are eligible to match. It computes edit distance directly, without calling Truvari or its alignment library.
For this deliberately isolated input, a comparison record has at most one
eligible baseline record. The duplicate creates two candidates for one
baseline record, so the number of distinct eligible baseline identifiers is
the number of matches under --pick single. This shortcut would not solve
an ambiguous cluster with several competing baseline records.
def edit_distance(first, second): """Calculate Levenshtein distance with unit edit costs.
Args: first: First allele sequence. second: Second allele sequence.
Returns: Minimum count of substitutions, insertions, and deletions. """ previous = list(range(len(second) + 1)) for row_index, first_base in enumerate(first, start=1): current = [row_index] for col_index, second_base in enumerate(second, start=1): current.append(min( current[-1] + 1, previous[col_index] + 1, previous[col_index - 1] + (first_base != second_base), )) previous = current return previous[-1]
def eligible_matches(sequence_threshold, baseline_records, comparison_records): """Find eligible pairs for the isolated, same-position fixture.
Args: sequence_threshold: Minimum independently calculated sequence score. baseline_records: Baseline allele and coordinate dictionaries. comparison_records: Comparison allele and coordinate dictionaries.
Returns: Comparison identifiers mapped to their eligible baseline identifiers. """ matches = {} for candidate in comparison_records: eligible = [] for truth in baseline_records: if candidate["type"] != truth["type"]: continue if abs(candidate["pos"] - truth["pos"]) > 500: continue # Isolation ensures that only same-position pairs reach this step. assert candidate["pos"] == truth["pos"] key = "ref" if truth["type"] == "DEL" else "alt" first, second = truth[key], candidate[key] first_size, second_size = len(first) - 1, len(second) - 1 size_similarity = min(first_size, second_size) size_similarity /= max(first_size, second_size) distance = edit_distance(first, second) similarity = 1 - distance / (len(first) + len(second)) if size_similarity >= 0.7 and similarity >= sequence_threshold: eligible.append(truth["id"]) assert len(eligible) <= 1 matches[candidate["id"]] = eligible return matches
def read_ids(path): """Read unique record identifiers from a result VCF.
Args: path: Result VCF path.
Returns: A set of unique identifiers. """ with pysam.VariantFile(path) as stream: identifiers = [record.id for record in stream] assert len(identifiers) == len(set(identifiers)) return set(identifiers)
baseline_ids = {item["id"] for item in baseline}comparison_ids = {item["id"] for item in comparison}metric_rows = []for label, threshold in (("sequence_090", 0.9), ("sequence_100", 1.0)): eligible = eligible_matches(threshold, baseline, comparison) expected_ids = {truth_id for ids in eligible.values() for truth_id in ids} result_dir = output / label tp_base = read_ids(result_dir / "tp-base.vcf.gz") tp_comp = read_ids(result_dir / "tp-comp.vcf.gz") fp = read_ids(result_dir / "fp.vcf.gz") fn = read_ids(result_dir / "fn.vcf.gz") assert tp_base == expected_ids and fn == baseline_ids - expected_ids assert not tp_comp & fp and tp_comp | fp == comparison_ids matched_ids = [eligible[identifier][0] for identifier in tp_comp] assert set(matched_ids) == expected_ids assert len(matched_ids) == len(set(matched_ids)) tp = len(expected_ids) precision = tp / len(comparison) recall = tp / len(baseline) f1 = 2 * precision * recall / (precision + recall) summary = summaries[label] expected_counts = { "TP-base": tp, "TP-comp": tp, "FP": len(comparison) - tp, "FN": len(baseline) - tp, "base cnt": len(baseline), "comp cnt": len(comparison), } for key, expected in expected_counts.items(): assert summary[key] == expected, (label, key) assert np.allclose( [summary["precision"], summary["recall"], summary["f1"]], [precision, recall, f1], atol=1e-12, rtol=0, ) metric_rows.append({ "sequence_threshold": threshold, "tp": tp, "fp": len(fp), "fn": len(fn), "precision": precision, "recall": recall, "f1": f1, })with (output / "verified_metrics.csv").open("w", newline="") as stream: writer = csv.DictWriter( stream, fieldnames=metric_rows[0], lineterminator="\n" ) writer.writeheader() writer.writerows(metric_rows)print("Independent allele comparisons agree with both Truvari runs.")print("Every truth and comparison record belongs to one result partition.")print("Both precision denominators:", len(comparison))print("Both recall denominators:", len(baseline))Independent allele comparisons agree with both Truvari runs.Every truth and comparison record belongs to one result partition.Both precision denominators: 11Both recall denominators: 12Precision uses matched comparison records divided by all evaluated comparison
records. Recall uses matched baseline records divided by all evaluated baseline
records. Here the match counts are equal because each match has one record on
each side. Keep TP-base and TP-comp distinct when you inspect other
assignment policies or representations.
Show the effect of the sequence rule
Section titled “Show the effect of the sequence rule”fig, axes = plt.subplots(1, 2, figsize=(10, 4), constrained_layout=True)labels = ["Sequence score ≥ 0.90", "Sequence score = 1.00"]positions = np.arange(len(labels))for offset, key, color in ( (-0.22, "tp", "#337f8d"), (0, "fp", "#c47546"), (0.22, "fn", "#80699b"),): values = [row[key] for row in metric_rows] bars = axes[0].bar(positions + offset, values, 0.22, label=key.upper(), color=color) axes[0].bar_label(bars, padding=3)axes[0].set_xticks(positions, labels, fontsize=9)axes[0].set_ylabel("Variant records")axes[0].set_ylim(0, len(baseline))axes[0].legend(frameon=False)for key, marker in (("precision", "o"), ("recall", "s"), ("f1", "^")): axes[1].plot(positions, [row[key] for row in metric_rows], marker=marker, label=key.capitalize())axes[1].set_xticks(positions, labels, fontsize=9)axes[1].set_ylim(0, 1.05)axes[1].set_ylabel("Metric value")axes[1].legend(frameon=False, loc="lower left")fig.suptitle("Controlled comparison of HG002 records")fig.savefig(output / "structural_variants_thresholds.png", dpi=180)plt.close(fig)
The verified metric table and controlled change record make the two results traceable. The bundle also includes both evaluated VCFs. For a real caller benchmark, replace the constructed comparison with calls from the same sample and assembly, retain the complete applicable truth and confident regions, and fix the matching rules before you compare callers.
This benchmark covers isolated insertions and deletions. It does not evaluate inversions, translocations, unresolved breakends, or somatic variants. The record matches also do not replace a separate assessment of genotype or phase accuracy. A matching allele can carry the wrong genotype.
Scientific references
Section titled “Scientific references”English and colleagues, 2022 describe Truvari’s structural variant comparisons and the effect of matching rules on allele distinctions.
Zook and colleagues, 2020 describe the HG002 benchmark for sequence-resolved insertions and deletions and its Tier 1 regions.
Further reading
Section titled “Further reading”The GIAB v0.6 release notes describe the sample, GRCh37 assembly, filtering rules, and Tier 1 and Tier 2 regions. They explain why a truth VCF must be paired with its confident regions.
The Truvari benchmark documentation
explains comparison thresholds, record selection, and output fields. Use the
installed version’s truvari bench --help output when you reproduce a command.
The GIAB benchmark publication describes how the real benchmark records were integrated and assessed. It provides the evidence behind the source data rather than the controlled comparison constructed on this page.