Skip to content

Latest commit

Β 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🧬 Reverse and Complement Nucleic Acid Sequences (DNA, RNA) using Python

Python Biopython Jupyter Tests

Domain Dataset Code Style License: MIT

A practical bioinformatics guide, high-performance toolkit, and interactive Jupyter Notebook for converting, reversing, complementing, and transcribing DNA & RNA sequencesβ€”featuring real-world genomic analysis of complete SARS-CoV-2 viral isolates.


πŸ“– What is this Repository About?

In molecular biology, genetic information is stored in nucleic acids: Deoxyribonucleic Acid (DNA) and Ribonucleic Acid (RNA). Unlike normal computer text strings, biological sequences have physical chemistry rules:

  1. Directionality (Polarity): Nucleic acid strands have chemical ends labeled 5-prime ($5'$) and 3-prime ($3'$). Cellular enzymes (DNA & RNA polymerases) read and synthesize sequences exclusively from $5'$ to $3'$.
  2. Antiparallel Pairing: Double-stranded DNA consists of two strands running in opposite directions ($5' \to 3'$ and $3' \to 5'$), held together by Watson-Crick hydrogen bonds ($A=T$, $G \equiv C$).
  3. The Universal Database Standard: Worldwide databases (NCBI GenBank, EMBL-EBI, DDBJ) store and display all sequences strictly in the $5'$ to $3'$ direction.

The Core Problem:

When working with the opposite (complementary) strand of a DNA sequence, taking only the complement gives you a sequence running backward ($3' \to 5'$). To write it according to international biological standards, you must both invert the order (reverse) and swap the bases (complement). This operation is the Reverse-Complement.

This repository provides:

  • The Theory: Clear biological explanations with visual diagrams.
  • The Code: Clean, bug-free, and high-performance Python modules (src/) that run ~35x faster than naive Python loops.
  • The Practice: An interactive Jupyter Notebook (notebooks/nucleic_acids_reverse_complement.ipynb) analyzing authentic complete ($29.9\text{ kb}$) coronavirus genomes from China, India, Bangladesh, and the United States.

🎯 For What is this Used? (Real-World Applications)

Application Why Reverse-Complement & Transcription are Needed
πŸ”¬ PCR Primer Design In Polymerase Chain Reaction (PCR) assays (e.g., COVID-19 RT-PCR tests), the reverse primer binds to the opposite strand. Oligonucleotide synthesizers require the primer sequence entered in the standard $5' \to 3'$ reverse-complement orientation.
🧬 RNA Viral Genomics Single-stranded $(+)$ RNA viruses like SARS-CoV-2 replicate by synthesizing a $(-)$ negative-sense RNA template. Bioinformaticians must transcribe and reverse-complement sequences to predict open reading frames (ORFs) and viral proteins.
πŸ§ͺ Next-Gen Sequencing (NGS) High-throughput sequencers (Illumina, Oxford Nanopore) sequence random fragments from both strands. Read alignment algorithms must reverse-complement reads to align them to reference genomes.
πŸ’Š mRNA Vaccines & Therapeutics DNA plasmid templates are transcribed into therapeutic mRNA transcripts (replacing Thymine with Uracil) for in-vitro synthesis.
πŸ” Restriction Site Discovery Many restriction enzymes recognize palindromic cleavage sites (e.g., EcoRI 5'-GAATTC-3'), which are identical to their own reverse complement.

πŸ› οΈ How to Use This Repository

1. Prerequisites & Installation

Ensure you have Python 3.10+ installed. Install the minimal dependencies:

# Clone or navigate to the repository directory
cd "18_Reverse and complement nucleic acid sequences (DNA, RNA) using Python"

# Install dependencies (Biopython, Pandas, Matplotlib, Seaborn, Jupyter)
py -m pip install -r requirements.txt

2. Method A: Interactive Master Jupyter Notebook (Recommended for Beginners & Learners)

The interactive notebook provides a complete visual learning and analysis experience:

jupyter notebook notebooks/nucleic_acids_reverse_complement.ipynb

