跳到正文
cccskills
免费在 GitHub 公开

bio-fastq-quality

Analyze FASTQ sequencing read quality with Biopython. Summarize quality scores, filter reads, trim low-quality bases, and inspect quality at each position. Convert older FASTQ quality encodings to the standard format when preparing data for further analysis.

中文简介正在准备中。当前显示英语简介。

原文查看原文说明

Work with FASTQ quality scores using Biopython. Use when analyzing read quality, filtering by quality, trimming low-quality bases, or generating quality reports.

实测评分 未实测

查看安装方法

适用场景

  • Filtering FASTQ reads by average or minimum quality
  • Trimming low-quality read ends
  • Checking quality changes across read positions
  • Converting legacy FASTQ quality encodings

包含的文件(3)

  • SKILL.md8.5 KB
  • examples/fastq_quality.py2.0 KB
  • usage-guide.md1.3 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Version Compatibility

Reference examples tested with: BioPython 1.83+

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

  • Python: pip show <package> then help(module.function) to check signatures

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

FASTQ Quality Scores

"Filter my FASTQ reads by quality score" → Access, analyze, and filter Phred quality scores, trim low-quality bases, and generate per-position quality profiles.

  • Python: SeqIO.parse() with letter_annotations['phred_quality'] (BioPython)

Analyze and manipulate FASTQ quality scores using Biopython.

Required Imports

from Bio import SeqIO
from Bio.Seq import Seq

Accessing Quality Scores

Quality scores are stored in letter_annotations['phred_quality'] as a list of integers.

for record in SeqIO.parse('reads.fastq', 'fastq'):
    qualities = record.letter_annotations['phred_quality']
    print(record.id, qualities[:10])  # First 10 quality scores

Quality Score Basics

Phred ScoreError ProbabilityAccuracy
101 in 1090%
201 in 10099%
301 in 100099.9%
401 in 1000099.99%

Code Patterns

Calculate Average Quality per Read

for record in SeqIO.parse('reads.fastq', 'fastq'):
    quals = record.letter_annotations['phred_quality']
    avg_qual = sum(quals) / len(quals)
    print(f'{record.id}: {avg_qual:.1f}')

Filter Reads by Mean Quality

def high_quality_reads(records, min_avg_qual=20):
    for record in records:
        quals = record.letter_annotations['phred_quality']
        if sum(quals) / len(quals) >= min_avg_qual:
            yield record

records = SeqIO.parse('reads.fastq', 'fastq')
good_reads = high_quality_reads(records, min_avg_qual=25)
SeqIO.write(good_reads, 'filtered.fastq', 'fastq')

Filter by Minimum Quality at Any Position

def all_bases_above(records, min_qual=20):
    for record in records:
        if min(record.letter_annotations['phred_quality']) >= min_qual:
            yield record

