The user wants a Python script to analyze and visualize genetic data.
This is a broad request. "Genetic data" can range from raw sequencing reads (FASTQ) to aligned reads (BAM), variant calls (VCF), or gene expression matrices.
To provide a useful and runnable example without requiring massive datasets or complex external tools (like GATK or command-line aligners), I should focus on a common, educational task.
Potential Scenarios:
DNA Sequence Analysis: Analyze a FASTA file (GC content, motif finding, transcription factor binding sites).
Variant Analysis: Analyze a VCF file (SNP distribution, impact prediction).
Selection: Gene Expression Analysis (Scenario 3) is visually appealing and standard in bioinformatics. However, handling a count matrix requires a specific data structure.
Alternatively, simple DNA Sequence Analysis (Scenario 1) is easier to code from scratch (parsing FASTA) and demonstrates basic bioinformatics logic (complement, GC content, translation).
Let's go with Scenario 1: DNA Sequence Analysis and Visualization, but make it robust. I will also include a mention of libraries like Biopython.
Plan:
Setup: Create a dummy FASTA file (so the script is self-contained).
Line plot for GC content across a sliding window (moving average).
Libraries:
matplotlib for plotting.
seaborn for prettier plots (optional but good).
Standard collections for counting.
Drafting the Code:
Imports:matplotlib.pyplot, collections.Counter.
Data Generation: Write a function to create a sample FASTA file.
Class Structure: Create a GeneticAnalyzer class to keep it organized.
__init__(self, fasta_file)
read_fasta(self)
calculate_gc_content(self)
nucleotide_frequency(self)
plot_frequency(self)
plot_gc_window(self)
Refining the Visualization:
Plot 1: Pie chart or Bar chart of A, T, C, G.
Plot 2: GC Content across the sequence using a sliding window. This is a classic bioinformatics plot.
Adding Biopython context:
Since this is a "Python script," writing a parser from scratch is good for understanding, but mentioning Biopython is professional. I will stick to standard libraries for the main runnable code to ensure it works without installing complex dependencies, but mention Biopython in the explanation.
Step-by-Step Implementation details:
Mock Data: A simple string like ATCG....
Parser: Read line by line, stripping headers (>).
Metrics:
Total length.
Counts of A, T, C, G.
GC%.
Windowed GC: Loop through sequence with step k, calculate GC, store.
Plotting: Use matplotlib.
Reviewing constraints:
The user asked for "Genetic data." Just doing a string might be too simple. Let's do a slightly more advanced version: Analyzing a VCF (Variant Call Format) file.Actually, VCF parsing is tedious to write from scratch. Let's stick to the FASTA/Sequence Analysis approach as it's more visual and intuitive for a general "genetic data" request.
Final Plan:
Create a synthetic FASTA file representing a gene.
Parse the DNA.
Analyze:
Base counts.
GC Content (Global and Sliding Window).
Codon usage (optional, might be too complex for a single script, stick to GC and Base counts).
Visualize:
Bar chart of base distribution.
Line plot of GC content over the gene length.
Code Structure:
python
import matplotlib.pyplot as plt
from collections import Counter
import random
# 1. Generate Data
# 2. Define Analyzer Class
# 3. Run Analysis
# 4. Plot results
Let's write the actual code mentally.
sliding_window function: for i in range(0, len(seq) - window, step): sub = seq[i:i+window] ...gc_content: (g+c)/len * 100
I will also add a function to find "ORFs" (Open Reading Frames) or at least motifs? No, keep it visual. The sliding window GC plot is the most "genomic" looking visualization.
Safety/Policy Check:
No dangerous content. Purely scientific/programming.
Output Format:
Explain the libraries used.
Provide the code.
Explain how to run it.
Explain the outputs.
Let's add a touch of Biopython usage as an alternative or advanced method? No, the prompt implies a script I can run now. Relying on pip install biopython creates a barrier. I will use standard libraries (matplotlib is standard enough for data science).
Refined Plan:
Data Simulation: Generate a random DNA sequence but inject "CpG islands" (high GC regions) to make the visualization interesting.
Analysis:
Global Stats (Length, Total GC).
Local Stats (Sliding Window GC).
Nucleotide Composition.
Visualization: A 2-panel plot (Subplots). Top: Nucleotide Pie/Bar. Bottom: GC Content over sequence position.
This looks solid.
Code Writing:
Function create_mock_fasta.
Function parse_fasta.
Function analyze_sequence.
Function visualize.
I will ensure comments explain the biology (e.g., what GC content implies).
Let's consider extending to Protein Translation?
DNA -> RNA -> Protein. It's a nice string manipulation demo.
Maybe just a simple function to convert the DNA sequence to a protein string and print the first few amino acids.
Okay, I will provide a comprehensive script that:
Simulates a FASTA file.
Parses it.
Calculates GC content (global and local).
Visualizes the local GC content (identifying regions of high/low stability).
Visualizes nucleotide distribution.
This covers "Analyze" and "Visualize" effectively.
Dependencies:matplotlibseaborn (makes plots nicer, easy to add).
pandas (good for data handling).
I will write the code to use matplotlib and seaborn (standard data viz stack).
One detail: The prompt asks for "Genetic data". A sequence is the most fundamental form. If the user meant "Gene Expression" (RNA-seq), that requires a CSV matrix usually. I will stick to Sequence Analysis but add a note that this logic applies to NGS data.
Let's construct the response.
Introduction: Explain that we will analyze a DNA sequence (FASTA format).
Prerequisites: pip install matplotlib seaborn.
The Script:
Helper to generate data.
Analysis class/functions.
Visualization block.
Explanation: What the graphs mean.
Let's refine the "Sliding Window" logic.
Sequence: ATGC...
Window: 100.
Step: 10.
X-axis: Position. Y-axis: GC %.
This shows the genomic landscape.
I'll include a "Motif Search" as well, as that is a common task. e.g., searching for "TATA" box or "EcoRI" site.
Final Code Structure:
Imports.
MockDataGenerator: creates a fake gene sequence with specific characteristics (high GC region, motif).
GenomicAnalyzer:
calculate_composition: Counts A, T, C, G.
calculate_gc_content: Returns %.
windowed_gc: Calculates GC over a sliding window.
find_motifs: Finds start indices of a specific pattern.
Visualizer:
Plot 1: Composition (Pie/Bar).
Plot 2: GC Content across length (Line).
Plot 3: Motif locations (Scatter/Markers on the line plot).
Main execution block.
This is robust and demonstrates multiple concepts.
To analyze and visualize genetic data effectively, we generally look at DNA sequences (strings of A, C, T, G).
Below is a complete Python script. It simulates a "Genomics Pipeline." Since I cannot access your local files, the script includes a function to generate a mock DNA sequence (simulating a gene). It then performs three common analyses:
Nucleotide Frequency: Analyzing the composition of the DNA.
GC Content: Calculating the percentage of Guanine and Cytosine (crucial for determining gene stability and identification).
Local GC Content: Visualizing how the composition changes across the length of the gene.
Prerequisites
You will need matplotlib for visualization.
bash
pip install matplotlib seaborn
The Python Script
python
How to Interpret the Visuals
Left Graph (Nucleotide Frequency):
This shows the overall composition of your sequence.
In a random sequence, A, T, C, and G should be roughly equal.
Application: In real biology, organisms often have a "bias." For example, bacteria often have high GC content, while some viruses are AT-rich.
Right Graph (GC Content Landscape):
This plots the percentage of G+C bases in "chunks" (windows) of the DNA.
Why this matters: Genes (coding regions) are often found in areas with higher GC content, while non-coding "junk" DNA often has lower GC content.
The Dotted Line: Represents 50%. Peaks above this indicate very stable, gene-rich regions. Valleys below indicate potentially unstable or regulatory regions.
How to use Real Data
To use this with a real gene (e.g., from a .fasta file), replace the generate_dna_sequence call in the __main__ block with code to load a file:
python
# Example for loading a real FASTA file
def load_fasta(filepath):
with open(filepath, 'r') as f:
# Skip header line
f.readline()
# Read sequence and remove newlines
sequence = f.read().replace("\n", "")
return sequence
import matplotlib.pyplot as plt
import seaborn as sns
import random
import pandas as pd
from collections import Counter
# ---------------------------------------------------------
# 1. Data Simulation (Generating a Mock DNA Sequence)
# ---------------------------------------------------------
def generate_dna_sequence(length=1000):
"""
Generates a random DNA sequence of a given length.
In a real scenario, you would load this from a .fasta or .txt file.
"""
genome = ''.join(random.choice('ATCG') for _ in range(length))
return genome
# ---------------------------------------------------------
# 2. Analysis Logic
# ---------------------------------------------------------
def calculate_nucleotide_frequency(sequence):
"""Counts the occurrence of each nucleotide."""
counts = Counter(sequence)
# Ensure all 4 bases are present even if count is 0
for base in ['A', 'T', 'C', 'G']:
if base not in counts:
counts[base] = 0
return counts
def calculate_gc_content(sequence):
"""
Calculates the GC content percentage of the entire sequence.
GC content is biologically significant for gene density and stability.
"""
g_count = sequence.count('G')
c_count = sequence.count('C')
return (g_count + c_count) / len(sequence) * 100
def calculate_windowed_gc(sequence, window_size=100):
"""
Calculates GC content over a sliding window to find
GC-rich or AT-rich regions.
"""
gc_values = []
positions = []
# Iterate through sequence with the window size
for i in range(0, len(sequence) - window_size, window_size):
sub_seq = sequence[i : i + window_size]
gc = (sub_seq.count('G') + sub_seq.count('C')) / window_size * 100
gc_values.append(gc)
positions.append(i)
return positions, gc_values
# ---------------------------------------------------------
# 3. Visualization
# ---------------------------------------------------------
def visualize_genetic_data(frequency_counts, window_pos, window_gc):
"""
Creates a dashboard with:
1. A bar chart of Nucleotide Frequency.
2. A line plot of GC Content across the gene (Genomic Landscape).
"""
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
fig.suptitle('Genetic Data Analysis Dashboard', fontsize=16)
# Plot 1: Nucleotide Distribution
sns.set_theme(style="whitegrid")
bases = list(frequency_counts.keys())
counts = list(frequency_counts.values())
sns.barplot(ax=axes[0], x=bases, y=counts, palette="viridis")
axes[0].set_title('Nucleotide Frequency Distribution')
axes[0].set_ylabel('Count')
axes[0].set_xlabel('Nucleotide Base')
# Plot 2: GC Content Landscape
sns.lineplot(ax=axes[1], x=window_pos, y=window_gc, color='purple', linewidth=2)
axes[1].axhline(50, color='gray', linestyle='--', label='50% Baseline')
axes[1].set_title('GC Content Across Sequence (Windowed)')
axes[1].set_ylabel('GC Content (%)')
axes[1].set_xlabel('Genomic Position (bp)')
axes[1].fill_between(window_pos, window_gc, alpha=0.3, color='purple')
axes[1].legend()
plt.tight_layout()
plt.show()
# ---------------------------------------------------------
# 4. Main Execution
# ---------------------------------------------------------
if __name__ == "__main__":
# Step A: Get Data (Simulated here)
print("Generating synthetic DNA sequence...")
dna_seq = generate_dna_sequence(length=2000)
# Step B: Analyze
freq = calculate_nucleotide_frequency(dna_seq)
total_gc = calculate_gc_content(dna_seq)
pos, gc_landscape = calculate_windowed_gc(dna_seq, window_size=50)
# Step C: Output Stats
print("\n--- Analysis Results ---")
print(f"Sequence Length: {len(dna_seq)} bp")
print(f"Total GC Content: {total_gc:.2f}%")
print(f"Base Counts: {dict(freq)}")
# Step D: Visualize
visualize_genetic_data(freq, pos, gc_landscape)