Inside the notebook, you will:

  • Follow guided explanations with markdown math and biological diagrams.
  • Run live code cells demonstrating string slicing, base classification, and reverse-complement logic.
  • Benchmark Python loop performance vs. vectorized translation tables.
  • Load real SARS-CoV-2 genomes from data/raw/ and inspect GC content and nucleotide percentages.
  • Plot genome-wide sliding-window GC curves highlighting viral genes (ORF1ab, Spike [S], Nucleocapsid [N]).
  • Export processed viral mRNA transcripts to data/processed/.

3. Method B: Using the Python Library in Your Own Code (src/)

You can directly import the modular tools into your Python scripts or research workflows:

from src.sequence_core import (
    reverse_sequence,
    complement_dna,
    reverse_complement_dna,
    transcribe_template_to_rna,
    transcribe_coding_to_rna,
)
from src.fasta_io import read_fasta, write_fasta
from src.analytics import calculate_gc_content, calculate_base_composition

# Example 1: DNA Reverse-Complement
dna = "ATGCCGCTAAACTGACATTCAGATC"
print("Original:         ", dna)
print("Reversed:         ", reverse_sequence(dna))
print("Complement:       ", complement_dna(dna))
print("Reverse-Comp:     ", reverse_complement_dna(dna))

# Example 2: Transcribing to mRNA
mrna = transcribe_template_to_rna(dna)
print("mRNA Transcript:  ", mrna)

# Example 3: Computing GC%
print(f"GC Content:        {calculate_gc_content(dna):.2f}%")

4. Method C: Processing Custom FASTA Files

To read and process your own genomic FASTA files using the streaming utilities:

from src.fasta_io import read_fasta, write_fasta
from src.sequence_core import transcribe_coding_to_rna

# Read any FASTA file
records = read_fasta("data/raw/NC_045512_China.txt")
header, sequence = records[0]

print(f"Loaded: {header}")
print(f"Length: {len(sequence):,} base pairs")

# Convert coding DNA to viral RNA
rna_seq = transcribe_coding_to_rna(sequence)

# Save to output FASTA
write_fasta("data/processed/my_transcript.fasta", [(header, rna_seq)], line_wrap=70)

πŸ“‚ Repository Layout

.
β”œβ”€β”€ assets/                                 # Publication figures & diagrams
β”‚   β”œβ”€β”€ nucleotide_composition.png          # Base frequency comparison chart
β”‚   β”œβ”€β”€ sars_cov_2_gc_profile.png           # Sliding-window GC profile across Wuhan genome
β”‚   └── workflow_diagram.png                # Nucleic acid polarity & workflow diagram
β”‚
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw/                                # Authentic NCBI FASTA genomes (~29.9 kb each)
β”‚   β”‚   β”œβ”€β”€ MN988668_China.txt              # Early Wuhan coronavirus isolate
β”‚   β”‚   β”œβ”€β”€ MT755827.1_Bangladesh.txt       # Bangladesh clinical isolate
β”‚   β”‚   β”œβ”€β”€ MT759582.1_India.txt            # India clinical isolate
β”‚   β”‚   β”œβ”€β”€ MT766907.1_USA.txt              # USA clinical isolate
β”‚   β”‚   └── NC_045512_China.txt             # Wuhan-Hu-1 NCBI Reference Genome
β”‚   └── processed/                          # Pipeline output files
β”‚       β”œβ”€β”€ NC_045512_China_RNA.fasta       # Transcribed single-isolate viral RNA
β”‚       └── sars_cov_2_all_rna_transcripts.fasta # Multi-isolate RNA FASTA database
β”‚
β”œβ”€β”€ notebooks/
β”‚   └── nucleic_acids_reverse_complement.ipynb # Master interactive Jupyter Notebook
β”‚
β”œβ”€β”€ src/                                    # Clean, modular Python package
β”‚   β”œβ”€β”€ __init__.py                         # Package entrypoint
β”‚   β”œβ”€β”€ analytics.py                        # GC%, base composition, sliding window
β”‚   β”œβ”€β”€ fasta_io.py                         # Stream-based FASTA reader & writer
β”‚   └── sequence_core.py                    # Vectorized reverse, complement, transcription
β”‚
β”œβ”€β”€ requirements.txt                        # Dependency specifications
β”œβ”€β”€ LICENSE                                 # MIT License
└── README.md                               # Project documentation & usage guide

πŸ”¬ Biological Background: Watson-Crick Rules & Directionality

