pyBigWig: Accessing BigWig Files

0.3.25 · active · verified Thu Apr 16

pyBigWig is a Python package providing efficient access to bigWig files, leveraging the underlying C library libBigWig. It enables reading genomic data stored in bigWig format and also supports creating and writing new bigWig files. The current version is 0.3.25, with frequent updates addressing bug fixes and build improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple bigWig file with dummy data, then open it in read mode to extract values, summary statistics, and intervals from specific genomic regions. It also shows the importance of closing the file handles.

import pyBigWig
import os

# Define a temporary bigWig file name
temp_bw_file = "temp_quickstart.bigWig"

# --- Writing a new bigWig file for demonstration ---
# Chromosome sizes are required for writing
chrom_sizes = {"chr1": 100000, "chr2": 50000}
bw_write = pyBigWig.open(temp_bw_file, "w")
bw_write.addHeader([(name, size) for name, size in chrom_sizes.items()])

# Add some dummy entries
bw_write.addEntries(
    ["chr1"] * 5,
    [0, 100, 200, 300, 400],
    [99, 199, 299, 399, 499],
    [0.1, 0.2, 0.3, 0.4, 0.5]
)
bw_write.addEntries("chr1", 5000, 5010, [1.0]*10, step=1, span=1)
bw_write.addEntries("chr2", 1000, 1005, [2.0]*5, step=1, span=1)
bw_write.close()
print(f"Created dummy bigWig file: {temp_bw_file}\n")

# --- Reading from the bigWig file ---
bw = pyBigWig.open(temp_bw_file)

print(f"Chromosomes found: {bw.chroms()}\n")

# Get values from a specific region on chr1
values_chr1 = bw.values("chr1", 0, 500)
print(f"Values on chr1 (0-500, first 10): {values_chr1[:10]}...\n")

# Get summary statistics for a region
summary_chr1 = bw.stats("chr1", 0, 1000, type="mean")
print(f"Mean value on chr1 (0-1000): {summary_chr1[0]}\n")

# Get intervals (start, end, value) for a region
intervals_chr1 = bw.intervals("chr1", 0, 1000)
print(f"Intervals on chr1 (0-1000, first 3): {intervals_chr1[:3]}...\n")

# Close the bigWig file to release resources
bw.close()

# Clean up the temporary file
if os.path.exists(temp_bw_file):
    os.remove(temp_bw_file)
    print(f"Cleaned up temporary file: {temp_bw_file}")

view raw JSON →