[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73K7HRXZXP554JTEJ1WS71Z":3,"skill-same:01M73K7HRXZXP554JTEJ1WS71Z":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73K7HRXZXP554JTEJ1WS71Z","viennarna-structure-prediction",null,"Predict RNA secondary structure, MFE folding, base-pair probabilities, RNA-RNA interactions via ViennaRNA Python bindings. Pipeline: sequence → MFE → partition function and pair-probability matrix → dot-bracket → duplex. Use for siRNA\u002FsgRNA targeting, ribozyme design, RNA accessibility. Use RNAfold CLI for batch use without Python.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fviennarna-structure-prediction\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"viennarna-structure-prediction\"\ndescription: \"Predict RNA secondary structure, MFE folding, base-pair probabilities, RNA-RNA interactions via ViennaRNA Python bindings. Pipeline: sequence → MFE → partition function and pair-probability matrix → dot-bracket → duplex. Use for siRNA\u002FsgRNA targeting, ribozyme design, RNA accessibility. Use RNAfold CLI for batch use without Python.\"\nlicense: \"MIT\"\n---\n\n# ViennaRNA Structure Prediction\n\n## Overview\n\nViennaRNA is the gold-standard toolkit for RNA secondary structure prediction based on thermodynamic nearest-neighbor parameters. It predicts the minimum free energy (MFE) structure and dot-bracket notation for a given RNA sequence, computes the full partition function to obtain base pair probabilities, and models RNA-RNA interactions via co-folding and duplex prediction. The Python bindings (`import RNA`) expose the full ViennaRNA C library with sequence-level and fold-compound APIs. Command-line programs (`RNAfold`, `RNAalifold`, `RNAduplex`) are also available and demonstrated here.\n\n## When to Use\n\n- Predicting the minimum free energy secondary structure of an RNA sequence (mRNA, lncRNA, miRNA precursor, aptamer)\n- Computing base pair probability matrices to assess structural uncertainty and identify well-defined stem-loops\n- Designing or evaluating siRNA accessibility by folding the target mRNA region and checking for double-stranded structure\n- Assessing sgRNA targeting efficiency by predicting guide RNA secondary structure that may reduce on-target activity\n- Modeling RNA-RNA interactions (co-folding or duplex prediction) for miRNA-target binding or antisense oligonucleotide design\n- Calculating folding free energies for a set of sequences to compare thermodynamic stability\n- Use `mfold` (web server) or `RNAstructure` instead when you need Mfold algorithm predictions specifically or need the Efold partition function; ViennaRNA uses the Turner 2004 nearest-neighbor parameters and is the standard for research-grade thermodynamic prediction\n\n## Prerequisites\n\n- **Python packages**: `ViennaRNA` (Python bindings), `matplotlib`, `numpy`\n- **Data requirements**: RNA sequences as strings (ACGU alphabet; T is auto-converted to U by ViennaRNA)\n- **Environment**: Python 3.8+; conda installation strongly recommended (handles C library dependencies)\n\n```bash\n# Install via conda (recommended)\nconda install -c conda-forge -c bioconda viennarna\n\n# Verify installation\npython -c \"import RNA; print(RNA.__version__)\"\n# 2.6.4\n\n# Install additional Python dependencies\npip install matplotlib numpy pandas\n\n# Optional: verify CLI tools are available\nRNAfold --version\n# RNAfold 2.6.4\n```\n\n## Quick Start\n\n```python\nimport RNA\n\n# Predict MFE structure for an RNA sequence\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nstructure, mfe = RNA.fold(sequence)\n\nprint(f\"Sequence:  {sequence}\")\nprint(f\"Structure: {structure}\")\nprint(f\"MFE:       {mfe:.2f} kcal\u002Fmol\")\n# Sequence:  GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\n# Structure: (((((((..((((........)))).(((((.......))))).....(((((.......))))))))))))....\n# MFE:       -31.30 kcal\u002Fmol\n```\n\n## Workflow\n\n### Step 1: Sequence Preparation and MFE Folding\n\nLoad an RNA sequence and compute its minimum free energy secondary structure using `RNA.fold()`. Validate the input and inspect the dot-bracket output.\n\n```python\nimport RNA\n\ndef prepare_sequence(seq: str) -> str:\n    \"\"\"Normalize sequence: uppercase, replace T→U, validate alphabet.\"\"\"\n    seq = seq.upper().replace(\"T\", \"U\").strip()\n    invalid = set(seq) - set(\"ACGUNX\")\n    if invalid:\n        raise ValueError(f\"Invalid characters in sequence: {invalid}\")\n    return seq\n\n# E. coli tRNA-Phe (GenBank: M10217)\nraw_seq = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nsequence = prepare_sequence(raw_seq)\n\nstructure, mfe = RNA.fold(sequence)\n\nprint(f\"Sequence length: {len(sequence)} nt\")\nprint(f\"Structure:       {structure}\")\nprint(f\"MFE:             {mfe:.2f} kcal\u002Fmol\")\n\n# Validate: structure length must equal sequence length\nassert len(structure) == len(sequence), \"Structure and sequence length mismatch\"\n\n# Count stems (paired bases)\nn_paired   = structure.count(\"(\") + structure.count(\")\")\nn_unpaired = structure.count(\".\")\nprint(f\"Paired bases: {n_paired}  |  Unpaired bases: {n_unpaired}\")\nprint(f\"Stem fraction: {n_paired\u002Flen(sequence):.2f}\")\n```\n\n### Step 2: Create a Fold Compound for Advanced Analysis\n\nThe `RNA.fold_compound` object is the central API for partition function, base pair probabilities, and constrained folding.\n\n```python\nimport RNA\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\n\n# Create fold compound (wraps the sequence with model parameters)\nfc = RNA.fold_compound(sequence)\n\n# Compute MFE structure via the fold compound API\nstructure, mfe = fc.mfe()\nprint(f\"MFE structure: {structure}\")\nprint(f\"MFE:           {mfe:.2f} kcal\u002Fmol\")\n\n# Evaluate free energy of an alternative structure\nalt_structure = \".\" * len(sequence)   # fully unfolded\nenergy = fc.eval_structure(alt_structure)\nprint(f\"Fully unfolded energy: {energy:.2f} kcal\u002Fmol\")\nprint(f\"Folding stabilization:  {energy - mfe:.2f} kcal\u002Fmol\")\n```\n\n### Step 3: Partition Function and Base Pair Probabilities\n\nCompute the thermodynamic partition function to obtain ensemble-level base pair probabilities. High-probability pairs indicate well-defined structural elements.\n\n```python\nimport RNA\nimport numpy as np\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nn = len(sequence)\n\nfc = RNA.fold_compound(sequence)\n\n# Step 1: MFE folding (required before pf for proper initialization)\nstructure_mfe, mfe = fc.mfe()\n\n# Step 2: Rescale Boltzmann factors for numerical stability (optional but recommended)\nfc.exp_params_rescale(mfe)\n\n# Step 3: Compute partition function\nstructure_pf, gibbs_free_energy = fc.pf()\nprint(f\"Gibbs free energy (ensemble): {gibbs_free_energy:.2f} kcal\u002Fmol\")\nprint(f\"MFE structure:  {structure_mfe}\")\nprint(f\"Centroid (pf):  {structure_pf}\")\n\n# Step 4: Retrieve base pair probability matrix\nbpp = fc.bpp()   # returns (n+1)x(n+1) matrix; 1-indexed\n\n# Convert to 0-indexed numpy array for analysis\nprobs = np.zeros((n, n))\nfor i in range(1, n + 1):\n    for j in range(i + 1, n + 1):\n        if bpp[i][j] > 0.0:\n            probs[i - 1][j - 1] = bpp[i][j]\n            probs[j - 1][i - 1] = bpp[i][j]\n\n# Identify high-confidence pairs (p > 0.9)\nhigh_conf = [(i, j, probs[i, j]) for i in range(n) for j in range(i + 1, n) if probs[i, j] > 0.9]\nprint(f\"\\nHigh-confidence base pairs (p > 0.9): {len(high_conf)}\")\nfor i, j, p in high_conf[:5]:\n    print(f\"  {sequence[i]}{i+1} — {sequence[j]}{j+1}: p={p:.3f}\")\n```\n\n### Step 4: Visualize Base Pair Probability Matrix\n\nPlot the base pair probability matrix as a heatmap to visualize structural regions.\n\n```python\nimport RNA\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nn = len(sequence)\n\nfc = RNA.fold_compound(sequence)\nstructure_mfe, mfe = fc.mfe()\nfc.exp_params_rescale(mfe)\nfc.pf()\nbpp = fc.bpp()\n\n# Build matrix\nprobs = np.zeros((n, n))\nfor i in range(1, n + 1):\n    for j in range(i + 1, n + 1):\n        if bpp[i][j] > 0.0:\n            probs[i - 1][j - 1] = bpp[i][j]\n            probs[j - 1][i - 1] = bpp[i][j]\n\nfig, ax = plt.subplots(figsize=(8, 7))\nim = ax.imshow(probs, cmap=\"hot_r\", vmin=0, vmax=1, origin=\"upper\", aspect=\"equal\")\nplt.colorbar(im, ax=ax, label=\"Base pair probability\")\n\nax.set_xlabel(\"Nucleotide position\")\nax.set_ylabel(\"Nucleotide position\")\nax.set_title(f\"Base Pair Probability Matrix\\n(n={n} nt, MFE={mfe:.2f} kcal\u002Fmol)\")\nplt.tight_layout()\nplt.savefig(\"bpp_matrix.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved: bpp_matrix.png\")\n```\n\n### Step 5: RNA-RNA Duplex Prediction (Co-folding)\n\nUse `RNA.cofold()` to predict the interaction between two RNA sequences by concatenating them with an `&` separator.\n\n```python\nimport RNA\n\n# miRNA (hsa-miR-21-5p) and its target sequence in mRNA (PTEN 3'UTR region)\nmirna_seq  = \"UAGCUUAUCAGACUGAUGUUGA\"\ntarget_seq = \"UCAACAUCAGUCUGAUAAGCUA\"   # approximate complementary target\n\n# Co-fold: concatenate with & separator\ncofold_seq = mirna_seq + \"&\" + target_seq\nstructure, mfe = RNA.cofold(cofold_seq)\n\nprint(f\"miRNA:          {mirna_seq}\")\nprint(f\"Target:         {target_seq}\")\nprint(f\"Co-fold MFE:    {mfe:.2f} kcal\u002Fmol\")\n\n# Parse the structure — & is retained in output\nn1, n2 = len(mirna_seq), len(target_seq)\nstruct_mirna  = structure[:n1]\nstruct_ampersand = structure[n1]\nstruct_target = structure[n1 + 1:]\n\nprint(f\"miRNA structure:  {struct_mirna}\")\nprint(f\"Target structure: {struct_target}\")\n\npaired_in_duplex = struct_mirna.count(\"(\") + struct_mirna.count(\")\")\nprint(f\"Bases paired across the duplex: {paired_in_duplex}\")\n```\n\n### Step 6: RNA Accessibility Analysis for siRNA Design\n\nCompute the accessibility of a target region within a longer mRNA sequence — critical for siRNA and antisense oligonucleotide efficiency.\n\n```python\nimport RNA\nimport numpy as np\n\ndef compute_accessibility(mrna_seq: str, window: int = 40) -> list:\n    \"\"\"\n    Compute per-position probability of being unpaired (accessible) using\n    a sliding-window approach on the partition function.\n    Returns list of (position, accessibility) tuples.\n    \"\"\"\n    n = len(mrna_seq)\n    fc = RNA.fold_compound(mrna_seq)\n    _, mfe = fc.mfe()\n    fc.exp_params_rescale(mfe)\n    fc.pf()\n    bpp = fc.bpp()\n\n    # Probability of being paired at each position\n    p_paired = np.zeros(n)\n    for i in range(1, n + 1):\n        for j in range(1, n + 1):\n            if i != j:\n                p = bpp[min(i,j)][max(i,j)]\n                p_paired[i - 1] += p\n\n    p_unpaired = 1.0 - np.clip(p_paired, 0, 1)\n    return p_unpaired\n\n# Example: 80-nt mRNA segment with a known accessible region\nmrna = \"AUGCUAGCUAGCUAGCUAUGCUAGCUAGCUUUUUUUUUUUUAUGCUAGCUAGCUAGCUAGCUAGCUAGCUAGCUAGC\"\np_unpaired = compute_accessibility(mrna)\n\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(figsize=(10, 3))\nax.bar(range(1, len(mrna) + 1), p_unpaired, color=\"#2166ac\", alpha=0.8)\nax.axhline(0.5, color=\"red\", lw=1, ls=\"--\", label=\"50% unpaired\")\nax.set_xlabel(\"Position (nt)\")\nax.set_ylabel(\"P(unpaired)\")\nax.set_title(\"RNA Accessibility Profile\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"rna_accessibility.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved: rna_accessibility.png\")\n\n# Top 5 most accessible positions (siRNA target candidates)\nbest = sorted(enumerate(p_unpaired, 1), key=lambda x: -x[1])[:5]\nprint(\"\\nMost accessible positions:\")\nfor pos, prob in best:\n    print(f\"  Position {pos}: P(unpaired) = {prob:.3f}  ({mrna[pos-1]})\")\n```\n\n### Step 7: Command-Line RNAfold and Output Parsing\n\nUse the `RNAfold` CLI for batch folding via subprocess, then parse the output.\n\n```bash\n# Fold a single sequence from stdin\necho \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\" | RNAfold\n\n# Output:\n# GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\n# (((((((..((((........)))).(((((.......))))).....(((((.......)))))))))))).... (-31.30)\n\n# Batch fold from FASTA file\nRNAfold \u003C sequences.fasta > structures.txt\n\n# Generate base pair probability dot plot (PostScript)\nRNAfold --noPS \u003C sequences.fasta   # suppress PostScript output\nRNAfold -p \u003C sequences.fasta       # save dot plot as rna.ps\n```\n\n```python\n# Python: run RNAfold via subprocess and parse output\nimport subprocess\nimport re\n\ndef run_rnafold(sequence: str) -> tuple:\n    \"\"\"Run RNAfold CLI and return (structure, mfe) tuple.\"\"\"\n    result = subprocess.run(\n        [\"RNAfold\", \"--noPS\"],\n        input=sequence,\n        capture_output=True, text=True, timeout=30\n    )\n    if result.returncode != 0:\n        raise RuntimeError(f\"RNAfold failed: {result.stderr}\")\n\n    lines = result.stdout.strip().split(\"\\n\")\n    # Last line: structure and energy, e.g. \"((....)) (-5.40)\"\n    match = re.match(r\"^([.()\\[\\]{}\u003C>|]+)\\s+\\((-?\\d+\\.\\d+)\\)$\", lines[-1])\n    if not match:\n        raise ValueError(f\"Could not parse RNAfold output: {lines[-1]}\")\n    structure = match.group(1)\n    mfe       = float(match.group(2))\n    return structure, mfe\n\nsequences = [\n    (\"tRNA-Phe\", \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"),\n    (\"miR-21\",   \"UAGCUUAUCAGACUGAUGUUGA\"),\n]\n\nfor name, seq in sequences:\n    struct, mfe = run_rnafold(seq)\n    print(f\"{name}: {mfe:.2f} kcal\u002Fmol  |  {struct}\")\n```\n\n### Step 8: Constrained Folding and Suboptimal Structures\n\nApply hard constraints (force or forbid specific base pairs) and enumerate suboptimal structures.\n\n```python\nimport RNA\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\n\n# --- Constrained folding: force specific pairs ---\nfc = RNA.fold_compound(sequence)\n\n# Add hard constraint: force positions 1-7 to be paired (known stem)\nhc = RNA.hc_add_bp(fc, 1, 72)  # force pair between position 1 and 72 (0-indexed in C API)\nstructure_c, mfe_c = fc.mfe()\nprint(f\"Constrained MFE:   {mfe_c:.2f} kcal\u002Fmol\")\nprint(f\"Constrained struct: {structure_c}\")\n\n# --- Enumerate suboptimal structures (delta_mfe threshold) ---\nfc_sub = RNA.fold_compound(sequence)\n_, mfe_opt = fc_sub.mfe()\n\n# Get suboptimal structures within 5 kcal\u002Fmol of MFE\ndelta = 5.0  # kcal\u002Fmol window\nsubopt_list = RNA.subopt(sequence, int(delta * 100))   # energy in 10-cal units\nprint(f\"\\nSuboptimal structures within {delta} kcal\u002Fmol of MFE:\")\nprint(f\"Total suboptimal structures: {len(subopt_list)}\")\nfor s in subopt_list[:3]:\n    e = s.energy \u002F 100.0  # convert from 10-cal to kcal\u002Fmol\n    print(f\"  {s.structure}  ({e:.2f} kcal\u002Fmol)\")\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `sequence` (RNA.fold) | — | ACGU string | Input RNA sequence; T is auto-converted to U |\n| `temperature` (model detail) | `37.0` °C | `0`–`100` °C | Folding temperature; lower temp stabilizes structures |\n| `dangles` (model detail) | `2` | `0`, `1`, `2`, `3` | Dangling end treatment; 2=average, 0=none, use 2 for most applications |\n| `noGU` (model detail) | `False` | `True`\u002F`False` | Disallow G-U wobble pairs when True |\n| `noLP` (model detail) | `False` | `True`\u002F`False` | Disallow lonely base pairs (single-bp stems); reduces noise |\n| `delta` (RNA.subopt) | — | float kcal\u002Fmol | Energy window above MFE for suboptimal structure enumeration |\n| `window` (sliding window) | — | int nt | Sliding window size for long-sequence accessibility analysis |\n\n## Common Recipes\n\n### Recipe: Batch MFE Folding from a FASTA File\n\nWhen to use: Fold a library of RNA sequences (e.g., candidate aptamers, guide RNAs) and compare energies.\n\n```python\nimport RNA\nfrom pathlib import Path\n\ndef read_fasta(fasta_path: str) -> list:\n    \"\"\"Parse FASTA file, return list of (name, sequence) tuples.\"\"\"\n    records = []\n    name, seq = None, []\n    for line in Path(fasta_path).read_text().splitlines():\n        if line.startswith(\">\"):\n            if name:\n                records.append((name, \"\".join(seq).upper().replace(\"T\", \"U\")))\n            name, seq = line[1:].split()[0], []\n        else:\n            seq.append(line.strip())\n    if name:\n        records.append((name, \"\".join(seq).upper().replace(\"T\", \"U\")))\n    return records\n\n# Example: fold sequences from a FASTA file\nsequences = [\n    (\"aptamer_1\", \"GGGUUUUGAAACUAAACUAGGCUCUAGCGCUGGUGUCCCUUCCCGGCUCUAGCCUCAGCAGAAGCUUGAAAAAACCC\"),\n    (\"aptamer_2\", \"GGGAGACAAGAAUAAACGCUCAACGUCUACCAUGAUCGAAUGCUAGCCUUCUAGCUUGCUUCGGCAGCACUAUAGGG\"),\n    (\"aptamer_3\", \"GGGCGACCCUGAUGAGUCCCAAGUCGAAACGAUUCCUUUUUAAACUCAUGGUGCCCAGCCUCGCUCAGCA\"),\n]\n\nprint(f\"{'Name':\u003C15} {'Length':>8} {'MFE':>10} {'Structure'}\")\nprint(\"-\" * 80)\nfor name, seq in sequences:\n    struct, mfe = RNA.fold(seq)\n    print(f\"{name:\u003C15} {len(seq):>8} {mfe:>10.2f}  {struct[:50]}...\")\n```\n\n### Recipe: Check sgRNA Secondary Structure\n\nWhen to use: Evaluate whether a CRISPR sgRNA guide sequence folds into secondary structures that reduce Cas9 binding efficiency.\n\n```python\nimport RNA\n\ndef assess_sgrna(guide_seq: str, scaffold: str = None) -> dict:\n    \"\"\"\n    Assess sgRNA secondary structure.\n    guide_seq: 20-nt spacer sequence (RNA)\n    scaffold: constant sgRNA scaffold sequence (default: SpCas9)\n    \"\"\"\n    if scaffold is None:\n        # SpCas9 sgRNA scaffold (Addgene standard)\n        scaffold = \"GUUUUAGAGCUAGAAAUAGCAAGUUAAAAUAAGGCUAGUCCGUUAUCAACUUGAAAAAGUGGCACCGAGUCGGUGCUUU\"\n\n    full_sgrna = guide_seq.upper().replace(\"T\", \"U\") + scaffold\n    fc = RNA.fold_compound(full_sgrna)\n    structure, mfe = fc.mfe()\n    fc.exp_params_rescale(mfe)\n    fc.pf()\n    bpp = fc.bpp()\n\n    n_guide = len(guide_seq)\n    # Check if any guide bases are paired (bad for targeting)\n    guide_paired = sum(\n        bpp[min(i, j)][max(i, j)]\n        for i in range(1, n_guide + 1)\n        for j in range(1, n_guide + 1)\n        if i != j\n    )\n    guide_accessibility = 1.0 - min(1.0, guide_paired \u002F n_guide)\n    return {\n        \"guide_seq\":    guide_seq,\n        \"mfe\":          mfe,\n        \"structure\":    structure[:n_guide],\n        \"guide_access\": guide_accessibility,\n        \"predicted_ok\": guide_accessibility > 0.7,\n    }\n\nguides = [\"GCACUAGUGACGCAUGGCAC\", \"GGGCAUAGCUAGCUAGCUAU\", \"AAAUUCGCACUAGUGACGCA\"]\nfor g in guides:\n    result = assess_sgrna(g)\n    status = \"OK\" if result[\"predicted_ok\"] else \"WARN (self-paired)\"\n    print(f\"{g}: accessibility={result['guide_access']:.2f}, MFE={result['mfe']:.1f} kcal\u002Fmol  [{status}]\")\n```\n\n### Recipe: Mountain Plot Visualization of RNA Structure\n\nWhen to use: Create a mountain plot — a classic RNA structure visualization showing stem height along the sequence.\n\n```python\nimport RNA\nimport matplotlib.pyplot as plt\n\ndef dot_bracket_to_mountain(structure: str) -> list:\n    \"\"\"Convert dot-bracket structure to mountain plot heights.\"\"\"\n    heights = []\n    level = 0\n    for c in structure:\n        if c == \"(\":\n            level += 1\n        heights.append(level)\n        if c == \")\":\n            level -= 1\n    return heights\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nstructure, mfe = RNA.fold(sequence)\nheights = dot_bracket_to_mountain(structure)\n\nfig, axes = plt.subplots(2, 1, figsize=(12, 5), sharex=True,\n                          gridspec_kw={\"height_ratios\": [1, 3]})\n\n# Top: sequence text\naxes[0].text(0.5, 0.5, \"tRNA-Phe  |  E. coli\", ha=\"center\", va=\"center\",\n             fontsize=10, transform=axes[0].transAxes)\naxes[0].axis(\"off\")\n\n# Bottom: mountain plot\naxes[1].fill_between(range(len(sequence)), heights, step=\"mid\",\n                      color=\"#2c7bb6\", alpha=0.7, label=f\"MFE = {mfe:.2f} kcal\u002Fmol\")\naxes[1].set_xlabel(\"Nucleotide position\")\naxes[1].set_ylabel(\"Stem height\")\naxes[1].set_title(\"Mountain Plot\")\naxes[1].legend()\nplt.tight_layout()\nplt.savefig(\"mountain_plot.png\", dpi=150, bbox_inches=\"tight\")\nprint(f\"Saved: mountain_plot.png  (MFE structure: {structure[:40]}...)\")\n```\n\n## Expected Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `structure` | string | Dot-bracket notation of MFE secondary structure; `(` and `)` for paired bases, `.` for unpaired |\n| `mfe` | float (kcal\u002Fmol) | Minimum free energy of the predicted structure; more negative = more stable |\n| `bpp` | (n+1)×(n+1) matrix | Base pair probability matrix from partition function; element `[i][j]` = P(i paired with j), 1-indexed |\n| `bpp_matrix.png` | PNG | Heatmap visualization of base pair probabilities |\n| `rna_accessibility.png` | PNG | Per-position probability of being unpaired |\n| `mountain_plot.png` | PNG | Mountain plot of stem heights along the sequence |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `ImportError: No module named 'RNA'` | ViennaRNA Python bindings not installed | Install via `conda install -c conda-forge viennarna`; `pip install` alone may fail to link C library |\n| `RuntimeError: RNAfold not found` | ViennaRNA CLI not in PATH | Confirm with `which RNAfold`; if using conda env, activate it before running scripts |\n| MFE is unexpectedly positive (> 0) | Very short or repetitive sequence with no favorable pairs | Short sequences (\u003C 10 nt) often have positive MFE; check sequence length and composition |\n| `bpp` matrix all zeros after `fc.pf()` | `fc.mfe()` must be called before `fc.pf()` on the same fold compound | Always call `fc.mfe()` first, then `fc.exp_params_rescale(mfe)`, then `fc.pf()` |\n| Suboptimal enumeration returns thousands of structures | Window too large for long sequences | Reduce delta to 2–3 kcal\u002Fmol for long sequences; very stable sequences have dense suboptimal ensembles |\n| Co-fold (`RNA.cofold`) shows unexpected pairing | Intramolecular folding dominates in one strand | Inspect each strand separately first; low individual-strand MFE indicates strong self-structure interfering with duplex |\n\n## References\n\n- [ViennaRNA documentation](https:\u002F\u002Fwww.tbi.univie.ac.at\u002FRNA\u002F) — official documentation, parameter files, and Python API reference\n- [Lorenz et al., Algorithms Mol Biol 2011](https:\u002F\u002Fdoi.org\u002F10.1186\u002F1748-7188-6-26) — ViennaRNA Package 2.0 paper (primary citation for structure prediction)\n- [Turner & Mathews, Nucleic Acids Res 2010](https:\u002F\u002Fdoi.org\u002F10.1093\u002Fnar\u002Fgkp892) — Nearest-neighbor thermodynamic parameters used by ViennaRNA\n- [ViennaRNA GitHub: ViennaRNA\u002FViennaRNA](https:\u002F\u002Fgithub.com\u002FViennaRNA\u002FViennaRNA) — source code, issue tracker, Python tutorial notebooks\n","# ViennaRNA Structure Prediction\n\n## Overview\n\nViennaRNA is the gold-standard toolkit for RNA secondary structure prediction based on thermodynamic nearest-neighbor parameters. It predicts the minimum free energy (MFE) structure and dot-bracket notation for a given RNA sequence, computes the full partition function to obtain base pair probabilities, and models RNA-RNA interactions via co-folding and duplex prediction. The Python bindings (`import RNA`) expose the full ViennaRNA C library with sequence-level and fold-compound APIs. Command-line programs (`RNAfold`, `RNAalifold`, `RNAduplex`) are also available and demonstrated here.\n\n## When to Use\n\n- Predicting the minimum free energy secondary structure of an RNA sequence (mRNA, lncRNA, miRNA precursor, aptamer)\n- Computing base pair probability matrices to assess structural uncertainty and identify well-defined stem-loops\n- Designing or evaluating siRNA accessibility by folding the target mRNA region and checking for double-stranded structure\n- Assessing sgRNA targeting efficiency by predicting guide RNA secondary structure that may reduce on-target activity\n- Modeling RNA-RNA interactions (co-folding or duplex prediction) for miRNA-target binding or antisense oligonucleotide design\n- Calculating folding free energies for a set of sequences to compare thermodynamic stability\n- Use `mfold` (web server) or `RNAstructure` instead when you need Mfold algorithm predictions specifically or need the Efold partition function; ViennaRNA uses the Turner 2004 nearest-neighbor parameters and is the standard for research-grade thermodynamic prediction\n\n## Prerequisites\n\n- **Python packages**: `ViennaRNA` (Python bindings), `matplotlib`, `numpy`\n- **Data requirements**: RNA sequences as strings (ACGU alphabet; T is auto-converted to U by ViennaRNA)\n- **Environment**: Python 3.8+; conda installation strongly recommended (handles C library dependencies)\n\n```bash\n# Install via conda (recommended)\nconda install -c conda-forge -c bioconda viennarna\n\n# Verify installation\npython -c \"import RNA; print(RNA.__version__)\"\n# 2.6.4\n\n# Install additional Python dependencies\npip install matplotlib numpy pandas\n\n# Optional: verify CLI tools are available\nRNAfold --version\n# RNAfold 2.6.4\n```\n\n## Quick Start\n\n```python\nimport RNA\n\n# Predict MFE structure for an RNA sequence\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nstructure, mfe = RNA.fold(sequence)\n\nprint(f\"Sequence:  {sequence}\")\nprint(f\"Structure: {structure}\")\nprint(f\"MFE:       {mfe:.2f} kcal\u002Fmol\")\n# Sequence:  GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\n# Structure: (((((((..((((........)))).(((((.......))))).....(((((.......))))))))))))....\n# MFE:       -31.30 kcal\u002Fmol\n```\n\n## Workflow\n\n### Step 1: Sequence Preparation and MFE Folding\n\nLoad an RNA sequence and compute its minimum free energy secondary structure using `RNA.fold()`. Validate the input and inspect the dot-bracket output.\n\n```python\nimport RNA\n\ndef prepare_sequence(seq: str) -> str:\n    \"\"\"Normalize sequence: uppercase, replace T→U, validate alphabet.\"\"\"\n    seq = seq.upper().replace(\"T\", \"U\").strip()\n    invalid = set(seq) - set(\"ACGUNX\")\n    if invalid:\n        raise ValueError(f\"Invalid characters in sequence: {invalid}\")\n    return seq\n\n# E. coli tRNA-Phe (GenBank: M10217)\nraw_seq = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nsequence = prepare_sequence(raw_seq)\n\nstructure, mfe = RNA.fold(sequence)\n\nprint(f\"Sequence length: {len(sequence)} nt\")\nprint(f\"Structure:       {structure}\")\nprint(f\"MFE:             {mfe:.2f} kcal\u002Fmol\")\n\n# Validate: structure length must equal sequence length\nassert len(structure) == len(sequence), \"Structure and sequence length mismatch\"\n\n# Count stems (paired bases)\nn_paired   = structure.count(\"(\") + structure.count(\")\")\nn_unpaired = structure.count(\".\")\nprint(f\"Paired bases: {n_paired}  |  Unpaired bases: {n_unpaired}\")\nprint(f\"Stem fraction: {n_paired\u002Flen(sequence):.2f}\")\n```\n\n### Step 2: Create a Fold Compound for Advanced Analysis\n\nThe `RNA.fold_compound` object is the central API for partition function, base pair probabilities, and constrained folding.\n\n```python\nimport RNA\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\n\n# Create fold compound (wraps the sequence with model parameters)\nfc = RNA.fold_compound(sequence)\n\n# Compute MFE structure via the fold compound API\nstructure, mfe = fc.mfe()\nprint(f\"MFE structure: {structure}\")\nprint(f\"MFE:           {mfe:.2f} kcal\u002Fmol\")\n\n# Evaluate free energy of an alternative structure\nalt_structure = \".\" * len(sequence)   # fully unfolded\nenergy = fc.eval_structure(alt_structure)\nprint(f\"Fully unfolded energy: {energy:.2f} kcal\u002Fmol\")\nprint(f\"Folding stabilization:  {energy - mfe:.2f} kcal\u002Fmol\")\n```\n\n### Step 3: Partition Function and Base Pair Probabilities\n\nCompute the thermodynamic partition function to obtain ensemble-level base pair probabilities. High-probability pairs indicate well-defined structural elements.\n\n```python\nimport RNA\nimport numpy as np\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nn = len(sequence)\n\nfc = RNA.fold_compound(sequence)\n\n# Step 1: MFE folding (required before pf for proper initialization)\nstructure_mfe, mfe = fc.mfe()\n\n# Step 2: Rescale Boltzmann factors for numerical stability (optional but recommended)\nfc.exp_params_rescale(mfe)\n\n# Step 3: Compute partition function\nstructure_pf, gibbs_free_energy = fc.pf()\nprint(f\"Gibbs free energy (ensemble): {gibbs_free_energy:.2f} kcal\u002Fmol\")\nprint(f\"MFE structure:  {structure_mfe}\")\nprint(f\"Centroid (pf):  {structure_pf}\")\n\n# Step 4: Retrieve base pair probability matrix\nbpp = fc.bpp()   # returns (n+1)x(n+1) matrix; 1-indexed\n\n# Convert to 0-indexed numpy array for analysis\nprobs = np.zeros((n, n))\nfor i in range(1, n + 1):\n    for j in range(i + 1, n + 1):\n        if bpp[i][j] > 0.0:\n            probs[i - 1][j - 1] = bpp[i][j]\n            probs[j - 1][i - 1] = bpp[i][j]\n\n# Identify high-confidence pairs (p > 0.9)\nhigh_conf = [(i, j, probs[i, j]) for i in range(n) for j in range(i + 1, n) if probs[i, j] > 0.9]\nprint(f\"\\nHigh-confidence base pairs (p > 0.9): {len(high_conf)}\")\nfor i, j, p in high_conf[:5]:\n    print(f\"  {sequence[i]}{i+1} — {sequence[j]}{j+1}: p={p:.3f}\")\n```\n\n### Step 4: Visualize Base Pair Probability Matrix\n\nPlot the base pair probability matrix as a heatmap to visualize structural regions.\n\n```python\nimport RNA\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as mcolors\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nn = len(sequence)\n\nfc = RNA.fold_compound(sequence)\nstructure_mfe, mfe = fc.mfe()\nfc.exp_params_rescale(mfe)\nfc.pf()\nbpp = fc.bpp()\n\n# Build matrix\nprobs = np.zeros((n, n))\nfor i in range(1, n + 1):\n    for j in range(i + 1, n + 1):\n        if bpp[i][j] > 0.0:\n            probs[i - 1][j - 1] = bpp[i][j]\n            probs[j - 1][i - 1] = bpp[i][j]\n\nfig, ax = plt.subplots(figsize=(8, 7))\nim = ax.imshow(probs, cmap=\"hot_r\", vmin=0, vmax=1, origin=\"upper\", aspect=\"equal\")\nplt.colorbar(im, ax=ax, label=\"Base pair probability\")\n\nax.set_xlabel(\"Nucleotide position\")\nax.set_ylabel(\"Nucleotide position\")\nax.set_title(f\"Base Pair Probability Matrix\\n(n={n} nt, MFE={mfe:.2f} kcal\u002Fmol)\")\nplt.tight_layout()\nplt.savefig(\"bpp_matrix.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved: bpp_matrix.png\")\n```\n\n### Step 5: RNA-RNA Duplex Prediction (Co-folding)\n\nUse `RNA.cofold()` to predict the interaction between two RNA sequences by concatenating them with an `&` separator.\n\n```python\nimport RNA\n\n# miRNA (hsa-miR-21-5p) and its target sequence in mRNA (PTEN 3'UTR region)\nmirna_seq  = \"UAGCUUAUCAGACUGAUGUUGA\"\ntarget_seq = \"UCAACAUCAGUCUGAUAAGCUA\"   # approximate complementary target\n\n# Co-fold: concatenate with & separator\ncofold_seq = mirna_seq + \"&\" + target_seq\nstructure, mfe = RNA.cofold(cofold_seq)\n\nprint(f\"miRNA:          {mirna_seq}\")\nprint(f\"Target:         {target_seq}\")\nprint(f\"Co-fold MFE:    {mfe:.2f} kcal\u002Fmol\")\n\n# Parse the structure — & is retained in output\nn1, n2 = len(mirna_seq), len(target_seq)\nstruct_mirna  = structure[:n1]\nstruct_ampersand = structure[n1]\nstruct_target = structure[n1 + 1:]\n\nprint(f\"miRNA structure:  {struct_mirna}\")\nprint(f\"Target structure: {struct_target}\")\n\npaired_in_duplex = struct_mirna.count(\"(\") + struct_mirna.count(\")\")\nprint(f\"Bases paired across the duplex: {paired_in_duplex}\")\n```\n\n### Step 6: RNA Accessibility Analysis for siRNA Design\n\nCompute the accessibility of a target region within a longer mRNA sequence — critical for siRNA and antisense oligonucleotide efficiency.\n\n```python\nimport RNA\nimport numpy as np\n\ndef compute_accessibility(mrna_seq: str, window: int = 40) -> list:\n    \"\"\"\n    Compute per-position probability of being unpaired (accessible) using\n    a sliding-window approach on the partition function.\n    Returns list of (position, accessibility) tuples.\n    \"\"\"\n    n = len(mrna_seq)\n    fc = RNA.fold_compound(mrna_seq)\n    _, mfe = fc.mfe()\n    fc.exp_params_rescale(mfe)\n    fc.pf()\n    bpp = fc.bpp()\n\n    # Probability of being paired at each position\n    p_paired = np.zeros(n)\n    for i in range(1, n + 1):\n        for j in range(1, n + 1):\n            if i != j:\n                p = bpp[min(i,j)][max(i,j)]\n                p_paired[i - 1] += p\n\n    p_unpaired = 1.0 - np.clip(p_paired, 0, 1)\n    return p_unpaired\n\n# Example: 80-nt mRNA segment with a known accessible region\nmrna = \"AUGCUAGCUAGCUAGCUAUGCUAGCUAGCUUUUUUUUUUUUAUGCUAGCUAGCUAGCUAGCUAGCUAGCUAGCUAGC\"\np_unpaired = compute_accessibility(mrna)\n\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(figsize=(10, 3))\nax.bar(range(1, len(mrna) + 1), p_unpaired, color=\"#2166ac\", alpha=0.8)\nax.axhline(0.5, color=\"red\", lw=1, ls=\"--\", label=\"50% unpaired\")\nax.set_xlabel(\"Position (nt)\")\nax.set_ylabel(\"P(unpaired)\")\nax.set_title(\"RNA Accessibility Profile\")\nax.legend()\nplt.tight_layout()\nplt.savefig(\"rna_accessibility.png\", dpi=150, bbox_inches=\"tight\")\nprint(\"Saved: rna_accessibility.png\")\n\n# Top 5 most accessible positions (siRNA target candidates)\nbest = sorted(enumerate(p_unpaired, 1), key=lambda x: -x[1])[:5]\nprint(\"\\nMost accessible positions:\")\nfor pos, prob in best:\n    print(f\"  Position {pos}: P(unpaired) = {prob:.3f}  ({mrna[pos-1]})\")\n```\n\n### Step 7: Command-Line RNAfold and Output Parsing\n\nUse the `RNAfold` CLI for batch folding via subprocess, then parse the output.\n\n```bash\n# Fold a single sequence from stdin\necho \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\" | RNAfold\n\n# Output:\n# GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\n# (((((((..((((........)))).(((((.......))))).....(((((.......)))))))))))).... (-31.30)\n\n# Batch fold from FASTA file\nRNAfold \u003C sequences.fasta > structures.txt\n\n# Generate base pair probability dot plot (PostScript)\nRNAfold --noPS \u003C sequences.fasta   # suppress PostScript output\nRNAfold -p \u003C sequences.fasta       # save dot plot as rna.ps\n```\n\n```python\n# Python: run RNAfold via subprocess and parse output\nimport subprocess\nimport re\n\ndef run_rnafold(sequence: str) -> tuple:\n    \"\"\"Run RNAfold CLI and return (structure, mfe) tuple.\"\"\"\n    result = subprocess.run(\n        [\"RNAfold\", \"--noPS\"],\n        input=sequence,\n        capture_output=True, text=True, timeout=30\n    )\n    if result.returncode != 0:\n        raise RuntimeError(f\"RNAfold failed: {result.stderr}\")\n\n    lines = result.stdout.strip().split(\"\\n\")\n    # Last line: structure and energy, e.g. \"((....)) (-5.40)\"\n    match = re.match(r\"^([.()\\[\\]{}\u003C>|]+)\\s+\\((-?\\d+\\.\\d+)\\)$\", lines[-1])\n    if not match:\n        raise ValueError(f\"Could not parse RNAfold output: {lines[-1]}\")\n    structure = match.group(1)\n    mfe       = float(match.group(2))\n    return structure, mfe\n\nsequences = [\n    (\"tRNA-Phe\", \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"),\n    (\"miR-21\",   \"UAGCUUAUCAGACUGAUGUUGA\"),\n]\n\nfor name, seq in sequences:\n    struct, mfe = run_rnafold(seq)\n    print(f\"{name}: {mfe:.2f} kcal\u002Fmol  |  {struct}\")\n```\n\n### Step 8: Constrained Folding and Suboptimal Structures\n\nApply hard constraints (force or forbid specific base pairs) and enumerate suboptimal structures.\n\n```python\nimport RNA\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\n\n# --- Constrained folding: force specific pairs ---\nfc = RNA.fold_compound(sequence)\n\n# Add hard constraint: force positions 1-7 to be paired (known stem)\nhc = RNA.hc_add_bp(fc, 1, 72)  # force pair between position 1 and 72 (0-indexed in C API)\nstructure_c, mfe_c = fc.mfe()\nprint(f\"Constrained MFE:   {mfe_c:.2f} kcal\u002Fmol\")\nprint(f\"Constrained struct: {structure_c}\")\n\n# --- Enumerate suboptimal structures (delta_mfe threshold) ---\nfc_sub = RNA.fold_compound(sequence)\n_, mfe_opt = fc_sub.mfe()\n\n# Get suboptimal structures within 5 kcal\u002Fmol of MFE\ndelta = 5.0  # kcal\u002Fmol window\nsubopt_list = RNA.subopt(sequence, int(delta * 100))   # energy in 10-cal units\nprint(f\"\\nSuboptimal structures within {delta} kcal\u002Fmol of MFE:\")\nprint(f\"Total suboptimal structures: {len(subopt_list)}\")\nfor s in subopt_list[:3]:\n    e = s.energy \u002F 100.0  # convert from 10-cal to kcal\u002Fmol\n    print(f\"  {s.structure}  ({e:.2f} kcal\u002Fmol)\")\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `sequence` (RNA.fold) | — | ACGU string | Input RNA sequence; T is auto-converted to U |\n| `temperature` (model detail) | `37.0` °C | `0`–`100` °C | Folding temperature; lower temp stabilizes structures |\n| `dangles` (model detail) | `2` | `0`, `1`, `2`, `3` | Dangling end treatment; 2=average, 0=none, use 2 for most applications |\n| `noGU` (model detail) | `False` | `True`\u002F`False` | Disallow G-U wobble pairs when True |\n| `noLP` (model detail) | `False` | `True`\u002F`False` | Disallow lonely base pairs (single-bp stems); reduces noise |\n| `delta` (RNA.subopt) | — | float kcal\u002Fmol | Energy window above MFE for suboptimal structure enumeration |\n| `window` (sliding window) | — | int nt | Sliding window size for long-sequence accessibility analysis |\n\n## Common Recipes\n\n### Recipe: Batch MFE Folding from a FASTA File\n\nWhen to use: Fold a library of RNA sequences (e.g., candidate aptamers, guide RNAs) and compare energies.\n\n```python\nimport RNA\nfrom pathlib import Path\n\ndef read_fasta(fasta_path: str) -> list:\n    \"\"\"Parse FASTA file, return list of (name, sequence) tuples.\"\"\"\n    records = []\n    name, seq = None, []\n    for line in Path(fasta_path).read_text().splitlines():\n        if line.startswith(\">\"):\n            if name:\n                records.append((name, \"\".join(seq).upper().replace(\"T\", \"U\")))\n            name, seq = line[1:].split()[0], []\n        else:\n            seq.append(line.strip())\n    if name:\n        records.append((name, \"\".join(seq).upper().replace(\"T\", \"U\")))\n    return records\n\n# Example: fold sequences from a FASTA file\nsequences = [\n    (\"aptamer_1\", \"GGGUUUUGAAACUAAACUAGGCUCUAGCGCUGGUGUCCCUUCCCGGCUCUAGCCUCAGCAGAAGCUUGAAAAAACCC\"),\n    (\"aptamer_2\", \"GGGAGACAAGAAUAAACGCUCAACGUCUACCAUGAUCGAAUGCUAGCCUUCUAGCUUGCUUCGGCAGCACUAUAGGG\"),\n    (\"aptamer_3\", \"GGGCGACCCUGAUGAGUCCCAAGUCGAAACGAUUCCUUUUUAAACUCAUGGUGCCCAGCCUCGCUCAGCA\"),\n]\n\nprint(f\"{'Name':\u003C15} {'Length':>8} {'MFE':>10} {'Structure'}\")\nprint(\"-\" * 80)\nfor name, seq in sequences:\n    struct, mfe = RNA.fold(seq)\n    print(f\"{name:\u003C15} {len(seq):>8} {mfe:>10.2f}  {struct[:50]}...\")\n```\n\n### Recipe: Check sgRNA Secondary Structure\n\nWhen to use: Evaluate whether a CRISPR sgRNA guide sequence folds into secondary structures that reduce Cas9 binding efficiency.\n\n```python\nimport RNA\n\ndef assess_sgrna(guide_seq: str, scaffold: str = None) -> dict:\n    \"\"\"\n    Assess sgRNA secondary structure.\n    guide_seq: 20-nt spacer sequence (RNA)\n    scaffold: constant sgRNA scaffold sequence (default: SpCas9)\n    \"\"\"\n    if scaffold is None:\n        # SpCas9 sgRNA scaffold (Addgene standard)\n        scaffold = \"GUUUUAGAGCUAGAAAUAGCAAGUUAAAAUAAGGCUAGUCCGUUAUCAACUUGAAAAAGUGGCACCGAGUCGGUGCUUU\"\n\n    full_sgrna = guide_seq.upper().replace(\"T\", \"U\") + scaffold\n    fc = RNA.fold_compound(full_sgrna)\n    structure, mfe = fc.mfe()\n    fc.exp_params_rescale(mfe)\n    fc.pf()\n    bpp = fc.bpp()\n\n    n_guide = len(guide_seq)\n    # Check if any guide bases are paired (bad for targeting)\n    guide_paired = sum(\n        bpp[min(i, j)][max(i, j)]\n        for i in range(1, n_guide + 1)\n        for j in range(1, n_guide + 1)\n        if i != j\n    )\n    guide_accessibility = 1.0 - min(1.0, guide_paired \u002F n_guide)\n    return {\n        \"guide_seq\":    guide_seq,\n        \"mfe\":          mfe,\n        \"structure\":    structure[:n_guide],\n        \"guide_access\": guide_accessibility,\n        \"predicted_ok\": guide_accessibility > 0.7,\n    }\n\nguides = [\"GCACUAGUGACGCAUGGCAC\", \"GGGCAUAGCUAGCUAGCUAU\", \"AAAUUCGCACUAGUGACGCA\"]\nfor g in guides:\n    result = assess_sgrna(g)\n    status = \"OK\" if result[\"predicted_ok\"] else \"WARN (self-paired)\"\n    print(f\"{g}: accessibility={result['guide_access']:.2f}, MFE={result['mfe']:.1f} kcal\u002Fmol  [{status}]\")\n```\n\n### Recipe: Mountain Plot Visualization of RNA Structure\n\nWhen to use: Create a mountain plot — a classic RNA structure visualization showing stem height along the sequence.\n\n```python\nimport RNA\nimport matplotlib.pyplot as plt\n\ndef dot_bracket_to_mountain(structure: str) -> list:\n    \"\"\"Convert dot-bracket structure to mountain plot heights.\"\"\"\n    heights = []\n    level = 0\n    for c in structure:\n        if c == \"(\":\n            level += 1\n        heights.append(level)\n        if c == \")\":\n            level -= 1\n    return heights\n\nsequence = \"GCGGAUUUAGCUCAGUUGGGAGAGCGCCAGACUGAAGAUCUGGAGGUCCUGUGUUCGAUCCACAGAAUUCGCACCA\"\nstructure, mfe = RNA.fold(sequence)\nheights = dot_bracket_to_mountain(structure)\n\nfig, axes = plt.subplots(2, 1, figsize=(12, 5), sharex=True,\n                          gridspec_kw={\"height_ratios\": [1, 3]})\n\n# Top: sequence text\naxes[0].text(0.5, 0.5, \"tRNA-Phe  |  E. coli\", ha=\"center\", va=\"center\",\n             fontsize=10, transform=axes[0].transAxes)\naxes[0].axis(\"off\")\n\n# Bottom: mountain plot\naxes[1].fill_between(range(len(sequence)), heights, step=\"mid\",\n                      color=\"#2c7bb6\", alpha=0.7, label=f\"MFE = {mfe:.2f} kcal\u002Fmol\")\naxes[1].set_xlabel(\"Nucleotide position\")\naxes[1].set_ylabel(\"Stem height\")\naxes[1].set_title(\"Mountain Plot\")\naxes[1].legend()\nplt.tight_layout()\nplt.savefig(\"mountain_plot.png\", dpi=150, bbox_inches=\"tight\")\nprint(f\"Saved: mountain_plot.png  (MFE structure: {structure[:40]}...)\")\n```\n\n## Expected Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `structure` | string | Dot-bracket notation of MFE secondary structure; `(` and `)` for paired bases, `.` for unpaired |\n| `mfe` | float (kcal\u002Fmol) | Minimum free energy of the predicted structure; more negative = more stable |\n| `bpp` | (n+1)×(n+1) matrix | Base pair probability matrix from partition function; element `[i][j]` = P(i paired with j), 1-indexed |\n| `bpp_matrix.png` | PNG | Heatmap visualization of base pair probabilities |\n| `rna_accessibility.png` | PNG | Per-position probability of being unpaired |\n| `mountain_plot.png` | PNG | Mountain plot of stem heights along the sequence |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| `ImportError: No module named 'RNA'` | ViennaRNA Python bindings not installed | Install via `conda install -c conda-forge viennarna`; `pip install` alone may fail to link C library |\n| `RuntimeError: RNAfold not found` | ViennaRNA CLI not in PATH | Confirm with `which RNAfold`; if using conda env, activate it before running scripts |\n| MFE is unexpectedly positive (> 0) | Very short or repetitive sequence with no favorable pairs | Short sequences (\u003C 10 nt) often have positive MFE; check sequence length and composition |\n| `bpp` matrix all zeros after `fc.pf()` | `fc.mfe()` must be called before `fc.pf()` on the same fold compound | Always call `fc.mfe()` first, then `fc.exp_params_rescale(mfe)`, then `fc.pf()` |\n| Suboptimal enumeration returns thousands of structures | Window too large for long sequences | Reduce delta to 2–3 kcal\u002Fmol for long sequences; very stable sequences have dense suboptimal ensembles |\n| Co-fold (`RNA.cofold`) shows unexpected pairing | Intramolecular folding dominates in one strand | Inspect each strand separately first; low individual-strand MFE indicates strong self-structure interfering with duplex |\n\n## References\n\n- [ViennaRNA documentation](https:\u002F\u002Fwww.tbi.univie.ac.at\u002FRNA\u002F) — official documentation, parameter files, and Python API reference\n- [Lorenz et al., Algorithms Mol Biol 2011](https:\u002F\u002Fdoi.org\u002F10.1186\u002F1748-7188-6-26) — ViennaRNA Package 2.0 paper (primary citation for structure prediction)\n- [Turner & Mathews, Nucleic Acids Res 2010](https:\u002F\u002Fdoi.org\u002F10.1093\u002Fnar\u002Fgkp892) — Nearest-neighbor thermodynamic parameters used by ViennaRNA\n- [ViennaRNA GitHub: ViennaRNA\u002FViennaRNA](https:\u002F\u002Fgithub.com\u002FViennaRNA\u002FViennaRNA) — source code, issue tracker, Python tutorial notebooks\n",{"name":5,"license":15,"description":7},"master","63f17866001c5ca854bf2fa0b678ce277133de5b","skills\u002Fawesome-skills\u002Fviennarna-structure-prediction",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill viennarna-structure-prediction",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill viennarna-structure-prediction",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill viennarna-structure-prediction","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fviennarna-structure-prediction\u002FSKILL.md",true,[],[49,57,64,71,78,85],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":56},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":56},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":56},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":56},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":56},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]