Watson-Crick Base Pairing

  • In DNA:
    • Adenine (A) pairs with Thymine (T) (2 hydrogen bonds)
    • Guanine (G) pairs with Cytosine (C) (3 hydrogen bonds)
  • In RNA:
    • Uracil (U) replaces Thymine: Adenine (A) pairs with Uracil (U)

Antiparallel Polarity & Reverse-Complement Workflow

Double-stranded DNA is arranged antiparallel:

5' β€” A  T  G  C  C  G  C  T  A  A β€” 3'  (Sense / Coding Strand)
     |  |  |  |  |  |  |  |  |  |
3' β€” T  A  C  G  G  C  G  A  T  T β€” 5'  (Template / Antisense Strand)
Nucleic Acid Directionality, Pairing & Reverse-Complement Workflow

Figure 1: Molecular directionality, Watson-Crick antiparallel pairing, reverse-complement sequence synthesis, and RNA transcription.

To read the complementary antisense strand in the standard $5' \to 3'$ direction:

  1. Complement: $3'\text{-TACGGCGATT-}5'$
  2. Reverse: $5'\text{-TTAGCGGCAT-}3'$ (Reverse-Complement)
  3. Transcribe: $5'\text{-AUGCCGCUAA-}3'$ (Transcribed mRNA)

Important

Why simple reversal or simple complement alone fails:

  • Reversing without complementing gives you the same strand in backward order.
  • Complementing without reversing gives you the opposite strand in $3' \to 5'$ order, which violates FASTA standards and causes PCR primers to bind the wrong location.
  • You must perform both operations.

⚑ Performance: Why Translation Tables Matter

In Python, manipulating long strings via character-by-character loops incurs interpreter overhead. This repository implements both:

  1. Pedagogical loops: Helpful for learning the concept.
  2. Vectorized translation tables (str.maketrans): C-level lookup table operating on contiguous memory.

Benchmark Comparison (100,000 bp Synthetic Sequence):

Method Average Latency Speedup Factor
Iterative Python for Loop 3.90 ms $1.0\times$ (Baseline)
Vectorized str.maketrans 0.11 ms $\sim 35.4\times$ FASTER

🦠 SARS-CoV-2 Complete Genomes: Comparative Findings

Using the included dataset of authentic complete viral genomes from NCBI GenBank:

Strain / Clinical Isolate Accession ID Origin Length (bp) GC% A (%) T/U (%) C (%) G (%)
Wuhan-Hu-1 (Reference) NC_045512.2 China 29,903 37.97% 29.94% 32.08% 18.37% 19.61%
China (Early Isolate) MN988668.1 China 29,881 37.98% 29.94% 32.08% 18.37% 19.61%
Bangladesh Isolate MT755827.1 Bangladesh 29,903 37.98% 29.94% 32.08% 18.38% 19.60%
India Isolate MT759582.1 India 29,800 37.98% 29.95% 32.08% 18.39% 19.59%
USA Isolate MT766907.1 USA 29,782 37.97% 29.93% 32.10% 18.38% 19.59%

Key Biological Insights:

  1. Strong AT-Bias: Coronaviruses have an AT-rich genome (~62% AT, ~38% GC), with Thymine/Uracil being the single most abundant nucleotide ($>32%$).
  2. Conserved Composition Across Continents: Despite small mutations, the overall nucleotide distribution is remarkably conserved across global isolates.

πŸ“Š Visualizations Included

1. Nucleic Acid Directionality & Workflow Diagram

Illustrates molecular polarity ($5' \to 3'$), Watson-Crick antiparallel pairing, reverse-complement generation, and transcription:

Nucleic Acid Polarity and Workflow Diagram

2. Sliding-Window GC Profile along the 29.9 kb Viral Genome

Reveals regional GC density fluctuations across major genes (ORF1ab, Spike [S], and Nucleocapsid [N]):

SARS-CoV-2 GC Profile

3. Comparative Nucleotide Frequency Chart

Highlights the marked AT-richness and conserved nucleotide distribution across global SARS-CoV-2 isolates:

Nucleotide Composition

πŸ“œ License

This project is open source and available under the MIT License.


πŸ”— Connect with Me

Twitter LinkedIn Stack Exchange GitHub

About

Interactive Jupyter Notebook for DNA/RNA reverse-complementation, transcription, and SARS-CoV-2 comparative genomic analysis.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages