Dataset: GFP sequences and brightness
We will use the GFP measurements from Sarkisyan et al. (2016). The data and reference sequence are available on Figshare. In the experiment, the researchers made many GFP variants and measured how brightly they fluoresced.
The file amino_acid_genotypes_to_brightness.tsv groups measurements by amino acid genotype. A barcode is a short DNA identifier used to track a GFP variant; several barcodes can represent the same amino acid sequence.
| Column | Meaning |
|---|
aaMutations | Substitutions relative to the reference; empty for wild type. |
uniqueBarcodes | Number of barcodes representing the genotype. |
medianBrightness | Median log-brightness across these barcodes. |
std | Standard deviation of log-brightness; empty when there is only one barcode. |
Reading the mutation notation
Positions in aaMutations are zero-based amino acid indices, just like Python string indices. For example, SA108D means “replace alanine (A) at index 108 with aspartate (D).” The first letter, S, denotes a substitution. A colon separates mutations, so SA108D:SN144D describes a sequence with two changes relative to the reference.
Loading the reference sequence
The file avGFP_reference_sequence.fa contains the nucleotide coding sequence. Translate it to get the 237-residue reference used by the mutation strings, excluding its terminal stop codon. Here is how to do this with Biopython (pip install biopython).
from pathlib import Path
from urllib.request import urlretrieve
from Bio.Seq import Seq
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
files = {
"amino_acid_genotypes_to_brightness.tsv":
"https://ndownloader.figshare.com/files/4820647",
"avGFP_reference_sequence.fa":
"https://ndownloader.figshare.com/files/4820653",
}
for name, url in files.items():
if not Path(name).exists():
urlretrieve(url, name)
# Read the DNA bases, leaving out the FASTA header.
dna = "".join(line.strip() for line in
Path("avGFP_reference_sequence.fa").read_text().splitlines()
if not line.startswith(">"))
# Translate DNA into amino acids and remove the terminal stop symbol.
translated = str(Seq(dna).translate())
assert translated.endswith("*")
WT = translated[:-1]
L = len(WT)
print("Reference length:", L)
print("Reference protein:", WT)
The code below reads each genotype and applies its substitutions to the reference. Genotypes containing a stop codon (*) are left out so that all starting proteins have the same length.
AA = "ACDEFGHIKLMNPQRSTVWY"
df = pd.read_csv("amino_acid_genotypes_to_brightness.tsv",
sep="\t", keep_default_na=False)
def parse_mutations(text):
mutations = []
for token in text.split(":") if text else []:
match = re.fullmatch(r"S([A-Z])(\d+)([A-Z*])", token)
if match is None:
raise ValueError(f"Unexpected mutation: {token}")
old, position, new = match.groups()
position = int(position)
assert 0 <= position < L and WT[position] == old
mutations.append((position, new))
return mutations
parsed = [parse_mutations(text) for text in df["aaMutations"]]
keep = [not any(new == "*" for j, new in muts) for muts in parsed]
data = df.loc[keep].copy().reset_index(drop=True)
mutations = [muts for muts, ok in zip(parsed, keep) if ok]
F = data["medianBrightness"].to_numpy(dtype=float)
F_WT = float(F[data["aaMutations"].eq("").to_numpy()][0])
def apply_mutations(muts):
residues = list(WT)
for j, new in muts:
residues[j] = new
return "".join(residues)
sequences = [apply_mutations(muts) for muts in mutations]
Direct downloads: GFP genotypes and brightness · reference coding sequence.
A simple fitness oracle
A genetic algorithm needs a score for each candidate it creates. Some candidates will be new combinations of mutations, so we cannot simply look up their brightness in the data. We will use a function called a fitness oracle to estimate their brightness.
In research, this function might be a deep neural network trained to predict a protein property, or a structure-based calculation with software such as Rosetta. For this exercise, we will use a much simpler rule: add the measured effects of individual substitutions.
Suppose the reference has log-brightness FWT, and a sequence with just one substitution at position j has measured log-brightness Fj,a. We estimate the effect of that substitution as Δj,a = Fj,a − FWT. For a candidate with several substitutions, our estimate is:
F̂(s) = FWT + ∑j : sj ≠ WTj Δj,sj.
For example, if two substitutions individually change log-brightness by −0.2 and +0.1, we predict a total change of −0.1 when they occur together. This assumes their effects add. It does not capture interactions between substitutions, called epistasis.
Some possible single substitutions were not measured. For these, we use the median measured single-substitution effect at that position. If the position has no single-substitution measurements, we use the median effect across all measured single substitutions.
Finally, we cap predictions at the smallest and largest log-brightness values in the dataset. This keeps the sum from producing implausibly large or small values. These rules define a simple teaching model built from the experimental measurements. The data are already logarithmic, so we do not take another logarithm.
The complete oracle is provided below. Run it before starting the exercises. You do not need to modify this code. You can use it directly to calculate fitness.
# Effects measured in genotypes with exactly one substitution.
single_effects = {
muts[0]: F[i] - F_WT
for i, muts in enumerate(mutations) if len(muts) == 1
}
global_default = float(np.median(list(single_effects.values())))
site_defaults = {}
for j in range(L):
observed = [effect for (position, new), effect in single_effects.items()
if position == j]
site_defaults[j] = (float(np.median(observed)) if observed
else global_default)
F_min, F_max = float(F.min()), float(F.max())
def oracle(sequence):
"""Estimate log-brightness by adding single-substitution effects."""
if len(sequence) != L or any(a not in AA for a in sequence):
raise ValueError("Use a full-length amino acid sequence.")
predicted = F_WT
for j, amino_acid in enumerate(sequence):
if amino_acid != WT[j]:
predicted += single_effects.get((j, amino_acid), site_defaults[j])
return float(np.clip(predicted, F_min, F_max))
# Start from WT and 39 measured sequences with 1-3 substitutions.
starting_pool = np.array([i for i, muts in enumerate(mutations)
if 1 <= len(muts) <= 3])
def starting_population(seed):
rng = np.random.default_rng(seed)
chosen = rng.choice(starting_pool, 39, replace=False)
population = [WT] + [sequences[i] for i in chosen]
measured = np.array([F_WT] + [F[i] for i in chosen])
return population, measured, rng
initial_population, starting_measured_F, rng = starting_population(0)
print("Measured WT log-brightness:", F_WT)
print("Oracle WT log-brightness:", oracle(WT))
All students
Problem 1: inspect your starting proteins
- Load the dataset and generate the starting population using the supplied code. Plot a histogram of the measured log-brightness of these 40 sequences. Label the horizontal axis “Measured log-brightness, F” and the vertical axis “Number of starting sequences.”
- Provide the full 237-residue wild-type GFP reference sequence used by the dataset.
Problem 2: build the genetic operators
Work with full 237-residue strings. Selection, crossover, and mutation can generate combinations not present in the measurements.
Selection
Implement tournament selection: sample k distinct population indices and return the sequence with the largest predicted log-brightness among them. Use the scores already computed for the population. Select the two parents independently.
def select_parent(population, fitness, rng, k=3):
# TODO: sample k distinct indices, find the highest-scoring one,
# and return its sequence.
raise NotImplementedError
Crossover
Choose a cut uniformly from 1 through L − 1. Combine the prefix of parent 1 with the suffix of parent 2. Preserve sequence length; the parents are aligned to the same reference.
def crossover(parent1, parent2, rng):
# TODO: choose cut = rng.integers(1, L).
# TODO: return parent1[:cut] followed by parent2[cut:].
raise NotImplementedError
Mutation anywhere in the protein
Independently attempt a substitution at each position with probability pmut. If a substitution occurs, choose uniformly from the 19 standard amino acids other than the current one. Any of the L positions may change. A replacement may return a previously mutated site to its reference residue.
def mutate(sequence, rng, p_mut=None):
if p_mut is None:
p_mut = 1.0 / L
residues = list(sequence)
for j, old in enumerate(residues):
# TODO: draw a random number to decide whether this site changes.
# TODO: if it changes, sample from the 19 alternatives.
pass
# TODO: return the new string.
raise NotImplementedError
- Implement each operator and explain its role in directed evolution.
- Check that crossover and mutation preserve length and the alphabet. Verify that pmut = 0 changes no sites and pmut = 1 changes every site.
- Show five example children, their substitution lists relative to wild type, and their predicted log-brightness.
- Explain how crossover between two parents with high predicted brightness could produce a child with lower predicted brightness. Consider what happens when the child inherits substitutions from both parents.
Problem 3: evolve a brighter GFP population
Combine the operators with the supplied oracle. Use these settings for your first experiments.
| Setting | Value |
|---|
| Population size | 40 |
| Generations | 100, plus generation 0 |
| Tournament size | 3 |
| Crossover probability | 0.8 per child |
| Mutation probability | 1/L per position (one expected substitution per child) |
| Elitism | Copy the best 2 population members unchanged |
| Independent runs | Seeds 0, 1, and 2 |
Duplicates are allowed. Evaluate all population members, including generation 0, and retain the best sequence encountered across the entire run.
def run_ga(initial_population, rng, generations=100,
p_cross=0.8, p_mut=None):
if p_mut is None:
p_mut = 1.0 / L
population = list(initial_population)
N = len(population)
best_sequence, best_F = None, -np.inf
history = []
queries = 0
for generation in range(generations + 1):
fitness = np.array([oracle(s) for s in population])
queries += N
# TODO: update best_sequence, best_F, and its discovery generation.
# TODO: record generation, mean fitness, generation maximum,
# best-so-far fitness, unique sequence count, and queries.
if generation == generations:
break
# TODO: copy the best two members into next_population.
next_population = ...
while len(next_population) < N:
parent1 = select_parent(population, fitness, rng)
parent2 = select_parent(population, fitness, rng)
# TODO: crossover with probability p_cross; otherwise copy parent1.
child = ...
child = mutate(child, rng, p_mut)
next_population.append(child)
population = next_population
return best_sequence, best_F, pd.DataFrame(history)
- Complete the loop. For each seed, call
population, measured, rng = starting_population(seed), then pass that population and generator to your search. - Plot average predicted log-brightness of the population versus generation for each run. Also plot the generation maximum and best-so-far fitness. Include generation 0 and the wild-type oracle value as a horizontal reference line. Label the vertical axis “Predicted log-brightness, F̂.”
- Plot the number of unique sequences versus generation. Also track the mean number of substitutions per sequence relative to WT. Does brightness improvement coincide with decreasing diversity or increasing sequence divergence?
- For each run, return the best full protein sequence as a FASTA entry, its predicted log-brightness, its zero-based substitution list (for example,
SA108D), and the generation when it was first found. Identify the overall best design.
Count every oracle call made by the search, including repeated sequences; exclude data preparation and validation queries. If you cache predictions, retain this logical query count for comparing algorithms.
Problem 4: mutation rate and model limitations
- Repeat the genetic algorithm with pmut = 0.25/L and 3/L. Compare these with 1/L using the same three seeds and starting populations. Report the expected number of substitutions introduced per child under each setting.
- Summarize final mean predicted log-brightness, best-so-far fitness, and final sequence diversity. Plot best-so-far fitness versus generation for the three mutation rates.
- Explain why predictions may be unreliable when many substitutions are combined, especially when estimated effects for unmeasured single substitutions are used. Why might the combined effect of two substitutions differ from the sum of their individual effects? Identify one other property that would matter when selecting a protein for experimental testing.
Graduate students only
Problem 5: GFP design with MCMC
Complete Problems 1–4, then use Metropolis–Hastings to search for brighter GFP sequences. Use the same oracle as in your genetic algorithm.
For each standard-amino-acid sequence of length L, define the target distribution:
πT(s) ∝ exp[F̂(s)/T], T > 0.
T is an algorithmic temperature in score units, not a physical temperature. Keep T fixed within a run. A proposal chooses one of the L positions uniformly and replaces its current residue uniformly with one of the 19 alternatives. The forward and reverse probabilities both equal 1/(19L), so the proposal is symmetric. The acceptance probability is:
α(s → s′) = min{1, exp([F̂(s′) − F̂(s)]/T)}.
Accept improvements and allow some decreases. Make the decision in log space by comparing ln(u) with min{0, [F̂(s′) − F̂(s)]/T}, where u is uniform on (0, 1). Every valid proposal has an oracle score, including sequences with no experimental measurement.
def propose_one_mutation(sequence, rng):
# TODO: choose one position uniformly from 0, ..., L-1.
# TODO: choose one of the 19 different residues and return the proposal.
raise NotImplementedError
def accept_move(current_F, proposed_F, T, rng):
# TODO: calculate log_alpha and compare it with log(u).
# Use u = max(rng.random(), np.finfo(float).tiny).
raise NotImplementedError
def run_mcmc(start_sequence, rng, T=0.2, steps=8000):
current = start_sequence
current_F = oracle(current)
queries = 1
best_sequence, best_F = current, current_F
accepted = 0
history = []
# TODO: record iteration 0, current_F, best_F, and queries.
for iteration in range(1, steps + 1):
proposed = propose_one_mutation(current, rng)
proposed_F = oracle(proposed)
queries += 1
# TODO: call accept_move; update current and current_F if accepted.
# TODO: update accepted and the best-sequence record.
# TODO: record every iteration, including unchanged states after rejection.
return best_sequence, best_F, pd.DataFrame(history), accepted / steps
- Implement the proposal and acceptance functions. Derive the acceptance rule from πT(s′)/πT(s), and explain why the normalizing constant cancels.
- Run 8,000 proposals at T = 0.05, 0.2, and 1.0 with seeds 0, 1, and 2. For each seed, recreate its starting population with
starting_population(seed) and start the chain from population[1]. Use the returned generator for the chain. - Plot current predicted log-brightness, best-so-far fitness, and a trailing 200-state mean versus iteration. Include repeated states after rejection. Explain how this mean differs from a population mean.
- Report each chain's acceptance rate, best full sequence as FASTA, predicted log-brightness, zero-based substitution list, and first discovery iteration. Also report how many substitutions in the best sequence lack a measured single-mutant effect. Identify the best MCMC design overall.
- Compare temperatures and explain how accepting a temporarily worse sequence can help exploration. Check that equal scores and higher scores are always accepted. At T = 0.2, a score decrease of 0.2 should be accepted with probability exp(−1) ≈ 0.368.
- Compare MCMC at T = 0.2 with the default genetic algorithm using best-so-far fitness versus cumulative oracle calls. Truncate each paired run to the smaller query budget. Report the initial scores and account for the different population and single-chain starting conditions.
Problem 6: a pretrained structure oracle
Use a pretrained ESMFold model to predict structures for three full-length sequences: the dataset's GFP reference, your best genetic algorithm design, and your best MCMC design. Run an existing hosted notebook or an available GPU environment; do not train or fine-tune a model.
ESMFold maps a protein sequence to predicted atomic coordinates using protein language-model representations and a structure prediction module. Its per-residue pLDDT describes confidence in local structure. This is a structural confidence score, not a fluorescence prediction or a measurement of stability or ΔΔG.
- Record the model/version and prediction settings. Report mean per-residue pLDDT for each sequence, averaging once per residue, such as over Cα atoms. Display the three predicted structures.
- Compare structural confidence with your oracle's brightness predictions. Does a high predicted brightness guarantee a confident structure? Does structural confidence establish that a protein will fluoresce?
- If a structural score were included in the search objective, explain which part of your algorithm would change and why the proposal and acceptance framework could remain the same.
Include these predictions and analysis with your graduate submission.