Trim Low-Quality Ends (3' Trimming)

def trim_low_quality(record, min_qual=20):
    quals = record.letter_annotations['phred_quality']
    trim_pos = len(quals)
    for i in range(len(quals) - 1, -1, -1):
        if quals[i] >= min_qual:
            trim_pos = i + 1
            break
    return record[:trim_pos]

records = SeqIO.parse('reads.fastq', 'fastq')
trimmed = (trim_low_quality(rec) for rec in records)
SeqIO.write(trimmed, 'trimmed.fastq', 'fastq')

Sliding Window Quality Trim

Goal: Trim a read at the first position where average quality in a sliding window drops below threshold.

Approach: Slide a fixed-size window across quality scores; when the window average falls below the cutoff, truncate the record at that position.

Reference (BioPython 1.83+):

def sliding_window_trim(record, window_size=5, min_avg_qual=20):
    quals = record.letter_annotations['phred_quality']
    for i in range(len(quals) - window_size + 1):
        window = quals[i:i + window_size]
        if sum(window) / window_size < min_avg_qual:
            return record[:i] if i > 0 else None
    return record

Quality Statistics Summary

import statistics

all_quals = []
for record in SeqIO.parse('reads.fastq', 'fastq'):
    all_quals.extend(record.letter_annotations['phred_quality'])

print(f'Mean quality: {statistics.mean(all_quals):.1f}')
print(f'Median quality: {statistics.median(all_quals):.1f}')
print(f'Min quality: {min(all_quals)}')
print(f'Max quality: {max(all_quals)}')

Per-Position Quality Profile

Goal: Compute mean quality at each read position to identify systematic quality drops (e.g., read-end degradation).

Approach: Accumulate quality scores by position across all reads, then compute per-position means.

Reference (BioPython 1.83+):

from collections import defaultdict

position_quals = defaultdict(list)
for record in SeqIO.parse('reads.fastq', 'fastq'):
    for i, q in enumerate(record.letter_annotations['phred_quality']):
        position_quals[i].append(q)

for pos in sorted(position_quals.keys())[:20]:
    quals = position_quals[pos]
    print(f'Position {pos}: mean={sum(quals)/len(quals):.1f}')

Count Reads by Quality Threshold

thresholds = [20, 25, 30, 35]
counts = {t: 0 for t in thresholds}

for record in SeqIO.parse('reads.fastq', 'fastq'):
    avg = sum(record.letter_annotations['phred_quality']) / len(record.seq)
    for t in thresholds:
        if avg >= t:
            counts[t] += 1

for t, c in counts.items():
    print(f'Q>={t}: {c} reads')

Remove N Bases and Low Quality Together

def clean_read(record, min_qual=20):
    seq = str(record.seq)
    quals = record.letter_annotations['phred_quality']
    keep = [(s, q) for s, q in zip(seq, quals) if s != 'N' and q >= min_qual]
    if not keep:
        return None
    new_seq, new_quals = zip(*keep)
    new_record = record[:0]  # Empty copy with same metadata
    new_record.seq = Seq(''.join(new_seq))
    new_record.letter_annotations['phred_quality'] = list(new_quals)
    return new_record

FASTQ Format Variants

VariantFormat StringQuality EncodingASCII Range
Sanger/Illumina 1.8+'fastq'Phred+33 (standard)33-126
Solexa'fastq-solexa'Solexa+6459-126
Illumina 1.3-1.7'fastq-illumina'Phred+6464-126

Most modern data uses standard 'fastq' (Sanger/Illumina 1.8+).

Quality Score Conversion

For legacy data using different quality encodings:

from Bio.SeqIO.QualityIO import phred_quality_from_solexa, solexa_quality_from_phred

Convert Solexa to Phred

from Bio.SeqIO.QualityIO import phred_quality_from_solexa

# Convert single score
solexa_score = 10
phred_score = phred_quality_from_solexa(solexa_score)

# Convert list of scores
solexa_scores = [10, 20, 30, 40]
phred_scores = [phred_quality_from_solexa(s) for s in solexa_scores]

Convert Phred to Solexa

from Bio.SeqIO.QualityIO import solexa_quality_from_phred

phred_score = 30
solexa_score = solexa_quality_from_phred(phred_score)

Convert Between FASTQ Variants

from Bio import SeqIO

# Read old Illumina format, write standard format
records = SeqIO.parse('old_reads.fastq', 'fastq-illumina')
SeqIO.write(records, 'standard_reads.fastq', 'fastq')

# Read Solexa format, write standard format
records = SeqIO.parse('solexa_reads.fastq', 'fastq-solexa')
SeqIO.write(records, 'standard_reads.fastq', 'fastq')

Auto-Detect Quality Encoding

Goal: Determine which FASTQ quality encoding (Sanger, Solexa, or Illumina 1.3+) a file uses.

Approach: Sample quality lines, find the minimum ASCII value, and compare against known offset ranges.

Reference (BioPython 1.83+):

def detect_quality_encoding(filepath, sample_size=1000):
    min_qual = 126
    max_qual = 0
    count = 0

    with open(filepath) as f:
        for i, line in enumerate(f):
            if i % 4 == 3:  # Quality line
                for char in line.strip():
                    min_qual = min(min_qual, ord(char))
                    max_qual = max(max_qual, ord(char))
                count += 1
                if count >= sample_size:
                    break

    if min_qual < 59:
        return 'fastq'  # Sanger/Illumina 1.8+ (Phred+33)
    elif min_qual < 64:
        return 'fastq-solexa'  # Solexa+64
    else:
        return 'fastq-illumina'  # Illumina 1.3+ (Phred+64)

Common Errors

ErrorCauseSolution
KeyError: 'phred_quality'Not FASTQ or wrong variantCheck format, try 'fastq-illumina'
Quality scores all 0Wrong encoding assumedTry different FASTQ variant
Trimmed reads emptyToo aggressive trimmingLower quality threshold

Related Skills

  • read-sequences - Parse FASTQ files
  • filter-sequences - Filter reads by other criteria (length, content)
  • paired-end-fastq - Handle R1/R2 paired quality filtering
  • sequence-statistics - Generate summary statistics including quality
  • alignment-files - After filtering, align reads with bwa/bowtie2; quality scores in BAM

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

adaptyv

免费

Support protein design with cloud laboratory testing for binding, expression, thermal stability, and enzyme activity. Covers sequence optimization, submitting experiments through the Adaptyv API, checking progress, and downloading experimental results.

中文简介正在准备中。当前显示英语简介。

  • Validate designed proteins with laboratory assays
  • Screen and redesign sequences for better solubility
  • Submit protein testing experiments through an API
FreedomIntelligence/OpenClaw-Medical-Skills30802026年7月21日 更新

Build flexible daily plans that account for ADHD-related difficulties with time estimation and getting started. Narrow priorities to three tasks, add transition buffers, and choose small next actions that match the energy available that day.

中文简介正在准备中。当前显示英语简介。

  • Choosing three priorities for today
  • Planning a schedule with transition buffers
  • Finding a small first step when starting feels difficult
FreedomIntelligence/OpenClaw-Medical-Skills30802026年7月21日 更新

aeon

免费

Build Python workflows for data recorded over time, including classification, forecasting, anomaly detection, and pattern search. Using aeon, the skill guides preprocessing, algorithm selection, feature extraction, and evaluation through interfaces compatible with scikit-learn.

中文简介正在准备中。当前显示英语简介。

  • Classify time series by their patterns
  • Forecast future values from historical data
  • Detect anomalies and change points
FreedomIntelligence/OpenClaw-Medical-Skills30802026年7月21日 更新

Use a browser to research topics, extract page information, fill forms, and test websites. Guides agents through identifying page controls, interacting with web apps, saving screenshots or PDFs, and reusing saved login sessions.

中文简介正在准备中。当前显示英语简介。

  • Researching topics and reading web articles
  • Filling and submitting online forms
  • Extracting page text and links
FreedomIntelligence/OpenClaw-Medical-Skills30802026年7月21日 更新

Combine health measurements, exercise, sleep, nutrition, and mental health records to examine trends, unusual changes, and estimated risks. The skill produces personalized suggestions and text or interactive HTML reports using local data without external API calls.

中文简介正在准备中。当前显示英语简介。

  • Review health records together in a comprehensive report
  • Explore links between sleep, mood, exercise, and weight
  • Summarize estimated disease and nutrition risks
FreedomIntelligence/OpenClaw-Medical-Skills30802026年7月21日 更新

alphafold

免费

Predict structures for designed protein sequences and protein complexes with AlphaFold2 or ColabFold. Inspect structure files and confidence scores to assess folding and chain interfaces, with guidance for local runs, Modal execution, and common prediction errors.

中文简介正在准备中。当前显示英语简介。

  • Check predicted folding of a designed protein sequence
  • Predict a binder–target protein complex
  • Review structure and interface confidence scores
FreedomIntelligence/OpenClaw-Medical-Skills30802026年7月21日 更新

查看 FreedomIntelligence 的全部技能

报告此技能的问题