Skip to content
bdolmoPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

BAMulator

BAMulator simulates variants directly into existing BAM files while preserving the characteristics of the original sequencing data.

Supported variant types include:

  • SNVs
  • INDELs
  • CNVs
  • SVs (including balanced and whole-arm translocations)
  • Subclonal variants
  • Haplotype-based variants

Requirements

Input BAMs must be coordinate sorted and indexed.

Install the Python dependencies and build the simulation engine:

python3 -m pip install -r requirements.txt
make -C src

The wrapper expects Linux-compatible binaries at:

bwa/bwa
samtools/samtools

Optional phasing also requires java, bcftools, bgzip, and tabix on PATH.

Quick start

Variants can be provided in three ways:

  1. Use an existing VCF, BCF or BEDPE
  2. Generate a BAMulator config using the included scripts
  3. Write a BAMulator TSV manually

For most use cases, the first two options are recommended.

Use an existing VCF

python3 bamulator.py \
  --variants variants.vcf.gz \
  --sample_bam sample.bam \
  --reference hg38.fa \
  --output simulated

The main output is:

simulated/sample_merged.bam

To additionally emit the complete simulated read set as paired, gzipped FASTQ files, add --emit-fastq:

python3 bamulator.py \
  --variants variants.vcf.gz \
  --sample_bam sample.bam \
  --reference hg38.fa \
  --output simulated \
  --emit-fastq

This creates simulated/sample_R1.fastq.gz and simulated/sample_R2.fastq.gz. The files contain complete primary read pairs, including both unchanged and simulated reads. BAM output is still produced.

VCF, compressed VCF, BCF and BEDPE inputs are supported.

For multi-sample VCF/BCF files, use --sample_map to associate each sample with its BAM.

Generate variant configurations

BAMulator includes scripts to automatically generate variants from a BAM directory and a gene-panel BED.

Generate SNVs and indels

For example, generate 20 small variants:

python3 scripts/generate_indels_config.py \
  --indir /path/to/bams \
  --bed panel.bed \
  --genome hg38.fa \
  --num_variants 20 \
  --proportions 1 \
  --output variants.tsv

Then simulate them:

python3 bamulator.py \
  --variants variants.tsv \
  --reference hg38.fa \
  --output simulated

Exactly one of --indir or --list must be provided.

The SNV, insertion, deletion and delins rates must sum to 1.

Generate structural variants

For example, generate a set containing only deletions and duplications:

python3 scripts/generate_sv_config.py \
  --indir /path/to/bams \
  --bed panel.bed \
  --num_variants 20 \
  --proportions 1 \
  --deletion_rate 0.5 \
  --duplication_rate 0.5 \
  --inversion_rate 0 \
  --translocation_rate 0 \
  --output variants.tsv

Then run:

python3 bamulator.py \
  --variants variants.tsv \
  --reference hg38.fa \
  --output simulated

Non-zero SV rates are automatically normalized.

Manually define variants

Manual TSV files are useful when you want to simulate specific variants.

Small variant example

SAMPLE	CHROM	POS	REF	ALT	TYPE	CLONE	CLONAL_PROPORTION	GENOTYPE	ADDITIONAL_INFO
sample.bam	chr7	55259515	T	G	snv	clone1	1.0	0/1	EGFR_p.L858R

Run:

python3 bamulator.py \
  --variants variants.tsv \
  --reference hg19.fa \
  --output simulated

Supported small-variant types are:

snv
insertion
deletion
delins

POS is 1-based.

CLONAL_PROPORTION controls the fraction of the sample carrying the variant. For example:

1.0   clonal
0.5   50% of the sample
0.2   20% of the sample

An optional HAPLOTYPE column can be used for explicit allele-specific simulation.

For a small-variant pass run on an ASCN output BAM, add mutation_multiplicity=K to ADDITIONAL_INFO to mutate only the first K descendant copies of the selected parental haplotype. For example, a mutation with multiplicity 2 on the major allele of a 4+2 segment is applied to two of the four hap1 copies. K must not exceed the copy count of the selected haplotype. If mutation_multiplicity is omitted, all descendants of that haplotype retain the historical behavior and receive the mutation.

When ASCN and small variants share a CLONE, stable fragment selection makes the second pass a nested subset of the first. For tumor purity p, cancer-cell fraction f, total tumor copy number C, and mutation multiplicity K, use CLONAL_PROPORTION = p * f; the expected bulk-sample VAF is p * f * K / (p * C + 2 * (1 - p)).

Structural variant example

Structural variants use a different TSV format.

Example heterozygous deletion:

SAMPLE	CHR1	START1	END1	CHR2	START2	END2	SVTYPE	SVID	PLOIDY	SV_MECHANISM	NTINS	HOMOLOGY	CLONE	CLONAL_PROPORTION	ADDITIONAL_INFO	HAPLOTYPE
sample.bam	chr9	21970277	21975386	.	.	.	DEL	CDKN2A_del	1	random	.	.	clone1	1.0	.	1

Supported structural variant types are:

DEL
DUP
ASCN
INV
BALANCED_TRANSLOCATION
WHOLE_ARM_TRANSLOCATION

Common PLOIDY values:

PLOIDY Meaning
0 Homozygous deletion
1 Heterozygous deletion
2 Balanced event
3 One-copy gain
4 Two-copy gain

Native TSV breakpoint coordinates are 1-based.

ASCN represents an allele-specific copy-number segment without asserting a particular breakpoint mechanism. Set PLOIDY to total copy number and provide the target parental copy counts in ADDITIONAL_INFO:

SAMPLE  CHR1  START1  END1  ...  SVTYPE  SVID       PLOIDY  ...  ADDITIONAL_INFO             HAPLOTYPE
sample.bam chr17 1 20000000 ...  ASCN    chr17_loh  2       ...  major_cn=2;minor_cn=0       hap1

The engine assigns every fragment consistently to haplotype 1 or 2, treats haplotype 1 as the major allele, and emits the configured number of copies in the CLONAL_PROPORTION fraction. This supports CN-neutral LOH (2+0), balanced whole-genome duplication (2+2), and asymmetric amplification such as 4+2. ASCN models read depth and phased B-allele frequency; it does not invent tandem-junction reads for copy-number segments inferred without a known breakpoint structure.

When every row for a sample is ASCN and its segments do not overlap, BAMulator automatically uses a direct-BAM implementation. It traverses the coordinate-sorted input once, applies phased background SNVs in place, and drops or duplicates aligned read pairs without changing their coordinates. With --threads N greater than one, the reader feeds bounded 4,096-record chunks to N-1 simulation workers while the coordinating thread preserves the original record order during output. This parallelizes record decoding, copy selection, phasing, and editing without chromosome seeks, temporary BAM shards, or unbounded memory. --threads 1 retains the lower-overhead serial path.

The threaded implementation deliberately has only two roles. The coordinating thread is the only thread that reads and writes BAM data. Worker threads take complete chunks, transform their records, and mark the chunks ready. The coordinator can read the next chunk while workers process earlier ones, but it always waits for and writes the oldest chunk first. A small bounded queue (at most two chunks per worker) prevents a fast reader from consuming unbounded memory. The queue mutex protects only the short act of handing out a chunk; the expensive record transformation happens outside that lock.

The final indexed <sample>_merged.bam is written directly: no uncompressed FASTQs, untouched-read BAM, BWA realignment, or genome-wide read-name table is created. Mixed ASCN/non-ASCN inputs and overlapping ASCN segments retain the general FASTQ/remapping path. Use --legacy_ascn only to force that older path for comparison or troubleshooting.

SNV/indel-only runs preserve realistic realignment without materializing a full untouched-read BAM. BAMulator records the exact QNAMEs being replaced, remaps their modified read pairs with BWA, and streams the read-only source BAM directly into a coordinate merge while filtering those original QNAMEs. The source BAM and index are never modified. The final BAM is written to a temporary path, checked, and published with its index only after successful completion.

For point breakpoints such as translocations:

START1 = END1
START2 = END2

Disease presets

Ready-made variant configurations, curated from published hotspot and dosage-sensitivity data (COSMIC, ClinVar, ClinGen, OncoKB, and the primary literature), are available under:

scripts/presets/hg19/
scripts/presets/hg38/

Each build is organized by disease category:

scripts/presets/<build>/solid_tumors/
scripts/presets/<build>/hematological/
scripts/presets/<build>/germline/

For example:

python3 bamulator.py \
  --variants scripts/presets/hg19/solid_tumors/lung_cancer_small_variants.tsv \
  --reference hg19.fa \
  --output simulated

Edit the SAMPLE column in the preset before running.

Available preset groups include:

  • Solid tumors — NSCLC, melanoma, colorectal cancer, breast cancer, CNS / GBM, pancreatic cancer, prostate cancer, ovarian cancer, gastric cancer
  • Hematological — AML
  • Germline — rich neurological disease coverage plus a couple of cardiac CNVs:
    • Recurrent syndromic microdeletion/microduplication rearrangements: 22q11.2 (DiGeorge), 7q11.23 (Williams-Beuren), 17p12 (CMT1A/HNPP), 17p11.2 (Smith-Magenis/Potocki-Lupski), 17q11.2 (NF1 microdeletion), 15q11-q13 (Prader-Willi/Angelman), 1p36, 5p15 (Cri-du-chat)
    • Neurological repeat expansions: HTT (Huntington disease), FMR1 (Fragile X), DMPK (myotonic dystrophy type 1), ATXN1 (SCA1), ATXN3 (SCA3/Machado-Joseph), FXN (Friedreich ataxia), C9orf72 (ALS/FTD), AR (SBMA/Kennedy disease) — represented as a moderate, clearly-pathogenic-range repeat insertion rather than a specific patient's exact allele length; see the caveat below

