본문으로 건너뛰기
cccskills
무료GitHub에 공개

bio-genome-intervals-coverage-analysis

Calculate read depth and coverage across genomic intervals using bedtools genomecov and coverage. Generate bedGraph files, compute per-base depth, and summarize coverage statistics. Use when assessing sequencing depth, creating coverage tracks, or evaluating target capture efficiency.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(4)

  • SKILL.md8.1 KB
  • examples/bedgraph_from_bam.sh2.4 KB
  • examples/coverage_analysis.py2.8 KB
  • usage-guide.md2.8 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Version Compatibility

Reference examples tested with: bedtools 2.31+, numpy 1.26+, pandas 2.2+, samtools 1.19+

Before using code patterns, verify installed versions match. If versions differ:

  • Python: pip show <package> then help(module.function) to check signatures
  • CLI: <tool> --version then <tool> --help to confirm flags

If code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.

Coverage Analysis

"Calculate sequencing coverage" → Compute per-base or per-region depth from BAM files to assess sequencing adequacy.

  • CLI: bedtools genomecov -ibam input.bam, samtools depth input.bam
  • Python: pybedtools.BedTool('input.bam').genome_coverage() (pybedtools)

Calculate coverage and depth across genomic regions using bedtools and pybedtools.

genomecov - Genome-wide Coverage

Per-base Coverage (bedGraph)

# Generate bedGraph from BAM (per-base depth)
bedtools genomecov -ibam alignments.bam -bg > coverage.bedGraph

# Include zero-coverage regions
bedtools genomecov -ibam alignments.bam -bga > coverage_with_zeros.bedGraph

# Split by strand
bedtools genomecov -ibam alignments.bam -bg -strand + > plus_strand.bedGraph
bedtools genomecov -ibam alignments.bam -bg -strand - > minus_strand.bedGraph

# Scale by total reads (RPM normalization)
TOTAL=$(samtools view -c alignments.bam)
SCALE=$(echo "scale=10; 1000000/$TOTAL" | bc)
bedtools genomecov -ibam alignments.bam -bg -scale $SCALE > normalized.bedGraph

# Use only 5' end of reads
bedtools genomecov -ibam alignments.bam -bg -5 > five_prime.bedGraph

# Use only 3' end of reads
bedtools genomecov -ibam alignments.bam -bg -3 > three_prime.bedGraph

Coverage Histogram

# Genome-wide coverage histogram
bedtools genomecov -ibam alignments.bam > coverage_hist.txt

# Output format: chr, depth, bases_at_depth, chr_size, fraction
# genome  0       1000000  10000000  0.1
# genome  1       5000000  10000000  0.5
# ...

Coverage from BED

# Coverage from BED intervals
bedtools genomecov -i regions.bed -g genome.txt -bg > coverage.bedGraph

# BED must be sorted
bedtools sort -i regions.bed | bedtools genomecov -i stdin -g genome.txt -bg > coverage.bedGraph

Python

import pybedtools

# From BAM
bam = pybedtools.BedTool('alignments.bam')
coverage = bam.genome_coverage(bg=True)
coverage.saveas('coverage.bedGraph')

# With zeros
coverage = bam.genome_coverage(bga=True)

# Normalized
coverage = bam.genome_coverage(bg=True, scale=0.001)

# From BED
bed = pybedtools.BedTool('regions.bed')
coverage = bed.genome_coverage(bg=True, g='genome.txt')

coverage - Coverage per Feature

Basic Coverage

# Calculate how much of each region in A is covered by B
bedtools coverage -a targets.bed -b reads.bed > coverage_per_target.bed

# Output adds 4 columns: overlaps, bases_covered, region_length, fraction
# chr1  100  200  region1  5  50  100  0.5

# From BAM
bedtools coverage -a targets.bed -b alignments.bam > coverage.bed

# Count only (no coverage calculation)
bedtools coverage -a targets.bed -b reads.bed -counts > counts.bed

Coverage Options

# Mean coverage per region
bedtools coverage -a targets.bed -b alignments.bam -mean > mean_coverage.bed

# Same strand only
bedtools coverage -a targets.bed -b alignments.bam -s > same_strand.bed

# Report depth at each position (histogram)
bedtools coverage -a targets.bed -b alignments.bam -d > per_base.bed

# Require minimum overlap
bedtools coverage -a targets.bed -b reads.bed -f 0.5 > min_overlap.bed

# Split alignments (for RNA-seq)
bedtools coverage -a exons.bed -b alignments.bam -split > exon_coverage.bed

Python

import pybedtools

a = pybedtools.BedTool('targets.bed')
b = pybedtools.BedTool('alignments.bam')

# Basic coverage
result = a.coverage(b)

# Mean coverage
result = a.coverage(b, mean=True)

# Counts only
result = a.coverage(b, counts=True)

# Per-base depth
result = a.coverage(b, d=True)

result.saveas('coverage.bed')

multicov - Counts Across Multiple BAMs

# Count reads in regions across multiple samples
bedtools multicov -bams sample1.bam sample2.bam sample3.bam -bed regions.bed > counts.txt

# Require mapping quality
bedtools multicov -bams sample1.bam sample2.bam -bed regions.bed -q 30 > counts.txt

# Split alignments
bedtools multicov -bams sample1.bam sample2.bam -bed regions.bed -s -split > counts.txt

Calculate Coverage Statistics

Mean/Median Depth

import pybedtools
import pandas as pd
import numpy as np

# Load coverage BED (from bedtools coverage -d)
bed = pybedtools.BedTool('per_base_coverage.bed')
df = bed.to_dataframe()

