You're looking for a comprehensive set of files for IGV! This is a great approach for visualizing your GenBank data effectively.
Here's how to get .bed, .gtf, .fa, .fa.fai, and .fa.sizes from a GenBank file using BioPython and samtools.
Prerequisites:
- Python 3: Ensure you have Python installed.
- BioPython: Install it via pip:
pip install biopython
- Samtools (optional but recommended for
.fa.fai): Download and install samtools from http://www.htslib.org/. Add it to your system's PATH. If you don't have samtools, IGV can often generate the .fai file itself upon loading a FASTA.
Python Script for Conversions (genbank_to_igv_formats.py)
This script will parse your GenBank file and generate the .fa, .fa.sizes, .bed, and .gtf files.
import os
from Bio import SeqIO
from Bio.SeqFeature import FeatureLocation, ExactPosition
def convert_genbank_to_igv_formats(genbank_file_path):
"""
Converts a GenBank file into FASTA (.fa), FASTA sizes (.fa.sizes),
BED (.bed), and GTF (.gtf) formats, suitable for IGV.
"""
if not os.path.exists(genbank_file_path):
print(f"Error: GenBank file not found at '{genbank_file_path}'")
return
base_name = os.path.splitext(os.path.basename(genbank_file_path))[0]
fasta_output_path = f"{base_name}.fa"
fasta_sizes_output_path = f"{base_name}.fa.sizes"
bed_output_path = f"{base_name}.bed"
gtf_output_path = f"{base_name}.gtf"
print(f"Processing GenBank file: {genbank_file_path}")
try:
with open(genbank_file_path, "r") as gb_input:
records = list(SeqIO.parse(gb_input, "genbank"))
except Exception as e:
print(f"Error parsing GenBank file: {e}")
return
if not records:
print("No records found in GenBank file. Exiting.")
return
# --- 1. Convert to FASTA (.fa) ---
with open(fasta_output_path, "w") as fasta_output:
SeqIO.write(records, fasta_output, "fasta")
print(f"FASTA sequence saved to: {fasta_output_path}")
# --- 2. Generate FASTA sizes (.fa.sizes) ---
with open(fasta_sizes_output_path, "w") as sizes_output:
for record in records:
sizes_output.write(f"{record.id}\t{len(record.seq)}\n")
print(f"FASTA sizes saved to: {fasta_sizes_output_path}")
# --- 3. Convert Features to BED (.bed) ---
# BED format: chrom chromStart chromEnd name score strand
with open(bed_output_path, "w") as bed_output:
for record in records:
seq_id = record.id
for feature in record.features:
if feature.type == "source":
continue
# BED is 0-based start, exclusive end
start = int(feature.location.start)
end = int(feature.location.end)
# Determine strand
strand = "."
if feature.location.strand == 1:
strand = "+"
elif feature.location.strand == -1:
strand = "-"
# Determine name for BED file
name = feature.qualifiers.get("locus_tag", [None])[0]
if not name:
name = feature.qualifiers.get("gene", [None])[0]
if not name:
name = feature.qualifiers.get("product", [None])[0]
if not name:
name = f"{feature.type}_{start}_{end}" # Fallback
# Basic score, not always meaningful for annotation
score = "0"
bed_line = f"{seq_id}\t{start}\t{end}\t{name}\t{score}\t{strand}\n"
bed_output.write(bed_line)
print(f"BED annotations saved to: {bed_output_path}")
# --- 4. Convert Features to GTF (.gtf) ---
# GTF format: seqname source feature start end score strand frame attributes
# Attributes: gene_id "gene_id"; transcript_id "transcript_id"; etc.
with open(gtf_output_path, "w") as gtf_output:
gtf_output.write("##gff-version 2\n") # GTF is technically GFF2-like
# Mapping common GenBank feature types to GTF types for better interpretation
# This is a simplification; complex gene models (spliced) are harder to derive directly
feature_type_map = {
"gene": "gene",
"mRNA": "mRNA",
"tRNA": "tRNA",
"rRNA": "rRNA",
"CDS": "CDS",
"exon": "exon",
"misc_feature": "misc_feature",
"mobile_element": "mobile_element_feature",
"repeat_region": "repeat_region",
"regulatory": "regulatory_feature",
"STS": "sequence_tag_site",
"variation": "variation"
# Add more as needed based on your GenBank files
}
for record in records:
seq_id = record.id
for feature in record.features:
if feature.type == "source":
continue
# GTF is 1-based start, 1-based end (inclusive)
start = int(feature.location.start) + 1
end = int(feature.location.end)
# Determine strand
strand = "."
if feature.location.strand == 1:
strand = "+"
elif feature.location.strand == -1:
strand = "-"
# Determine feature type for GTF
gtf_type = feature_type_map.get(feature.type, "feature")
# Frame for CDS (0, 1, 2), else '.'
frame = "."
if feature.type == "CDS":
# GenBank codon_start is 1, 2, or 3. GTF frame is 0, 1, or 2.
# GTF frame means (start - 1) % 3 relative to the start of the feature
# BioPython's feature.qualifiers.get("codon_start", [1])[0] is 1-based
# So, if codon_start is 1, frame is 0. If 2, frame 1. If 3, frame 2.
codon_start = feature.qualifiers.get("codon_start", [1])[0]
frame = str(codon_start - 1)
# GTF attributes
attributes = []
# Get unique ID for gene/transcript/feature
gene_id_val = feature.qualifiers.get("locus_tag", [None])[0]
if not gene_id_val:
gene_id_val = feature.qualifiers.get("gene", [None])[0]
if not gene_id_val:
# Fallback to a unique ID if no locus_tag or gene name
gene_id_val = f"{gtf_type}_{seq_id}_{start}_{end}"
# GTF requires gene_id and transcript_id, even if they are the same
attributes.append(f'gene_id "{gene_id_val}"')
# For simplicity, if not an actual spliced transcript, make transcript_id same as gene_id
# More complex logic needed for true spliced transcripts
transcript_id_val = feature.qualifiers.get("protein_id", [None])[0]
if not transcript_id_val:
transcript_id_val = f"{gene_id_val}_transcript" # or similar
attributes.append(f'transcript_id "{transcript_id_val}"')
# Add gene_name if available (often the same as 'gene' qualifier)
gene_name = feature.qualifiers.get("gene", [None])[0]
if gene_name:
attributes.append(f'gene_name "{gene_name}"')
# Add product if available
product_name = feature.qualifiers.get("product", [None])[0]
if product_name:
# Escape double quotes within the product name
product_name = product_name.replace('"', '""')
attributes.append(f'product "{product_name}"')
# Add locus_tag if different from gene_id (or if it was used for gene_id)
locus_tag_val = feature.qualifiers.get("locus_tag", [None])[0]
if locus_tag_val and locus_tag_val != gene_id_val:
attributes.append(f'locus_tag "{locus_tag_val}"')
# Add protein_id if available
protein_id_val = feature.qualifiers.get("protein_id", [None])[0]
if protein_id_val and protein_id_val != transcript_id_val:
attributes.append(f'protein_id "{protein_id_val}"')
# Add other qualifiers as generic key-value pairs
for key, values in feature.qualifiers.items():
# Exclude keys already handled or not useful (e.g., "translation")
if key not in ["gene", "product", "locus_tag", "protein_id", "translation", "codon_start"]:
for value in values:
# Escape double quotes for GTF attribute values
formatted_value = str(value).replace('"', '""')
attributes.append(f'{key} "{formatted_value}"')
attributes_str = "; ".join(attributes) + ";" # GTF attributes end with a semicolon
# GTF format: seqname source feature start end score strand frame attributes
gtf_line = f"{seq_id}\tGenBank\t{gtf_type}\t{start}\t{end}\t.\t{strand}\t{frame}\t{attributes_str}\n"
gtf_output.write(gtf_line)
print(f"GTF annotations saved to: {gtf_output_path}")
print("\nConversion complete!")
print(f"You will need to generate '{base_name}.fa.fai' using 'samtools faidx' or let IGV create it.")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Convert GenBank file to FASTA, FASTA sizes, BED, and GTF for IGV.")
parser.add_argument("genbank_file", help="Path to the input GenBank (.gb or .gbk) file.")
args = parser.parse_args()
convert_genbank_to_igv_formats(args.genbank_file)