Some panels have separate files for small variants and structural variants.

Variants that cannot be simulated together because they occupy the same position are stored in companion *_alternates.tsv files.

Each preset row carries a SOURCE column citing the database or publication backing that variant (e.g. COSMIC, ClinVar, ClinGen, STRchive, PMID:xxxxxxxx), so entries can be traced back to published evidence rather than taken on faith.

The repeat-expansion presets are simulated as ordinary insertion rows (reference anchor base + the repeat motif tiled out to a representative pathogenic-range copy count), which the engine handles like any other indel. Short-read alignment fundamentally cannot resolve a repeat's true length once it exceeds the read length — reads landing inside a large expansion just come back as pure repeat-motif sequence, which is itself a realistic signature of a real expansion, but not a way to recover an exact allele size. Treat these presets as "a pathogenic-range expansion is present at this locus" test fixtures for expansion-aware callers (ExpansionHunter, STRipy, GangSTR, etc.), not as a stand-in for a specific patient's measured repeat count.

Combining small and structural variants

Small variants and structural variants cannot currently be simulated in the same BAMulator run.

To simulate both, run BAMulator twice.

First simulate the structural variants:

python3 bamulator.py \
  --variants svs.tsv \
  --reference hg38.fa \
  --output sv_out

Then use the resulting BAM as the input for the small-variant configuration:

sv_out/sample_merged.bam

and run BAMulator again:

python3 bamulator.py \
  --variants snvs.tsv \
  --reference hg38.fa \
  --output final

Reproducible simulations

Use --seed to reproduce the same stochastic simulation:

python3 bamulator.py \
  --variants variants.tsv \
  --reference hg38.fa \
  --output simulated \
  --seed 42

The effective seed is logged for every run.

Outputs

A typical run produces:

sample_merged.bam
sample_merged.bam.bai

# With --emit-fastq:
sample_R1.fastq.gz
sample_R2.fastq.gz

sample_simulated.bam

sample_simulated_R1.fq
sample_simulated_R2.fq

sample_replacement_qnames.txt
sample_streaming_small.complete

sample_coverage_warnings.tsv

bamulator.truth.vcf

The replacement-QNAME files are produced for SNV/indel-only runs. Legacy and structural-variant workflows may instead retain sample_unsimulated.bam. The source BAM is always treated as read-only.

The main downstream file is:

sample_merged.bam

When --emit-fastq is enabled, the paired sample_R1.fastq.gz and sample_R2.fastq.gz files are collated by read name and contain only complete primary pairs; secondary, supplementary, orphan, and unpaired records are not included.

bamulator.truth.vcf contains the variants requested for the simulation.

sample_coverage_warnings.tsv reports variants with insufficient source coverage.

Check this file whenever a configured variant does not appear in the output.

Variants with zero or fewer than 10 overlapping read pairs are reported as coverage warnings.

Phasing

Optional phasing can be enabled with:

--phase_snvs

Example:

python3 bamulator.py \
  --variants deletions.tsv \
  --reference hg38.fa \
  --output simulated \
  --phase_snvs \
  --input_vcf_list vcfs/ \
  --genome_version hg38 \
  --map_dir maps/ \
  --ref_dir reference-panels/

Phasing allows nearby heterozygous SNVs to be retained on consistent parental haplotypes.

Supported genome labels are:

hg19
b37
hg38
b38

The optional HAPLOTYPE field can explicitly assign variants to:

maternal
paternal
both

Nearby variants assigned to the same parental haplotype remain in cis, while variants assigned to opposite haplotypes remain in trans.

Current limitations

  • Small variants and structural variants cannot be mixed in one run.
  • Mixed small/SV VCF or BCF inputs are rejected.
  • Background phasing currently supports SNVs but not background indels.
  • HOMOLOGY is parsed but is not currently applied to simulated sequences.
  • Phasing currently processes chromosomes 1–22 and X.
  • --suffix and --max_reads are accepted for compatibility but currently do not modify the corresponding engine behavior.
  • --minins and --maxins are accepted by the SV generator but currently unused. Breakpoint NTINS length is controlled with --ntmin and --ntmax.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages