[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EC6EG16W3V0Y0QKFAEYZCB":3,"skill-same:01M7EC6EG16W3V0Y0QKFAEYZCB":70},{"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":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7EC6EG16W3V0Y0QKFAEYZCB","bio-codon-usage",null,"Analyze codon usage and calculate CAI (Codon Adaptation Index), RSCU, and Nc with Biopython, and produce naive max-CAI codon-optimized sequences. Use when scoring a gene's codon bias against a host, optimizing a CDS for heterologous expression, or studying synonymous codon selection.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-codon-usage\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-codon-usage\ndescription: Analyze codon usage and calculate CAI (Codon Adaptation Index), RSCU, and Nc with Biopython, and produce naive max-CAI codon-optimized sequences. Use when scoring a gene's codon bias against a host, optimizing a CDS for heterologous expression, or studying synonymous codon selection.\ntool_type: python\nprimary_tool: Bio.SeqUtils.CodonAdaptationIndex\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"sequence-manipulation\u002Fcodon-usage\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: BioPython 1.83+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Codon Usage\n\nAnalyze codon usage patterns, score adaptation to a host, and optimize coding sequences for expression.\n\n**\"Analyze codon usage\"** -> Count codons in a coding sequence, compute frequencies and bias metrics.\n- Python: `Counter` on in-frame triplets + RSCU\u002FNc helpers (BioPython + standard library)\n\n**\"Score this gene against a host\"** -> Compute the Codon Adaptation Index from a reference set of highly expressed genes.\n- Python: `CodonAdaptationIndex(reference_seqs).calculate(query)` (BioPython)\n\n**\"Optimize codons for expression\"** -> Replace each codon with the host's single most-preferred synonymous codon.\n- Python: `CodonAdaptationIndex(reference_seqs).optimize(seq)` (BioPython)\n\n## The governing principle\n\nCAI is meaningless without an expression-biased reference. The relative-adaptiveness weights (w) must be built from the **highly expressed genes of the TARGET organism** (ribosomal proteins, elongation factors). A CAI computed against a whole-genome average, or against the wrong organism, is a number with no biological meaning. There is no bundled reference index in modern Biopython, so the reference set is always the caller's responsibility.\n\nTwo silent traps dominate this skill:\n- **Out-of-frame input is silently corrupted.** `calculate` blindly steps `range(0, len, 3)` from position 0; it never checks the reading frame. A frame-shifted CDS returns a plausible CAI computed from garbage codons. Frame correctness is the caller's job (length divisible by 3, starts at the first base of codon 1).\n- **Naive max-CAI optimization can REDUCE expression.** `optimize()` is the textbook max-CAI output (single most-frequent codon per amino acid). It is blind to the translation ramp, 5' mRNA structure, GC extremes, cryptic regulatory elements, and codon-pair bias. It is a starting point to screen, never a final design. Failure is silent: correct protein, high CAI, poor expression.\n\n## CRITICAL API migration (Biopython 1.82)\n\n`Bio.SeqUtils.CodonUsage` and `Bio.SeqUtils.CodonUsageIndices` were **removed in Biopython 1.82**. Any code calling `generate_index()`, `set_cai_index()`, `cai_for_gene()`, `print_index()`, or importing `SharpEcoliIndex` raises ImportError on any modern install. The replacement is a redesigned class imported directly from `Bio.SeqUtils`:\n\n```python\nfrom Bio.SeqUtils import CodonAdaptationIndex  # NOT Bio.SeqUtils.CodonUsage (removed)\n```\n\n| Removed (\u003C=1.81) | Replacement (>=1.82) |\n|------------------|----------------------|\n| `CodonAdaptationIndex()` then `generate_index(fasta)` | `CodonAdaptationIndex(reference_seqs, table=...)` constructor |\n| `cai.cai_for_gene(seq)` | `cai.calculate(seq)` |\n| `cai.set_cai_index(d)` | `cai.update(d)` (it is a dict subclass) |\n| `SharpEcoliIndex` (bundled) | none -- build from a supplied reference CDS set |\n| `cai.print_index()` | iterate the object: `for codon, w in cai.items()` |\n\n## Required Imports\n\n```python\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqUtils import CodonAdaptationIndex, GC123\nfrom Bio.Data.CodonTable import standard_dna_table\nfrom Bio.Data import CodonTable\nfrom collections import Counter\n```\n\n## Codon Adaptation Index (CAI)\n\n**Goal:** Measure how closely a gene's codon usage matches the highly expressed genes of a host organism.\n\n**Approach:** Build a `CodonAdaptationIndex` from a reference set of highly expressed CDS (the constructor computes per-codon relative adaptiveness w), then score query sequences with `calculate` (0-1, higher = better adapted).\n\n```python\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqUtils import CodonAdaptationIndex\nfrom Bio.Data.CodonTable import standard_dna_table\n\n# Reference = highly expressed genes of the TARGET host (ribosomal proteins, EFs).\n# Parse a FASTA yourself; there is no bundled index. Pass str\u002FSeq\u002FSeqRecord.\nreference_seqs = list(SeqIO.parse('highly_expressed_genes.fasta', 'fasta'))\ncai = CodonAdaptationIndex(reference_seqs, table=standard_dna_table)\n\nquery = Seq('ATGAAACGTGCTGAAGCTAAATAA')\nscore = cai.calculate(query)   # 0-1; the query MUST be in-frame (see governing principle)\nprint(f'CAI: {score:.3f}')\n```\n\n`CodonAdaptationIndex` **is a dict subclass** -- the codon->w mapping is the object itself. Inspect or override weights directly:\n\n```python\nprint(cai['GCT'])         # relative adaptiveness of Ala codon GCT\ncai.update({'GCT': 0.9})  # override a weight (replaces the old set_cai_index)\n```\n\nVerified behavior (Biopython >=1.82):\n- **ATG (Met) and TGG (Trp) are excluded** from CAI -- single-codon families, w is always 1.\n- **Stop codons are excluded.**\n- **Unobserved codons get w = 0.5** (Sharp & Li), softly down-weighted; no division-by-zero.\n- **Case-insensitive** -- both the constructor and `calculate` uppercase internally.\n- An illegal codon (non-ACGT) in a reference raises `ValueError`; an illegal or trailing-partial codon in a query raises `TypeError`. Out-of-frame input does NOT raise -- it is silently mis-scored.\n\n## RSCU = w is built from these ratios\n\nCAI weights come from RSCU. w_ij = RSCU_ij \u002F RSCU_jmax = (codon count) \u002F (count of the most-used synonymous codon in that family); CAI = exp((1\u002FL) * sum ln w). RSCU itself = observed count \u002F expected-if-uniform within a synonymous family (=1 no bias, >1 over-used, \u003C1 under-used). RSCU normalizes away amino-acid composition, which is why w is built from RSCU ratios rather than raw frequencies.\n\n**Goal:** Quantify synonymous codon bias to detect translational selection or mutational pressure.\n\n**Approach:** Group codons by amino acid via the codon table, then divide each codon's observed count by the family mean.\n\n```python\nfrom Bio.Data import CodonTable\nfrom collections import Counter\n\ndef count_codons(seq):\n    s = str(seq).upper()\n    return Counter(s[i:i+3] for i in range(0, len(s) - 2, 3))\n\ndef calculate_rscu(seq, table_id=1):\n    '''RSCU per codon: observed \u002F expected-if-uniform within its synonymous family'''\n    table = CodonTable.unambiguous_dna_by_id[table_id]\n    counts = count_codons(seq)\n    back_table = {}\n    for codon, aa in table.forward_table.items():\n        back_table.setdefault(aa, []).append(codon)\n    rscu = {}\n    for aa, codons in back_table.items():\n        total = sum(counts.get(c, 0) for c in codons)\n        expected = total \u002F len(codons) if codons else 0\n        for codon in codons:\n            rscu[codon] = counts.get(codon, 0) \u002F expected if expected > 0 else 0\n    return rscu\n```\n\n## Codon optimization for expression\n\n**Goal:** Generate a host-adapted CDS that preserves the protein.\n\n**Approach:** `optimize()` swaps each amino acid for the host's single most-preferred synonymous codon (max-CAI). Always confirm the protein is unchanged, then screen the design against the tradeoffs below.\n\n```python\nopt = cai.optimize(query, seq_type='DNA', strict=True)\nassert opt.translate() == query.translate()   # protein must be identical\n```\n\n`optimize(sequence, seq_type='DNA'|'RNA'|'protein', strict=True)`: `strict=True` **raises ValueError on a tie** (two equally-preferred codons, e.g. `'TTT and TTC are equally preferred.'`); `strict=False` warns and picks one.\n\n### Why naive max-CAI can HURT expression\n\n`optimize()` is blind to everything except single-codon frequency. Screen the output for:\n- **The translation ramp** (Tuller et al. 2010): a conserved profile of slow (rare) codons over the first ~30-50 codons spaces ribosomes; flattening it can lower yield and increase misfolding.\n- **5' mRNA secondary structure:** strong folding near the start codon impedes initiation. Minimize 5' free energy, sometimes against CAI.\n- **GC extremes:** swaps that push GC very high create stable hairpins; very low GC destabilizes.\n- **Cryptic elements created by swaps:** splice sites, internal Shine-Dalgarno\u002FRBS, polyadenylation signals, restriction sites, AU-rich destabilizing elements -- silent in protein, corrupting in expression.\n- **Codon-pair bias:** decoding efficiency depends on adjacent codon pairs; CAI scores single codons only.\n\n### tAI -- the supply-side alternative\n\nThe tRNA Adaptation Index (dos Reis et al. 2004) weights each codon by **tRNA gene copy number** (a proxy for tRNA abundance) scaled by wobble-pairing efficiency at the third position. Where tRNA copy number is a good abundance proxy, tAI tracks expression and elongation speed better than CAI. tAI is **not in Biopython** -- use the R `tAI` package or reimplement.\n\n## Synonymous bias by other metrics\n\n### Effective Number of Codons (Nc)\n\nA reference-free bias measure (lower = more biased; range ~20 fully biased to 61 unbiased). The helper below is a simplified per-amino-acid approximation: Wright's published estimator averages the homozygosity F WITHIN each degeneracy class (2-, 3-, 4-, 6-fold) before combining as `Nc = 2 + 9\u002FF2 + 1\u002FF3 + 5\u002FF4 + 3\u002FF6`. The endpoints agree, but intermediate values will not match codonW\u002Fstandard Nc when families in a class have unequal F. For comparable Nc, average F by class per Wright (1990) or use codonW.\n\n```python\nimport math\nfrom Bio.Data import CodonTable\n\ndef effective_nc(seq, table_id=1):\n    table = CodonTable.unambiguous_dna_by_id[table_id]\n    counts = count_codons(seq)\n    aa_groups = {}\n    for codon, aa in table.forward_table.items():\n        aa_groups.setdefault(aa, []).append(codon)\n    nc_sum = 0\n    for aa, codons in aa_groups.items():\n        n = sum(counts.get(c, 0) for c in codons)\n        if n \u003C= 1:\n            continue\n        pi_sq = sum((counts.get(c, 0) \u002F n) ** 2 for c in codons)\n        F = (n * pi_sq - 1) \u002F (n - 1)\n        nc_sum += 1 \u002F F if F > 0 else len(codons)\n    return nc_sum if nc_sum > 0 else 61\n```\n\n### GC at codon positions (GC123)\n\n```python\nfrom Bio.SeqUtils import GC123\n\ngc_total, gc_pos1, gc_pos2, gc_pos3 = GC123(seq)  # four PERCENTAGES (0-100)\nprint(f'GC3 (wobble): {gc_pos3:.1f}%')             # correlates with genome GC\n```\n\nGC123 returns percentages (0-100), unlike `gc_fraction` which returns 0-1. GC3 at the wobble position usually tracks overall genome GC content.\n\n## Codon tables\n\n```python\nfrom Bio.Data import CodonTable\n\ntable = CodonTable.unambiguous_dna_by_id[1]   # standard genetic code\nprint(table.start_codons, table.stop_codons)\nprint(table.forward_table['ATG'])             # 'M'\n```\n\n| ID | Name | Organism |\n|----|------|----------|\n| 1 | Standard | Most nuclear genomes |\n| 2 | Vertebrate Mitochondrial | Human\u002Fmouse mito |\n| 4 | Mold\u002FProtozoan Mitochondrial | Fungi, protozoa mito |\n| 5 | Invertebrate Mitochondrial | Insects, worms mito |\n| 11 | Bacterial\u002FPlastid | E. coli, chloroplasts |\n\nPass the matching `table=` to `CodonAdaptationIndex` when scoring mitochondrial or bacterial genes.\n\n## Metric reference\n\n| Metric | Range | Reference needed | Interpretation |\n|--------|-------|------------------|----------------|\n| CAI | 0-1 | Highly expressed genes of the host | Higher = better adapted |\n| RSCU | 0-N | None (within-sequence) | 1 = no bias, >1 over-used |\n| Nc | ~20-61 | None | Lower = more biased |\n| GC3 | 0-100% | None | GC at wobble position |\n| tAI | 0-1 | tRNA gene copy numbers | Higher = better tRNA supply |\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| `ImportError: cannot import name 'CodonUsage'` | `Bio.SeqUtils.CodonUsage` removed in 1.82 | `from Bio.SeqUtils import CodonAdaptationIndex` |\n| `AttributeError: 'CodonAdaptationIndex' object has no attribute 'generate_index'` | Old API on new class | Build in the constructor; score with `calculate` |\n| Plausible CAI from a frame-shifted CDS | Out-of-frame input silently mis-scored | Confirm frame: length divisible by 3, starts at codon 1 |\n| CAI near 1 for every gene | Reference set is whole-genome, not expression-biased | Use only highly expressed genes of the target host |\n| `ValueError: ... equally preferred` | `optimize(strict=True)` hit a tie | Pass `strict=False`, or curate weights with `update` |\n| High CAI but poor expression in the lab | Max-CAI ignores ramp \u002F 5' structure \u002F cryptic sites | Screen `optimize()` output; treat it as a draft |\n\n## Related Skills\n\n- transcription-translation - Translate CDS and select the correct codon table\n- sequence-properties - GC123 and per-position GC content\n- sequence-io\u002Fread-sequences - Parse reference CDS from FASTA\u002FGenBank for CAI training\n- database-access\u002Fentrez-fetch - Fetch highly expressed gene sets from NCBI for CAI references\n\n## References\n\nSharp PM, Li WH (1987) The codon adaptation index -- a measure of directional synonymous codon usage bias, and its potential applications. Nucleic Acids Res 15(3):1281-1295.\n\ndos Reis M, Savva R, Wernisch L (2004) Solving the riddle of codon usage preferences: a test for translational selection. Nucleic Acids Res 32(17):5036-5044.\n\nTuller T, Carmi A, Vestsigian K, Navon S, Dorfan Y, Zaborske J, Pan T, Dahan O, Furman I, Pilpel Y (2010) An evolutionarily conserved mechanism for controlling the efficiency of protein translation. Cell 141(2):344-354.\n\nWright F (1990) The 'effective number of codons' used in a gene. Gene 87(1):23-29.\n","## Version Compatibility\n\nReference examples tested with: BioPython 1.83+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Codon Usage\n\nAnalyze codon usage patterns, score adaptation to a host, and optimize coding sequences for expression.\n\n**\"Analyze codon usage\"** -> Count codons in a coding sequence, compute frequencies and bias metrics.\n- Python: `Counter` on in-frame triplets + RSCU\u002FNc helpers (BioPython + standard library)\n\n**\"Score this gene against a host\"** -> Compute the Codon Adaptation Index from a reference set of highly expressed genes.\n- Python: `CodonAdaptationIndex(reference_seqs).calculate(query)` (BioPython)\n\n**\"Optimize codons for expression\"** -> Replace each codon with the host's single most-preferred synonymous codon.\n- Python: `CodonAdaptationIndex(reference_seqs).optimize(seq)` (BioPython)\n\n## The governing principle\n\nCAI is meaningless without an expression-biased reference. The relative-adaptiveness weights (w) must be built from the **highly expressed genes of the TARGET organism** (ribosomal proteins, elongation factors). A CAI computed against a whole-genome average, or against the wrong organism, is a number with no biological meaning. There is no bundled reference index in modern Biopython, so the reference set is always the caller's responsibility.\n\nTwo silent traps dominate this skill:\n- **Out-of-frame input is silently corrupted.** `calculate` blindly steps `range(0, len, 3)` from position 0; it never checks the reading frame. A frame-shifted CDS returns a plausible CAI computed from garbage codons. Frame correctness is the caller's job (length divisible by 3, starts at the first base of codon 1).\n- **Naive max-CAI optimization can REDUCE expression.** `optimize()` is the textbook max-CAI output (single most-frequent codon per amino acid). It is blind to the translation ramp, 5' mRNA structure, GC extremes, cryptic regulatory elements, and codon-pair bias. It is a starting point to screen, never a final design. Failure is silent: correct protein, high CAI, poor expression.\n\n## CRITICAL API migration (Biopython 1.82)\n\n`Bio.SeqUtils.CodonUsage` and `Bio.SeqUtils.CodonUsageIndices` were **removed in Biopython 1.82**. Any code calling `generate_index()`, `set_cai_index()`, `cai_for_gene()`, `print_index()`, or importing `SharpEcoliIndex` raises ImportError on any modern install. The replacement is a redesigned class imported directly from `Bio.SeqUtils`:\n\n```python\nfrom Bio.SeqUtils import CodonAdaptationIndex  # NOT Bio.SeqUtils.CodonUsage (removed)\n```\n\n| Removed (\u003C=1.81) | Replacement (>=1.82) |\n|------------------|----------------------|\n| `CodonAdaptationIndex()` then `generate_index(fasta)` | `CodonAdaptationIndex(reference_seqs, table=...)` constructor |\n| `cai.cai_for_gene(seq)` | `cai.calculate(seq)` |\n| `cai.set_cai_index(d)` | `cai.update(d)` (it is a dict subclass) |\n| `SharpEcoliIndex` (bundled) | none -- build from a supplied reference CDS set |\n| `cai.print_index()` | iterate the object: `for codon, w in cai.items()` |\n\n## Required Imports\n\n```python\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqUtils import CodonAdaptationIndex, GC123\nfrom Bio.Data.CodonTable import standard_dna_table\nfrom Bio.Data import CodonTable\nfrom collections import Counter\n```\n\n## Codon Adaptation Index (CAI)\n\n**Goal:** Measure how closely a gene's codon usage matches the highly expressed genes of a host organism.\n\n**Approach:** Build a `CodonAdaptationIndex` from a reference set of highly expressed CDS (the constructor computes per-codon relative adaptiveness w), then score query sequences with `calculate` (0-1, higher = better adapted).\n\n```python\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqUtils import CodonAdaptationIndex\nfrom Bio.Data.CodonTable import standard_dna_table\n\n# Reference = highly expressed genes of the TARGET host (ribosomal proteins, EFs).\n# Parse a FASTA yourself; there is no bundled index. Pass str\u002FSeq\u002FSeqRecord.\nreference_seqs = list(SeqIO.parse('highly_expressed_genes.fasta', 'fasta'))\ncai = CodonAdaptationIndex(reference_seqs, table=standard_dna_table)\n\nquery = Seq('ATGAAACGTGCTGAAGCTAAATAA')\nscore = cai.calculate(query)   # 0-1; the query MUST be in-frame (see governing principle)\nprint(f'CAI: {score:.3f}')\n```\n\n`CodonAdaptationIndex` **is a dict subclass** -- the codon->w mapping is the object itself. Inspect or override weights directly:\n\n```python\nprint(cai['GCT'])         # relative adaptiveness of Ala codon GCT\ncai.update({'GCT': 0.9})  # override a weight (replaces the old set_cai_index)\n```\n\nVerified behavior (Biopython >=1.82):\n- **ATG (Met) and TGG (Trp) are excluded** from CAI -- single-codon families, w is always 1.\n- **Stop codons are excluded.**\n- **Unobserved codons get w = 0.5** (Sharp & Li), softly down-weighted; no division-by-zero.\n- **Case-insensitive** -- both the constructor and `calculate` uppercase internally.\n- An illegal codon (non-ACGT) in a reference raises `ValueError`; an illegal or trailing-partial codon in a query raises `TypeError`. Out-of-frame input does NOT raise -- it is silently mis-scored.\n\n## RSCU = w is built from these ratios\n\nCAI weights come from RSCU. w_ij = RSCU_ij \u002F RSCU_jmax = (codon count) \u002F (count of the most-used synonymous codon in that family); CAI = exp((1\u002FL) * sum ln w). RSCU itself = observed count \u002F expected-if-uniform within a synonymous family (=1 no bias, >1 over-used, \u003C1 under-used). RSCU normalizes away amino-acid composition, which is why w is built from RSCU ratios rather than raw frequencies.\n\n**Goal:** Quantify synonymous codon bias to detect translational selection or mutational pressure.\n\n**Approach:** Group codons by amino acid via the codon table, then divide each codon's observed count by the family mean.\n\n```python\nfrom Bio.Data import CodonTable\nfrom collections import Counter\n\ndef count_codons(seq):\n    s = str(seq).upper()\n    return Counter(s[i:i+3] for i in range(0, len(s) - 2, 3))\n\ndef calculate_rscu(seq, table_id=1):\n    '''RSCU per codon: observed \u002F expected-if-uniform within its synonymous family'''\n    table = CodonTable.unambiguous_dna_by_id[table_id]\n    counts = count_codons(seq)\n    back_table = {}\n    for codon, aa in table.forward_table.items():\n        back_table.setdefault(aa, []).append(codon)\n    rscu = {}\n    for aa, codons in back_table.items():\n        total = sum(counts.get(c, 0) for c in codons)\n        expected = total \u002F len(codons) if codons else 0\n        for codon in codons:\n            rscu[codon] = counts.get(codon, 0) \u002F expected if expected > 0 else 0\n    return rscu\n```\n\n## Codon optimization for expression\n\n**Goal:** Generate a host-adapted CDS that preserves the protein.\n\n**Approach:** `optimize()` swaps each amino acid for the host's single most-preferred synonymous codon (max-CAI). Always confirm the protein is unchanged, then screen the design against the tradeoffs below.\n\n```python\nopt = cai.optimize(query, seq_type='DNA', strict=True)\nassert opt.translate() == query.translate()   # protein must be identical\n```\n\n`optimize(sequence, seq_type='DNA'|'RNA'|'protein', strict=True)`: `strict=True` **raises ValueError on a tie** (two equally-preferred codons, e.g. `'TTT and TTC are equally preferred.'`); `strict=False` warns and picks one.\n\n### Why naive max-CAI can HURT expression\n\n`optimize()` is blind to everything except single-codon frequency. Screen the output for:\n- **The translation ramp** (Tuller et al. 2010): a conserved profile of slow (rare) codons over the first ~30-50 codons spaces ribosomes; flattening it can lower yield and increase misfolding.\n- **5' mRNA secondary structure:** strong folding near the start codon impedes initiation. Minimize 5' free energy, sometimes against CAI.\n- **GC extremes:** swaps that push GC very high create stable hairpins; very low GC destabilizes.\n- **Cryptic elements created by swaps:** splice sites, internal Shine-Dalgarno\u002FRBS, polyadenylation signals, restriction sites, AU-rich destabilizing elements -- silent in protein, corrupting in expression.\n- **Codon-pair bias:** decoding efficiency depends on adjacent codon pairs; CAI scores single codons only.\n\n### tAI -- the supply-side alternative\n\nThe tRNA Adaptation Index (dos Reis et al. 2004) weights each codon by **tRNA gene copy number** (a proxy for tRNA abundance) scaled by wobble-pairing efficiency at the third position. Where tRNA copy number is a good abundance proxy, tAI tracks expression and elongation speed better than CAI. tAI is **not in Biopython** -- use the R `tAI` package or reimplement.\n\n## Synonymous bias by other metrics\n\n### Effective Number of Codons (Nc)\n\nA reference-free bias measure (lower = more biased; range ~20 fully biased to 61 unbiased). The helper below is a simplified per-amino-acid approximation: Wright's published estimator averages the homozygosity F WITHIN each degeneracy class (2-, 3-, 4-, 6-fold) before combining as `Nc = 2 + 9\u002FF2 + 1\u002FF3 + 5\u002FF4 + 3\u002FF6`. The endpoints agree, but intermediate values will not match codonW\u002Fstandard Nc when families in a class have unequal F. For comparable Nc, average F by class per Wright (1990) or use codonW.\n\n```python\nimport math\nfrom Bio.Data import CodonTable\n\ndef effective_nc(seq, table_id=1):\n    table = CodonTable.unambiguous_dna_by_id[table_id]\n    counts = count_codons(seq)\n    aa_groups = {}\n    for codon, aa in table.forward_table.items():\n        aa_groups.setdefault(aa, []).append(codon)\n    nc_sum = 0\n    for aa, codons in aa_groups.items():\n        n = sum(counts.get(c, 0) for c in codons)\n        if n \u003C= 1:\n            continue\n        pi_sq = sum((counts.get(c, 0) \u002F n) ** 2 for c in codons)\n        F = (n * pi_sq - 1) \u002F (n - 1)\n        nc_sum += 1 \u002F F if F > 0 else len(codons)\n    return nc_sum if nc_sum > 0 else 61\n```\n\n### GC at codon positions (GC123)\n\n```python\nfrom Bio.SeqUtils import GC123\n\ngc_total, gc_pos1, gc_pos2, gc_pos3 = GC123(seq)  # four PERCENTAGES (0-100)\nprint(f'GC3 (wobble): {gc_pos3:.1f}%')             # correlates with genome GC\n```\n\nGC123 returns percentages (0-100), unlike `gc_fraction` which returns 0-1. GC3 at the wobble position usually tracks overall genome GC content.\n\n## Codon tables\n\n```python\nfrom Bio.Data import CodonTable\n\ntable = CodonTable.unambiguous_dna_by_id[1]   # standard genetic code\nprint(table.start_codons, table.stop_codons)\nprint(table.forward_table['ATG'])             # 'M'\n```\n\n| ID | Name | Organism |\n|----|------|----------|\n| 1 | Standard | Most nuclear genomes |\n| 2 | Vertebrate Mitochondrial | Human\u002Fmouse mito |\n| 4 | Mold\u002FProtozoan Mitochondrial | Fungi, protozoa mito |\n| 5 | Invertebrate Mitochondrial | Insects, worms mito |\n| 11 | Bacterial\u002FPlastid | E. coli, chloroplasts |\n\nPass the matching `table=` to `CodonAdaptationIndex` when scoring mitochondrial or bacterial genes.\n\n## Metric reference\n\n| Metric | Range | Reference needed | Interpretation |\n|--------|-------|------------------|----------------|\n| CAI | 0-1 | Highly expressed genes of the host | Higher = better adapted |\n| RSCU | 0-N | None (within-sequence) | 1 = no bias, >1 over-used |\n| Nc | ~20-61 | None | Lower = more biased |\n| GC3 | 0-100% | None | GC at wobble position |\n| tAI | 0-1 | tRNA gene copy numbers | Higher = better tRNA supply |\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| `ImportError: cannot import name 'CodonUsage'` | `Bio.SeqUtils.CodonUsage` removed in 1.82 | `from Bio.SeqUtils import CodonAdaptationIndex` |\n| `AttributeError: 'CodonAdaptationIndex' object has no attribute 'generate_index'` | Old API on new class | Build in the constructor; score with `calculate` |\n| Plausible CAI from a frame-shifted CDS | Out-of-frame input silently mis-scored | Confirm frame: length divisible by 3, starts at codon 1 |\n| CAI near 1 for every gene | Reference set is whole-genome, not expression-biased | Use only highly expressed genes of the target host |\n| `ValueError: ... equally preferred` | `optimize(strict=True)` hit a tie | Pass `strict=False`, or curate weights with `update` |\n| High CAI but poor expression in the lab | Max-CAI ignores ramp \u002F 5' structure \u002F cryptic sites | Screen `optimize()` output; treat it as a draft |\n\n## Related Skills\n\n- transcription-translation - Translate CDS and select the correct codon table\n- sequence-properties - GC123 and per-position GC content\n- sequence-io\u002Fread-sequences - Parse reference CDS from FASTA\u002FGenBank for CAI training\n- database-access\u002Fentrez-fetch - Fetch highly expressed gene sets from NCBI for CAI references\n\n## References\n\nSharp PM, Li WH (1987) The codon adaptation index -- a measure of directional synonymous codon usage bias, and its potential applications. Nucleic Acids Res 15(3):1281-1295.\n\ndos Reis M, Savva R, Wernisch L (2004) Solving the riddle of codon usage preferences: a test for translational selection. Nucleic Acids Res 32(17):5036-5044.\n\nTuller T, Carmi A, Vestsigian K, Navon S, Dorfan Y, Zaborske J, Pan T, Dahan O, Furman I, Pilpel Y (2010) An evolutionarily conserved mechanism for controlling the efficiency of protein translation. Cell 141(2):344-354.\n\nWright F (1990) The 'effective number of codons' used in a gene. Gene 87(1):23-29.\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","python","2026-09-20","sequence-manipulation\u002Fcodon-usage\u002FSKILL.md","Bio.SeqUtils.CodonAdaptationIndex","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-codon-usage","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-codon-usage",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-codon-usage",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-codon-usage","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-codon-usage\u002FSKILL.md",true,[50,56,60,64],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fbasic_analysis.py","SCRIPT","脚本",1783,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-codon-usage\u002Fexamples\u002Fbasic_analysis.py",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"examples\u002Fcai_optimization.py",2502,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-codon-usage\u002Fexamples\u002Fcai_optimization.py",{"path":61,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":62,"sourceHtmlUrl":63},"examples\u002Frscu_analysis.py",2445,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-codon-usage\u002Fexamples\u002Frscu_analysis.py",{"path":65,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":69},"usage-guide.md","REFERENCE","参考文档",4562,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-codon-usage\u002Fusage-guide.md",[71,79,86,93,100,107],{"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":78},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":78},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":78},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":78},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":78},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":78},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]