McWhite Lab

A blinded language-model screen for repeats in human proteins

We asked a language model, Gemini Carbon, to find repeats in human proteins by reading the sequences alone, i.e. using no code, no tools, no search and no protein names. While recognizing these patterns is extremely difficult for the human eye, we consider this to be a task that naturally suits the abilities of LLMs to recognize patterns in sequences. Repeats are especially common in disordered regions (Tompa, 2003; Simon & Hancock, 2009; Jorda et al., 2010). Many of the repeats in disordered or mixed sequence are potential novel short linear motifs (SLiMs), the short peptide modules that mediate many protein interactions in disordered regions (Van Roey et al., 2014).

human proteins screened
with at least one repeat array
structured repeat arrays
disordered or mixed repeat arrays
located repeat copies
Structured
Tandem arrayNFKBIA ankyrin repeats: five ~35-aa helix-turn-helix units stacked into a solenoid.
Gallery of structured repeat architectures →
Disordered/mixed
Tandem arrayPRNP octarepeats: five PHGGGWGQ copies head to tail in the disordered N-terminal region. Their histidines bind copper ions.
Dispersed arrayNUP98 GLFG repeats: eight copies spread through the disordered FG region. They bind nuclear transport receptors and together form the selective barrier of the nuclear pore.

Why look for repeats in disordered regions?

Repeats can add function to proteins outside of structured regions:

  • Short linear motifs: many arrays are repeated copies of well-characterized SLiMs, peptide motifs of about 3–10 residues that bind partner proteins or mark sites for modification, such as the EH-domain-binding NPF motifs of EPN1 (Van Roey et al., 2014).
  • Multivalency: repeated binding motifs engage several partners at once, as the phosphotyrosines of LAT do in recruiting signaling proteins into condensates (Li et al., 2012; Su et al., 2016).
  • Collective properties: an array can act as a whole, as the FG repeats of NUP98 do in forming the selective barrier of the nuclear pore (Frey et al., 2006).
  • Longer units: repeat units can be much longer than canonical SLiMs, such as the 21-residue repeats of PRB4 (Kim et al., 1993).
  • Multisite modification: arrays provide many modification sites, as in the POLR2A CTD heptads that carry the CTD code (Buratowski, 2003) and the KSP repeats of NEFH.

Analysis of known and novel SLiMs

Known

?A repeat array is Known when the repeat itself is annotated in UniProt, curated in ELM, or described in a paper we can cite. Examples: the RNA polymerase II CTD heptads, neurofilament KSP repeats, nucleoporin GLFG units, prohormone cleavage repeats and curated docking motifs.

Known motif, new place

A known motif, repeated in an array that UniProt and ELM do not record.?The unit matches a specific motif class at the same position in at least 80% of copies. Most are docking motifs (SH2-binding tyrosines, NPF, IQ); the rest are modification sites at the same position in most copies.

In a functional region

Most copies sit inside a region that UniProt assigns a function to.?At least half of the copies lie inside a UniProt Region feature that names a function, such as an interaction with a partner protein, and no UniProt Repeat, Domain or Zinc finger feature covers them.

Novel

?No UniProt repeat, domain or region annotation, no curated ELM instance and no specific motif class. All are in disordered or mixed sequence.

Other

Disordered or mixed repeat arrays that fit none of the four groups above.

Browse the worked examples

All selected repeat arrays, grouped by function. Click one to show it alone on the structure.

Color

Repeat classes

Repeat PTMs

Types of structured repeat

Most repeat arrays are folded domains in series (Marcotte et al., 1999). One example of each of the most common types.?UniProt already annotates these, so all are in the Known group. Their copy number is constrained by structure: a WD40 propeller closes with seven blades and EF-hands work in pairs. Types are ranked by how many repeat arrays they have, counting only types whose longest array has three or more copies. The example is the longest array of each type not already used for another tile; the bar shows its copies along the protein. Olduvai copies are coloured by subtype (copies grouped by sequence similarity).

The screen at a glance

Structured contextDisordered contextMixed
Figure 1. Each row is one protein, sorted by length; colored segments are repeat copies. Hover to identify a protein; click to open it.?Segments are colored by the sequence context the model assigned. Proteins longer than 2,500 aa are truncated.
A. Sequence context (per repeat array)
B. Repeat unit length (aa; ranges at midpoint)
C. Copies per repeat array

Method

Gemini Carbon reads the sequences itself, with no tools, code, search or prior knowledge of named proteins. Scripts only select the cohort, blind the sequences and look up coordinates. A repeat array is the set of copies of one repeat in one protein. How other models compare →

1

Cohort

The full human proteome.

2

Blinding

Names and annotations are removed and sequences get shuffled anonymous IDs. The key is kept separately.

3

Reading

Four sequences per prompt: one pass for long structural repeats, then one over disordered stretches for short motifs.?Units of at least 5 aa in at least 3 copies; 2 copies only for long, conserved units.

4

Locating copies

The model quotes each copy exactly. A script finds each quote in the sequence; quotes that are not found are dropped.

5

Unblinding

Identities are attached only afterwards, then results are compared with UniProt features, ELM and AlphaFold models.

Other species

For every species other than human, each proteome is first cut down to its predicted disordered regions, where SLiM-like repeats sit. Removed stretches are replaced by a -{N}- token giving their length, so spacing and full-protein positions are kept.?UniProt reference proteomes are collapsed to one entry per gene, preferring the reviewed record, then the longest. metapredict V3 predicts disordered regions; those of at least 30 aa are kept with 25 aa of flank on each side, and overlapping pieces are merged. Proteins with no such region are skipped. Every quoted copy must sit inside a single kept piece and is mapped back to full-protein coordinates. Run on the human proteome, this keeps 39% of residues and recovers 96% of the disordered or mixed repeat arrays found on full sequences (2,460 of 2,563); most of the rest are coiled-coil heptad arrays that the predictor scores as folded. Yeast keeps 32% of residues, Arabidopsis 30% and Drosophila 42%.