# Calculate stats per region
stats = df.groupby(['chrom', 'start', 'end']).agg({
    'score': ['mean', 'median', 'std', 'max']
}).reset_index()

print(stats)

Coverage Distribution

Goal: Parse a genome-wide coverage histogram to calculate mean sequencing depth and visualize the depth distribution.

Approach: Run bedtools genomecov to produce a histogram, parse the genome-wide depth and fraction columns, and compute weighted mean depth from the distribution.

import pybedtools

# Get coverage histogram
bam = pybedtools.BedTool('alignments.bam')
hist = bam.genome_coverage()

# Parse histogram
depths = []
fractions = []
for line in open(hist.fn):
    fields = line.strip().split('\t')
    if fields[0] == 'genome':
        depths.append(int(fields[1]))
        fractions.append(float(fields[4]))

# Calculate metrics
import numpy as np
mean_depth = sum(d * f for d, f in zip(depths, fractions))
print(f'Mean depth: {mean_depth:.1f}x')

Common Patterns

Target Region Coverage Summary

# Get per-region coverage stats
bedtools coverage -a targets.bed -b alignments.bam | \
    awk -v OFS='\t' '{
        mean = ($NF > 0) ? $5/$6 : 0;
        print $1, $2, $3, $4, $7, mean
    }' > summary.bed

# Regions with low coverage
bedtools coverage -a targets.bed -b alignments.bam | \
    awk '$NF < 0.8' > low_coverage.bed

Normalize to CPM (Counts Per Million)

import pybedtools

bam = pybedtools.BedTool('alignments.bam')

# Get total reads
import subprocess
result = subprocess.run(['samtools', 'view', '-c', 'alignments.bam'],
                        capture_output=True, text=True)
total_reads = int(result.stdout.strip())

# Generate CPM-normalized bedGraph
scale_factor = 1000000 / total_reads
coverage = bam.genome_coverage(bg=True, scale=scale_factor)
coverage.saveas('cpm_normalized.bedGraph')

Exon Coverage for RNA-seq

# Calculate coverage across exons (handling spliced reads)
bedtools coverage -a exons.bed -b alignments.bam -split > exon_coverage.bed

# Summarize by gene
awk -v OFS='\t' '{
    gene = $4; gsub(/_exon.*/, "", gene);
    sum[gene] += $NF * ($3-$2);
    len[gene] += $3-$2;
}
END {
    for (g in sum) print g, sum[g]/len[g];
}' exon_coverage.bed > gene_coverage.txt

bedGraph Format

# bedGraph: chr, start, end, value (0-based coordinates)
chr1    0       100     0
chr1    100     200     5.5
chr1    200     300     10.2
chr1    300     400     3.1

Key Parameters

ToolParameterDescription
genomecov -bgbedGraphOutput bedGraph format
genomecov -bgabedGraph allInclude zero coverage
genomecov -scaleNormalizeScale values by factor
coverage -meanMeanReport mean coverage
coverage -dPer-baseReport per-position depth
coverage -countsCountCount overlaps only
multicov -qQualityMinimum mapping quality

Related Skills

  • bigwig-tracks - Convert bedGraph to bigWig
  • alignment-files/sam-bam-basics - BAM processing
  • interval-arithmetic - Intersect with regions
  • chip-seq/chipseq-visualization - Peak coverage analysis

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Workflow for read alignment, sorting, indexing, mapping statistics, and downstream-ready alignment artifacts.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

BioTender-max/awesome-bio-agent-skills2042026년 7월 2일 업데이트

alphafold

무료

Validate protein designs using AlphaFold2 structure prediction. Use this skill when: (1) Validating designed sequences fold correctly, (2) Predicting binder-target complex structures, (3) Calculating confidence metrics (pLDDT, pTM, ipTM), (4) Self-consistency validation of designs, (5) Multi-chain complex prediction with AlphaFold-Multimer. For faster single-chain prediction, use esm. For QC thresholds, use protein-qc.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

BioTender-max/awesome-bio-agent-skills2042026년 7월 2일 업데이트

AlphaFold2 / AlphaFold-Multimer structure prediction for validation and confidence scoring. Use this skill when: (1) Validating designed sequences fold correctly, (2) Predicting binder-target complex structures, (3) Calculating confidence metrics (pLDDT, pTM, ipTM), (4) Self-consistency validation of designs, (5) Multi-chain complex prediction with AlphaFold-Multimer. For faster single-chain prediction, use esm2-sequence-scoring. For QC thresholds, use protein-design-qc.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

BioTender-max/awesome-bio-agent-skills2042026년 7월 2일 업데이트

Workflow for event-level and isoform-level splicing analysis with sashimi-ready outputs and splice QC.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

BioTender-max/awesome-bio-agent-skills2042026년 7월 2일 업데이트

atac-seq

무료

ATAC-seq processing with assay QC, MACS3 peak calling, consensus peak matrices, differential accessibility, and motif or footprint follow-up.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

BioTender-max/awesome-bio-agent-skills2042026년 7월 2일 업데이트

bindcraft

무료

End-to-end binder design using BindCraft hallucination. Use this skill when: (1) Designing protein binders with built-in AF2 validation, (2) Running production-quality binder campaigns, (3) Using different design protocols (fast, default, slow), (4) Need joint backbone and sequence optimization, (5) Want high experimental success rate. For backbone-only generation, use rfdiffusion. For QC thresholds, use protein-qc. For tool selection guidance, use binder-design.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

BioTender-max/awesome-bio-agent-skills2042026년 7월 2일 업데이트

BioTender-max의 스킬 모두 보기

이 스킬의 문제 신고