Consensus notation. One symbol per residue position; unit positions in the highlights count these symbols from 1.

W fixed residue[ST] one of thesex any residue(x){4,13} variable loop φ hydrophobic (AVILMFWY)ψ large aliphatic (VILM)Ω aromatic (FWY) + basic (KR)- acidic (DE)o polar (STNQ)

Run it yourself

Open a new session in an empty folder, attach a protein FASTA and paste the box for your app. It writes the instruction file, the analyst prompt and a small script, runs the screen and returns tables of repeat arrays and their copies.?The script blinds the sequences, packs them four to a prompt (at most 2,600 aa), checks that every quoted copy appears verbatim in its sequence, gives copies 1-based full-protein coordinates and unblinds at the end; it never searches for repeats. Each prompt goes to its own analyst with no tools. Proteins over 5,000 aa are read as 3,000 aa windows overlapping by 500. Set MODE to reduced to cut each protein to its predicted disordered regions first, as for the other species (needs metapredict). The FASTA is used as given, so collapse it to one entry per gene first if it holds isoforms.

Paste into a new Claude Code session, as run for Claude Fable 5.2
Set up a blinded protein repeat screen in this folder and run it on the FASTA file I attached.

MODE: full
(Change to "reduced" to cut each protein to its predicted disordered regions first, as for every species except human on the page. Reduced mode needs `pip install metapredict`; if that fails, stop and tell me.)

1. Create each file below with exactly the text between its BEGIN and END lines (not the markers).
2. Save the attached FASTA here as `input.fasta`. If nothing is attached, use the only .fasta/.fa file in this folder; if there is none, stop and ask me for one.
3. Run `python3 screen.py prepare input.fasta` (add `--reduce` if MODE is reduced).
4. Follow CLAUDE.md until the screen is complete, then give me the export summary.

===== BEGIN FILE: CLAUDE.md =====
# Blinded repeat screen (Claude Code)

Proteins in the FASTA are screened for repeat arrays (one repeat's copies within one protein) by reading the sequence, with no tools. Mode is set at `prepare`: `full` reads whole sequences with `prompts/repeat_analyst_v2.txt`; `reduced` (`--reduce`) reads only predicted disordered regions with `prompts/repeat_analyst_v2_reduced.txt`. `cat screen_work/mode.txt` shows which.

## Rules (do not change)
1. **The model reads every sequence itself.** Never write or run code (regex, k-mers, alignment, dotplots, periodicity, HMMs, repeat finders) to find, filter or score repeats. `screen.py` only blinds and packs sequences, checks that each quoted copy appears verbatim, maps copies to coordinates, and unblinds at the end.
2. **Blinding.** Never open `screen_work/.key/`, the input FASTA after `prepare`, or the exported tables while the screen is running. Analysts see only `SEQ_` IDs, lengths and residues.
3. **Fixed prompt and chunk size.** Every chunk is read with the analyst prompt named in Loop step 3, unedited. Chunks hold at most 4 sequences and 2,600 aa; `screen.py` sets this. Only the number of chunks per wave (`--chunks`) may change.
4. **One analyst per chunk, no tools.** Each chunk goes to a fresh analyst that has no tools and sees nothing but that chunk's text. If this environment cannot start isolated analysts, read each chunk yourself under the analyst prompt, one chunk at a time, with no code, and say so in the final summary.
5. **One folder per run.** Use a new, empty folder for each model or proteome.

## Loop
1. `python3 screen.py status`
2. `python3 screen.py next-wave --chunks 8` prints each pending chunk between `=== CHUNK XX ===` lines (it resumes an unfinished wave if there is one). Raise `--chunks` to 16 or 24 if rate limits allow.
3. Send each chunk's text (everything after its `=== CHUNK XX ===` line, up to the next one) to its own analyst, all in parallel. Use the Task tool with `subagent_type: repeat-analyst` for full mode or `repeat-analyst-reduced` for reduced mode, and pass the chunk text as the whole prompt. The analyst's reply is the JSON.
4. Collect the replies into one JSON object keyed by two-digit chunk number, `{"01": [...], "02": [...]}`, and write it to `screen_work/waves/wave_NNN/raw_batch.json`. Keep every reply that came back, even if some analysts failed.
5. `python3 screen.py ingest screen_work/waves/wave_NNN`. Chunks that pass are saved. If a quoted copy is not found verbatim, re-read that chunk's `prompt_XX.txt` by eye (no code), correct the copy in a new `raw_batch.json` holding only that chunk, and ingest again. A wave commits when all its chunks pass.
6. Repeat until `status` reports 100.00%, then run `python3 screen.py export` and report its summary line. Outputs: `proteins.tsv`, `repeat_arrays.tsv`, `repeat_copies.tsv` (1-based full-protein coordinates).

## Settings
Run at medium effort (`.claude/settings.json`). Subagents inherit the session model.
===== END FILE: CLAUDE.md =====

===== BEGIN FILE: .claude/agents/repeat-analyst.md =====
---
name: repeat-analyst
description: Blinded protein repeat analyst for full sequences. No tools; the prompt is one chunk of raw sequence text.
tools: []
model: inherit
---

You are a protein sequence motif and repeat analyst examining blinded amino acid sequence(s).
STRICT ISOLATION RULE:
- Do NOT call any tools (do not read files, search the codebase, or search the web). Analyze ONLY the raw amino acid sequence text provided directly in the prompt.

Analysis guidelines:
- Use ZERO prior knowledge of specific proteins or named domain families; judge strictly from the amino acid sequence provided.
- Perform an explicit TWO-STAGE VISUAL SCAN on every sequence so strong structural repeats never shadow subtle disordered repeats:
  1. Stage 1 (Long & Structural Repeats): Scan the full sequence for longer repeats (15+ aa), tandem arrays, or high-conservation internal duplications.
  2. Stage 2 (Independent Disordered-Region Scan): Independently isolate all disordered-like regions (N/C-terminal tails, long linkers, segments enriched in P,S,E,K,Q,G,D,N,R,T and depleted in bulky hydrophobics) and carefully scan them for short-to-medium repeats (5-15 aa) occurring >=3 times, whether dispersed or tandem!
- Copy number & minimum length rule:
  - Minimum repeat unit length is strictly >=5 aa (never report <=4 aa short repeats).
  - Require >=3 occurrences by default (especially important for 5-15 aa repeats in disordered regions).
  - Report a 2-copy repeat ONLY if it is long (typically >=15 aa) and strongly conserved across many positions so chance occurrence is implausible.
- Spacing: Repeats do NOT need to be tandem or periodic -- dispersed repeats separated by variable linkers are equally important. Record whether spacing is "tandem" (head-to-tail or <=2 aa gap), "periodic" (regular linker length), or "dispersed" (variable spacing).
- Motif quality & low-complexity boundary:
  - Look for convincing multi-position architecture: fixed anchor residues (especially P, G, W, Y, F, C, H, D, E, K, R, L), constrained 2-3 residue choices, and physicochemically conserved positions.
  - Disregard pure unanchored low-complexity / compositional-bias tracts (bare homopolymers like QQQQQQ, PPPPPP, EEEEE, or simple 2-3 letter repeats like GSGSGS, RGG, SRSR with no multi-position consensus).
  - IMPORTANT EXCEPTION: Do NOT dismiss a motif merely because it contains a short proline or polar run (such as PPP or PPPP) IF it is anchored by conserved flanking or internal non-bias positions across >=3 copies (for example, `PPPPGφx[PG]L` or `[ST]Px+xΩ` where specific flanking residues align cleanly by eye).
- Window refinement & non-overlap:
  - Check whether shifting phase or expanding 1-4 residues left/right yields a longer, higher-information consensus across copies.
  - If a protein contains multiple distinct, non-overlapping repeat families (e.g., a structured repeat domain AND a dispersed 6-10mer motif in flanking disorder, or two different IDR motifs), report ALL of them, ordered strongest first. Never report overlapping instances.
- Proactive structural-bias `flags`:
  - Conventional tools easily detect collagen, coiled-coils, and charged helical rods. Whenever a sequence contains a noticeable tract of:
    * `"collagen_gxy"` (repetitive G-x-y triplets),
    * `"coiled_coil_heptad"` (amphipathic alpha-helical heptads with hydrophobic `a,d` register and polar/charged `e,g`), or
    * `"charged_helical_rod"` (extended E/K/R-rich single alpha-helical / charged alternating tracts like EEEKKRREEE...),
    add the corresponding label(s) to `flags`. Do NOT list those generic tracts in `repeats`, and continue scanning the rest of the protein for genuine motif/domain repeats.

Symbol key for `consensus` (1 token = 1 residue position, concatenated with NO separator):
  A..Y  = fixed standard amino acid (note: P is NOT part of φ; treat P as its own fixed anchor or inside [...])
  [XY]  = constrained choice of 2-3 specific amino acids (e.g., [ST], [GP], [KRH])
  φ     = hydrophobic, excluding proline (A,V,I,L,M,F,W,Y)
  ψ     = large aliphatic (V,I,L,M)
  Ω     = aromatic (F,W,Y)
  +     = basic / positively charged (K,R)
  -     = acidic / negatively charged (D,E)
  o     = polar uncharged (S,T,N,Q)
  x     = unconstrained single residue
  (For repeats >=20 aa with minor internal length variation across copies, use `(x){n,m}` only where a variable loop occurs.)

--- OUTPUT SCHEMA (per sequence) ---
{
  "seq_id": "<string: blinded sequence ID provided>",
  "has_repeat": <boolean: true if `repeats` is non-empty, else false>,
  "flags": ["collagen_gxy" | "coiled_coil_heptad" | "charged_helical_rod"],
  "repeats": [
    {
      "consensus": "<string using symbol key above>",
      "unit_length": <integer or "<min>-<max>" if variable-length >=20 aa repeat>,
      "spacing": "tandem" | "periodic" | "dispersed",
      "sequence_context": "disordered_like" | "structured_like" | "mixed",
      "confidence": "high" | "medium",
      "instances": [
        "<exact verbatim uppercase amino acid substring from the input sequence, in N-to-C order>"
      ],
      "rationale": "<concise 1-2 sentence explanation of conserved anchors, physicochemical positions, and spacing/context>"
    }
  ]
}

CRITICAL RULES:
1. Every string in `instances` MUST be an exact, contiguous, un-gapped substring copied verbatim from the input sequence.
2. Output ONLY valid JSON (a single object if 1 sequence is given, or a JSON array of objects if multiple sequences are given) -- no markdown fences, no prose.
===== END FILE: .claude/agents/repeat-analyst.md =====

===== BEGIN FILE: .claude/agents/repeat-analyst-reduced.md =====
---
name: repeat-analyst-reduced
description: Blinded protein repeat analyst for disordered-region sequences with -{N}- spacers. No tools; the prompt is one chunk of raw sequence text.
tools: []
model: inherit
---

You are a protein sequence motif and repeat analyst examining blinded amino acid sequence(s).
STRICT ISOLATION RULE:
- Do NOT call any tools (do not read files, search the codebase, or search the web). Analyze ONLY the raw amino acid sequence text provided directly in the prompt.

Analysis guidelines:
- Use ZERO prior knowledge of specific proteins or named domain families; judge strictly from the amino acid sequence provided.
- Reduced-sequence & `-{N}-` spacer notation:
  - Input sequences have been reduced to predicted intrinsically disordered regions padded by 25-aa boundary flanks, with omitted structured/non-IDR intervals replaced by explicit length tokens of the form `-{N}-` (meaning `N` amino acid residues were excised at that position).
  - Terminal spacers: A leading `-{N}-` means `N` residues were trimmed from the N-terminus (no leading `-{N}-` means the sequence begins at true residue 1); a trailing `-{N}-` means `N` residues were trimmed from the C-terminus (no trailing `-{N}-` means the sequence reaches the true C-terminus).
  - Never treat `-`, `{`, `}`, or digits as amino acids, and never match or span a repeat instance across a `-{N}-` spacer. The 25-aa flanks are present so repeats near disorder boundaries remain intact.
- Perform an explicit TWO-STAGE VISUAL SCAN on every sequence so strong longer repeats never shadow subtle short disordered repeats:
  1. Stage 1 (Long & Boundary Repeats): Scan all retained segments for longer repeats (15+ aa), tandem arrays, or high-conservation internal duplications.
  2. Stage 2 (Independent Disordered-Region Scan): Independently scan all disordered-like segments and N/C-terminal tails (segments enriched in P,S,E,K,Q,G,D,N,R,T and depleted in bulky hydrophobics) for short-to-medium repeats (5-15 aa) occurring >=3 times, whether dispersed or tandem!
- Copy number & minimum length rule:
  - Minimum repeat unit length is strictly >=5 aa (never report <=4 aa short repeats).
  - Require >=3 occurrences by default (especially important for 5-15 aa repeats in disordered regions).
  - Report a 2-copy repeat ONLY if it is long (typically >=15 aa) and strongly conserved across many positions so chance occurrence is implausible.
- Spacing: Repeats do NOT need to be tandem or periodic -- dispersed repeats separated by variable linkers (within one segment or across separate retained segments) are equally important. Record whether spacing is "tandem" (head-to-tail or <=2 aa gap with NO intervening `-{N}-` spacer), "periodic" (regular true inter-copy linker length), or "dispersed" (variable spacing). Whenever a `-{N}-` spacer lies between two copies, add `N` omitted residues to the true inter-copy linker length (so copies separated by `-{N}-` are never "tandem").
- Motif quality & low-complexity boundary:
  - Look for convincing multi-position architecture: fixed anchor residues (especially P, G, W, Y, F, C, H, D, E, K, R, L), constrained 2-3 residue choices, and physicochemically conserved positions.
  - Disregard pure unanchored low-complexity / compositional-bias tracts (bare homopolymers like QQQQQQ, PPPPPP, EEEEE, or simple 2-3 letter repeats like GSGSGS, RGG, SRSR with no multi-position consensus).
  - IMPORTANT EXCEPTION: Do NOT dismiss a motif merely because it contains a short proline or polar run (such as PPP or PPPP) IF it is anchored by conserved flanking or internal non-bias positions across >=3 copies (for example, `PPPPGφx[PG]L` or `[ST]Px+xΩ` where specific flanking residues align cleanly by eye).
- Window refinement & non-overlap:
  - Check whether shifting phase or expanding 1-4 residues left/right within the retained segment yields a longer, higher-information consensus across copies.
  - If a protein contains multiple distinct, non-overlapping repeat families (e.g., a longer boundary repeat AND a dispersed 6-10mer motif in disorder, or two different IDR motifs), report ALL of them, ordered strongest first. Never report overlapping instances.
- Proactive structural-bias `flags`:
  - Conventional tools easily detect collagen, coiled-coils, and charged helical rods. Whenever a sequence contains a noticeable tract of:
    * `"collagen_gxy"` (repetitive G-x-y triplets),
    * `"coiled_coil_heptad"` (amphipathic alpha-helical heptads with hydrophobic `a,d` register and polar/charged `e,g`), or
    * `"charged_helical_rod"` (extended E/K/R-rich single alpha-helical / charged alternating tracts like EEEKKRREEE...),
    add the corresponding label(s) to `flags`. Do NOT list those generic tracts in `repeats`, and continue scanning the rest of the protein for genuine motif/domain repeats.

Symbol key for `consensus` (1 token = 1 residue position, concatenated with NO separator):
  A..Y  = fixed standard amino acid (note: P is NOT part of φ; treat P as its own fixed anchor or inside [...])
  [XY]  = constrained choice of 2-3 specific amino acids (e.g., [ST], [GP], [KRH])
  φ     = hydrophobic, excluding proline (A,V,I,L,M,F,W,Y)
  ψ     = large aliphatic (V,I,L,M)
  Ω     = aromatic (F,W,Y)
  +     = basic / positively charged (K,R)
  -     = acidic / negatively charged (D,E)
  o     = polar uncharged (S,T,N,Q)
  x     = unconstrained single residue
  (For repeats >=20 aa with minor internal length variation across copies, use `(x){n,m}` only where a variable loop occurs.)

--- OUTPUT SCHEMA (per sequence) ---
{
  "seq_id": "<string: blinded sequence ID provided>",
  "has_repeat": <boolean: true if `repeats` is non-empty, else false>,
  "flags": ["collagen_gxy" | "coiled_coil_heptad" | "charged_helical_rod"],
  "repeats": [
    {
      "consensus": "<string using symbol key above>",
      "unit_length": <integer or "<min>-<max>" if variable-length >=20 aa repeat>,
      "spacing": "tandem" | "periodic" | "dispersed",
      "sequence_context": "disordered_like" | "structured_like" | "mixed",
      "confidence": "high" | "medium",
      "instances": [
        "<exact verbatim uppercase amino acid substring from a single retained segment of the input sequence, in N-to-C order>"
      ],
      "rationale": "<concise 1-2 sentence explanation of conserved anchors, physicochemical positions, and spacing/context>"
    }
  ]
}

CRITICAL RULES:
1. Every string in `instances` MUST be an exact, contiguous, un-gapped uppercase amino acid substring (`A-Y` letters only) copied verbatim from within a single retained segment of the input sequence -- NEVER include or span across any `-{N}-` spacer token.
2. Output ONLY valid JSON (a single object if 1 sequence is given, or a JSON array of objects if multiple sequences are given) -- no markdown fences, no prose.
===== END FILE: .claude/agents/repeat-analyst-reduced.md =====

===== BEGIN FILE: .claude/settings.json =====
{
  "effortLevel": "medium"
}
===== END FILE: .claude/settings.json =====

===== BEGIN FILE: screen.py =====
#!/usr/bin/env python3
"""Blinded LLM repeat screen: bookkeeping only.

This script never looks for repeats. It blinds and packs sequences, checks that every
copy the model quotes is a verbatim substring, maps copies to 1-based coordinates,
and unblinds at the end. All repeat calls come from the model reading the sequence.

  python3 screen.py prepare INPUT.fasta [--reduce]   # blind (optionally cut to disordered regions)
  python3 screen.py status
  python3 screen.py next-wave [--chunks 8]           # print the next prompts (=== CHUNK XX ===)
  python3 screen.py ingest screen_work/waves/wave_001  # verify raw_batch.json and commit
  python3 screen.py export                           # unblinded tables, after the screen is done
"""
import argparse, csv, glob, json, os, random, re, sys

W = "screen_work"
KEY = os.path.join(W, ".key", "key.tsv")          # never shown to analysts
BLIND = os.path.join(W, "blinded.tsv")
RESULTS = os.path.join(W, "results.jsonl")
MODE = os.path.join(W, "mode.txt")
SEG_RE = re.compile(r"-\{(\d+)\}-|([A-Z]+)")
UNIT_RE = re.compile(r"-\{\d+\}-|[A-Z]")
AA_RE = re.compile(r"^[A-Z]+$")
MAX_PER_CHUNK, MAX_AA = 4, 2600
WINDOW, OVERLAP, WINDOW_ABOVE = 3000, 500, 5000


# ---------- input ----------
def read_fasta(path):
    recs, hdr, buf = [], None, []
    with open(path) as fh:
        for line in fh:
            line = line.strip()
            if line.startswith(">"):
                if hdr is not None:
                    recs.append((hdr, "".join(buf)))
                hdr, buf = line[1:], []
            elif line:
                buf.append(line)
    if hdr is not None:
        recs.append((hdr, "".join(buf)))
    out = []
    for hdr, seq in recs:
        seq = re.sub(r"[^A-Za-z]", "", seq).upper()
        acc = hdr.split("|")[1] if hdr.count("|") >= 2 else hdr.split()[0]
        if seq:
            out.append((acc, hdr, seq))
    return out


def idr_segments(seq, min_idr=30, flank=25):
    """metapredict V3 disordered regions >= min_idr aa, padded by flank, merged. 1-based inclusive."""
    import metapredict as meta
    doms = meta.predict_disorder_domains(seq).disordered_domain_boundaries
    iv = [(max(1, s + 1 - flank), min(len(seq), e + flank)) for s, e in doms if e - s >= min_idr]
    iv.sort()
    merged = []
    for s, e in iv:
        if merged and s <= merged[-1][1] + 1:
            merged[-1][1] = max(merged[-1][1], e)
        else:
            merged.append([s, e])
    return merged


def reduce_record(seq, segs):
    parts, prev = [], 0
    if segs[0][0] > 1:
        parts.append(f"-{{{segs[0][0] - 1}}}-")
    for s, e in segs:
        if prev:
            parts.append(f"-{{{s - prev - 1}}}-")
        parts.append(seq[s - 1:e])
        prev = e
    if prev < len(seq):
        parts.append(f"-{{{len(seq) - prev}}}-")
    return "".join(parts)


def cmd_prepare(a):
    if os.path.exists(BLIND):
        sys.exit(f"{BLIND} already exists; this folder already holds a screen.")
    recs = read_fasta(a.fasta)
    items, skipped = [], 0
    for acc, hdr, seq in recs:
        if a.reduce:
            segs = idr_segments(seq)
            if not segs:
                skipped += 1
                continue
            items.append(dict(acc=acc, header=hdr, full_length=len(seq), offset=0, seq=reduce_record(seq, segs)))
        elif len(seq) > WINDOW_ABOVE:
            start = 0
            while True:
                items.append(dict(acc=acc, header=hdr, full_length=len(seq), offset=start, seq=seq[start:start + WINDOW]))
                if start + WINDOW >= len(seq):
                    break
                start += WINDOW - OVERLAP
        else:
            items.append(dict(acc=acc, header=hdr, full_length=len(seq), offset=0, seq=seq))
    random.Random(a.seed).shuffle(items)
    width = max(5, len(str(len(items))))
    os.makedirs(os.path.dirname(KEY), exist_ok=True)
    with open(BLIND, "w") as b, open(KEY, "w") as k:
        b.write("seq_id\tsequence\n")
        k.write("seq_id\taccession\tfull_length\toffset\theader\n")
        for i, it in enumerate(items, 1):
            sid = f"SEQ_{i:0{width}d}"
            b.write(f"{sid}\t{it['seq']}\n")
            k.write(f"{sid}\t{it['acc']}\t{it['full_length']}\t{it['offset']}\t{it['header']}\n")
    with open(MODE, "w") as m:
        m.write("reduced\n" if a.reduce else "full\n")
    print(f"{len(recs)} proteins read; {len(items)} blinded sequences written"
          + (f"; {skipped} proteins with no disordered region >=30 aa skipped" if a.reduce else "")
          + f". Mode: {'reduced' if a.reduce else 'full'}. Analyst prompt: "
          + ("prompts/repeat_analyst_v2_reduced.txt" if a.reduce else "prompts/repeat_analyst_v2.txt"))


# ---------- shared ----------
def load_blind():
    with open(BLIND) as fh:
        return {r["seq_id"]: r["sequence"] for r in csv.DictReader(fh, delimiter="\t")}


def load_results():
    done = {}
    if os.path.exists(RESULTS):
        with open(RESULTS) as fh:
            for line in fh:
                if line.strip():
                    r = json.loads(line)
                    done[r["seq_id"]] = r
    return done


def parse_tokens(seq):
    """-> (retained_aa, full_length, [(raw_start0, raw_end0, full_start1)])"""
    full, kept, segs, pos = 1, 0, [], 0
    for m in SEG_RE.finditer(seq):
        if m.start() != pos:
            raise ValueError(f"bad characters at {pos}")
        pos = m.end()
        if m.group(1):
            full += int(m.group(1))
        else:
            segs.append((m.start(), m.end(), full))
            full += len(m.group(2))
            kept += len(m.group(2))
    return kept, full - 1, segs


def locate(seq, instances):
    """Find each quoted copy in N-to-C order; 1-based coordinates in the (full) sequence."""
    _, _, segs = parse_tokens(seq)
    out, cursor = [], 0
    for sub in instances:
        pos = seq.find(sub, cursor)
        note = "in_order"
        if pos == -1:
            pos = seq.find(sub)
            note = "out_of_order_or_duplicate"
        if pos == -1:
            out.append(dict(subsequence=sub, verified=False))
            continue
        start = next(fs + (pos - rs) for rs, re_, fs in segs if rs <= pos < re_)
        out.append(dict(subsequence=sub, verified=True, start=start, end=start + len(sub) - 1, status=note))
        if note == "in_order":
            cursor = pos + len(sub)
    return out


def wrap(seq, width=60):
    lines, cur = [], ""
    for u in UNIT_RE.findall(seq):
        if cur and len(cur) + len(u) > width:
            lines.append(cur)
            cur = ""
        cur += u
    return "\n".join(lines + [cur] if cur else lines)


def waves():
    return sorted(glob.glob(os.path.join(W, "waves", "wave_*")))


def open_wave():
    for d in waves():
        if not os.path.exists(os.path.join(d, "COMMITTED")):
            return d
    return None


def print_pending(d):
    man = json.load(open(os.path.join(d, "manifest.json")))
    n = 0
    for ch in man["chunks"]:
        if not os.path.exists(os.path.join(d, f"output_{ch['chunk']:02d}.json")):
            print(f"=== CHUNK {ch['chunk']:02d} ===")
            print(open(os.path.join(d, f"prompt_{ch['chunk']:02d}.txt")).read())
            n += 1
    print(f"[{n} pending chunk(s) in {d}; save answers to {d}/raw_batch.json, then run: python3 screen.py ingest {d}]")


# ---------- commands ----------
def cmd_status(a):
    seqs, done = load_blind(), load_results()
    pos = sum(1 for r in done.values() if r["has_repeat"])
    print(f"Mode: {open(MODE).read().strip()} | screened {len(done)}/{len(seqs)} "
          f"({100 * len(done) / max(1, len(seqs)):.2f}%) | with a repeat array: {pos}")
    d = open_wave()
    if d:
        print(f"Open wave: {d}")


def cmd_next_wave(a):
    d = open_wave()
    if d:
        print_pending(d)
        return
    seqs, done = load_blind(), load_results()
    pending = [(sid, s) for sid, s in seqs.items() if sid not in done]
    if not pending:
        print("Screen complete (100.00%). Run: python3 screen.py export")
        return
    chunks, cur, cur_aa = [], [], 0
    for sid, s in pending:
        L = parse_tokens(s)[0]
        cap = 1 if L > 2500 else 2 if L > 1200 else MAX_PER_CHUNK
        if cur and (len(cur) >= cap or any(x[2] > 2500 for x in cur)
                    or (any(x[2] > 1200 for x in cur) and len(cur) >= 2) or cur_aa + L > MAX_AA):
            chunks.append(cur)
            cur, cur_aa = [], 0
            if len(chunks) >= a.chunks:
                break
        cur.append((sid, s, L))
        cur_aa += L
        if len(cur) >= cap:
            chunks.append(cur)
            cur, cur_aa = [], 0
            if len(chunks) >= a.chunks:
                break
    if cur and len(chunks) < a.chunks:
        chunks.append(cur)
    d = os.path.join(W, "waves", f"wave_{len(waves()) + 1:03d}")
    os.makedirs(d)
    reduced = open(MODE).read().strip() == "reduced"
    man = {"chunks": []}
    for i, ch in enumerate(chunks, 1):
        blocks = []
        for sid, s, L in ch:
            if reduced:
                kept, full, _ = parse_tokens(s)
                blocks.append(f">{sid} retained_aa={kept} full_length={full}\n{wrap(s)}")
            else:
                blocks.append(f">{sid} length={len(s)}\n{wrap(s)}")
        if len(ch) == 1:
            head = ("Inspect this anonymized protein sequence strictly following your "
                    "system instructions and output a single JSON object:\n\n")
        else:
            head = (f"Inspect these {len(ch)} anonymized protein sequences strictly following your "
                    f"system instructions and output a JSON array of {len(ch)} objects (one per sequence, in order):\n\n")
        with open(os.path.join(d, f"prompt_{i:02d}.txt"), "w") as fh:
            fh.write(head + "\n\n".join(blocks) + "\n")
        man["chunks"].append({"chunk": i, "seq_ids": [x[0] for x in ch]})
    json.dump(man, open(os.path.join(d, "manifest.json"), "w"), indent=1)
    print_pending(d)


def min_unit(u):
    nums = [int(x) for x in re.findall(r"\d+", str(u))]
    return min(nums) if nums else 0


def cmd_ingest(a):
    d = a.wave_dir.rstrip("/")
    man = json.load(open(os.path.join(d, "manifest.json")))
    cmap = {c["chunk"]: c["seq_ids"] for c in man["chunks"]}
    seqs = load_blind()
    errors = []
    bp = os.path.join(d, "raw_batch.json")
    if os.path.exists(bp):
        batch = json.load(open(bp))
        for key, val in batch.items():
            idx = int(re.findall(r"\d+", key)[0])
            if idx not in cmap:
                errors.append(f"chunk {idx:02d} not in this wave")
                continue
            if isinstance(val, str):
                v = val.strip()
                v = re.sub(r"^```(?:json)?\s*|\s*```$", "", v)
                try:
                    val = json.loads(v)
                except Exception as e:
                    errors.append(f"chunk {idx:02d}: invalid JSON ({e})")
                    continue
            items = val if isinstance(val, list) else [val]
            got = [r.get("seq_id") for r in items if isinstance(r, dict)]
            if got != cmap[idx]:
                errors.append(f"chunk {idx:02d}: expected seq_ids {cmap[idx]}, got {got}")
                continue
            bad, clean = [], []
            for rec in items:
                seq, kept = seqs[rec["seq_id"]], []
                for rep in rec.get("repeats", []):
                    inst = [s.strip().upper() for s in rep.get("instances", []) if s.strip()]
                    if not inst:
                        continue
                    nonaa = [s for s in inst if not AA_RE.match(s)]
                    if nonaa:
                        bad += [(rec["seq_id"], s) for s in nonaa]
                        continue
                    if min_unit(rep.get("unit_length", 0)) < 5 or min(map(len, inst)) < 5:
                        continue  # schema floor: units under 5 aa are dropped
                    bad += [(rec["seq_id"], m["subsequence"]) for m in locate(seq, inst) if not m["verified"]]
                    kept.append(dict(rep, instances=inst))
                clean.append(dict(seq_id=rec["seq_id"], has_repeat=bool(kept),
                                  flags=rec.get("flags", []), repeats=kept))
            if bad:
                errors.append(f"chunk {idx:02d}: copies not found verbatim in the sequence: {bad}")
                continue
            json.dump(clean, open(os.path.join(d, f"output_{idx:02d}.json"), "w"), indent=1)
        os.remove(bp)
    have = {int(re.findall(r"\d+", os.path.basename(p))[0]) for p in glob.glob(os.path.join(d, "output_*.json"))}
    missing = sorted(set(cmap) - have)
    if errors:
        sys.exit(f"Saved {len(have)}/{len(cmap)} chunks. Fix and re-ingest only these: {errors}")
    if missing:
        print(f"Partial wave: {len(have)}/{len(cmap)} chunks saved. Missing: {missing}")
        return
    done = load_results()
    n_inst = 0
    for p in sorted(glob.glob(os.path.join(d, "output_*.json"))):
        for rec in json.load(open(p)):
            seq = seqs[rec["seq_id"]]
            for rep in rec["repeats"]:
                rep["verified_instances"] = locate(seq, rep["instances"])
                n_inst += len(rep["instances"])
            rec["source_wave"] = os.path.basename(d)
            done[rec["seq_id"]] = rec
    with open(RESULTS + ".tmp", "w") as out:
        for sid in sorted(done):
            out.write(json.dumps(done[sid]) + "\n")
    os.replace(RESULTS + ".tmp", RESULTS)
    open(os.path.join(d, "COMMITTED"), "w").close()
    print(f"Committed {os.path.basename(d)}: {sum(len(v) for v in cmap.values())} sequences, "
          f"{n_inst} copies verified.")
    cmd_status(a)


def cmd_export(a):
    key = {r["seq_id"]: r for r in csv.DictReader(open(KEY), delimiter="\t")}
    done = load_results()
    if len(done) < len(key):
        print(f"Warning: only {len(done)}/{len(key)} sequences screened.")
    prots, arrays, copies = {}, [], []
    seen = {}  # accession -> set of copy starts already reported (window overlaps)
    for sid in sorted(done, key=lambda s: (key[s]["accession"], int(key[s]["offset"]))):
        rec, k = done[sid], key[sid]
        acc, off = k["accession"], int(k["offset"])
        p = prots.setdefault(acc, dict(accession=acc, full_length=k["full_length"], n_arrays=0,
                                       flags=set(), header=k["header"]))
        p["flags"].update(rec.get("flags", []))
        for rep in rec["repeats"]:
            vi = [m for m in rep["verified_instances"] if m["verified"]]
            starts = {m["start"] + off for m in vi}
            if starts and starts <= seen.setdefault(acc, set()):
                continue  # same array seen in the overlapping window
            seen[acc] |= starts
            p["n_arrays"] += 1
            n = p["n_arrays"]
            arrays.append([acc, n, rep.get("consensus", ""), rep.get("unit_length", ""), rep.get("spacing", ""),
                           rep.get("sequence_context", ""), rep.get("confidence", ""), len(vi),
                           min(starts), max(m["end"] + off for m in vi), rep.get("rationale", "")])
            for j, m in enumerate(vi, 1):
                copies.append([acc, n, j, m["start"] + off, m["end"] + off, m["subsequence"]])
    with open("proteins.tsv", "w") as fh:
        fh.write("accession\tfull_length\thas_repeat\tn_arrays\tflags\theader\n")
        for p in prots.values():
            fh.write(f"{p['accession']}\t{p['full_length']}\t{p['n_arrays'] > 0}\t{p['n_arrays']}\t"
                     f"{','.join(sorted(p['flags']))}\t{p['header']}\n")
    with open("repeat_arrays.tsv", "w") as fh:
        fh.write("accession\tarray\tconsensus\tunit_length\tspacing\tsequence_context\tconfidence\t"
                 "copies\tfirst_start\tlast_end\trationale\n")
        for r in arrays:
            fh.write("\t".join(str(x) for x in r) + "\n")
    with open("repeat_copies.tsv", "w") as fh:
        fh.write("accession\tarray\tcopy\tstart\tend\tsequence\n")
        for r in copies:
            fh.write("\t".join(str(x) for x in r) + "\n")
    print(f"{len(prots)} proteins, {sum(1 for p in prots.values() if p['n_arrays'])} with a repeat array, "
          f"{len(arrays)} arrays, {len(copies)} copies -> proteins.tsv, repeat_arrays.tsv, repeat_copies.tsv")


def main():
    ap = argparse.ArgumentParser()
    sp = ap.add_subparsers(dest="cmd", required=True)
    p = sp.add_parser("prepare"); p.add_argument("fasta"); p.add_argument("--reduce", action="store_true")
    p.add_argument("--seed", type=int, default=1)
    sp.add_parser("status")
    p = sp.add_parser("next-wave"); p.add_argument("--chunks", type=int, default=8)
    p = sp.add_parser("ingest"); p.add_argument("wave_dir")
    sp.add_parser("export")
    a = ap.parse_args()
    {"prepare": cmd_prepare, "status": cmd_status, "next-wave": cmd_next_wave,
     "ingest": cmd_ingest, "export": cmd_export}[a.cmd](a)


if __name__ == "__main__":
    main()
===== END FILE: screen.py =====

Catalog

Every protein with at least one repeat array. Search by gene, protein name or consensus; click a row to open it in the explorer.

GeneProteinLengthRepeat arrays (consensus, copies)
Loading catalog…

References

  • Buratowski S. The CTD code. Nat Struct Biol 2003;10:679–680. doi:10.1038/nsb0903-679
  • Frey S, Richter RP, Görlich D. FG-rich repeats of nuclear pore proteins form a three-dimensional meshwork with hydrogel-like properties. Science 2006;314:815–817. doi:10.1126/science.1132516
  • Jorda J, Xue B, Uversky VN, Kajava AV. Protein tandem repeats – the more perfect, the less structured. FEBS J 2010;277:2673–2682. doi:10.1111/j.1742-464X.2010.07684.x
  • Kim HS, Lyons KM, Saitoh E, Azen EA, Smithies O, Maeda N. The structure and evolution of the human salivary proline-rich protein gene family. Mamm Genome 1993;4:3–14. doi:10.1007/BF00364656
  • Li P, et al. Phase transitions in the assembly of multivalent signalling proteins. Nature 2012;483:336–340. doi:10.1038/nature10879
  • Marcotte EM, Pellegrini M, Yeates TO, Eisenberg D. A census of protein repeats. J Mol Biol 1999;293:151–160. doi:10.1006/jmbi.1999.3136
  • Simon M, Hancock JM. Tandem and cryptic amino acid repeats accumulate in disordered regions of proteins. Genome Biol 2009;10:R59. doi:10.1186/gb-2009-10-6-r59
  • Su X, et al. Phase separation of signaling molecules promotes T cell receptor signal transduction. Science 2016;352:595–599. doi:10.1126/science.aad9964
  • Tompa P. Intrinsically unstructured proteins evolve by repeat expansion. BioEssays 2003;25:847–855. doi:10.1002/bies.10324
  • Van Roey K, et al. Short linear motifs: ubiquitous and functionally diverse protein interaction modules directing cell regulation. Chem Rev 2014;114:6733–6778. doi:10.1021/cr400585q

Citation

Please get in touch before citing.

@misc{mcwhite_repeats_preview,
  title  = {A blinded language-model screen for repeats in human proteins},
  author = {{McWhite Lab}},
  year   = {2026},
  note   = {Research preview},
  url    = {https://clairemcwhite.github.io/repeats/highlights.html}
}