Simulating a Plant Breeding Program
Chris Gaynor
2026-12-01
Source:vignettes/articles/SimulatePlantBreedingProgram.Rmd
SimulatePlantBreedingProgram.RmdThis article will briefly outline a strategy for writing plant breeding program simulations in AlphaSimR using a very simple clonal breeding program as an example. This example will model the breeding program for 20 years. The example will also generate plots to show the change in mean genetic value and genetic variance over time for the first stage of the breeding program.
Complete code for the simulation is provided after step 6. The steps in-between demonstrate the process used to write this code. Note that some intermediate steps provide invalid code, so you shouldn’t run code for the intermediate steps. Only run the final, complete code.
Step 7 then extends the simulation into the form most simulation studies take: a burn-in period, alternative scenarios run in the years after it, and replicates, with the results collected for comparison.
1. Translate program description to code
Begin by translating a description of the breeding program directly into AlphaSimR code. Don’t worry about whether or not the code runs just yet and instead focus on making sure that the code is faithful representation of the breeding program’s description. This code will be used later when you write code that will actually run.
Breeding program description by year
Year 1 (Crossing)
Make 100 bi-parental crosses at random using all clones from Stage 2 and Stage 3 yield trials as parents. The total number of parents will be 60.
Year 3 (Stage 1)
Clonally propagate all seedlings for Stage 1 testing. Stage 1 testing is performed using a single plot per clone and has a residual error variance of 4.
Description as code
# Year 1 (Crossing)
Parents = c(Stage2, Stage3)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
# Year 2 (Seedlings)
Seedlings = F1
# Year 3 (Stage 1)
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 4 (Stage 2)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 5 (Stage 3)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)2. Create founder haplotypes
This will be your first piece of executable code. I suggest using the founder haplotypes to represent your initial parents, so you will need 60 individuals.
founderPop = runMacs(nInd=60, nChr=4, segSites=1000)3. Set simulation parameters
We will only add a single trait to this simulation. The mean and variance of this trait will represent the mean and variance of the initial parents. Since there is no selection between crossing the parents and growing Stage 1 clones, these values will also approximately equal the mean and variance of the initial Stage 1 clones.
SP = SimParam$
new(founderPop)$
addTraitA(1000)4. Fill breeding program pipeline
The purpose of this stage is to place unique individuals in every stage of the breeding program. We don’t want the exact same individuals to be in multiple stages of the breeding program at the same time. We will generate all individuals from the initial parents, so they won’t have the generational differences we’d expect in a real breeding program. This generational difference will be created later in the simulation as future years are simulated.
Parents = newPop(founderPop)
# Year 5 (Stage 3)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 3 (Stage 1)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 2 (Seedlings)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
# Year 1 (Crossing)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)5. Simulate 20 years of breeding
This part of the script will model the breeding program in action. Thus, you need to advance material as it would be advanced in a real breeding program. This means you need to be careful not to delete or overwrite a population you need later. The most efficient way of doing this is usually to start at the final stage of the breeding program and work your way toward earlier stages, because this often lets you avoid making copies of populations.
for(year in 1:20){
# Year 5 (Stage 3)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 3 (Stage 1)
Stage1 = setPheno(Seedlings, varE=4)
# Year 2 (Seedlings)
Seedlings = F1
# Year 1 (Crossing)
Parents = c(Stage3, Stage2)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
}6. Report results
I like to write code for reporting results at the end, but the code itself often needs to occur within code you’ve already written. This is the case in this simulation, because we are overwriting populations in each new year. Thus, we must save summary data in each year.
First, we need to create a couple of vectors for storing the summary data. This code needs to occur before simulating the 20 years of breeding.
Then, the code for reporting the results needs to occur inside the loop for simulating 20 years of breeding.
for(year in 1:20){
# Code for advancing one year
# Report mean and variance
meanStage1[year] = meanG(Stage1)
varStage1[year] = varG(Stage1)
}Finally, here is the code for generating plots of the summary data. This code occurs after the simulation is complete.
Full Code
library(AlphaSimR)
## Create founder haplotypes
founderPop = runMacs(nInd=60, nChr=4, segSites=1000)
## Set simulation parameters
SP = SimParam$
new(founderPop)$
addTraitA(1000)
## Fill breeding program pipeline
Parents = newPop(founderPop)
# Year 5 (Stage 3)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 3 (Stage 1)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 2 (Seedlings)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
# Year 1 (Crossing)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
## Create vectors for output
meanStage1 = numeric(20)
varStage1 = numeric(20)
## Simulate 20 years of breeding
for(year in 1:20){
# Year 5 (Stage 3)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 3 (Stage 1)
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 2 (Seedlings)
Seedlings = F1
# Year 1 (Crossing)
Parents = c(Stage3, Stage2)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
# Report mean and variance
meanStage1[year] = meanG(Stage1)
varStage1[year] = varG(Stage1)
}
## Plot mean and variance
plot(1:20, meanStage1, type="l", xlab="Year", ylab="Mean", main="Mean Stage 1")
plot(1:20, varStage1, type="l", xlab="Year", ylab="Variance", main="Variance Stage 1")
7. Compare scenarios with a burn-in and replicates
A single run of a breeding program tells you little on its own. The usual purpose of a simulation is to compare alternative versions of a program, and that comparison needs three things the code above does not have.
- A burn-in: a period of breeding under the current
program before the alternatives begin. The founders produced by
runMacshave never been selected, so the first years of any program are atypical. The burn-in puts the program into a realistic state before the scenarios start to differ. - Scenarios: the alternative programs being compared, each run forward for a number of future years from the end of the burn-in.
- Replicates: independent repeats of the whole process, each with new founders and a new burn-in. A simulation is a random draw, so a difference between scenarios means nothing until you know how much it varies between replicates.
The burn-in is shared: within a replicate, it is run once, and every scenario starts from the state it ends in. The scenarios in a replicate therefore start from the same founders and the same breeding program, so a difference between them comes from the scenarios themselves rather than from differences in their starting points.
As an example, we will compare the program above with an alternative that uses the same number of plots each year. The current program tests 1000 Stage 1 clones in one plot each, 50 Stage 2 clones in four plots each and 10 Stage 3 clones in eight plots each, for 1280 plots. The alternative makes 80 crosses instead of 100, giving 800 Stage 1 clones, and spends the 200 plots this saves on testing Stage 2 clones in eight plots each instead of four. It trades selection intensity in Stage 1 for accuracy in Stage 2. Keeping the number of plots equal is what makes this a fair comparison: an alternative that simply tested more material would win by spending more.
Run the burn-in and save it
The code below follows the layout used in the example simulations that accompany Bančič et al. (2025), Plant breeding simulations with AlphaSimR. The work is split in two. The burn-in is run first: each replicate creates new founders, fills the pipeline as in step 4, runs 10 years under the current program, and saves the state of the simulation at the end to a file of its own. Each scenario then loads those files, one replicate at a time, and runs 10 future years under its own program. Both loops over years advance the stages exactly as the loop in step 5 does, and the only difference between them is the number of crosses and the number of Stage 2 plots.
Keeping the burn-in in files means it is run only once, however many scenarios use it. The scenarios can be run as separate jobs, in separate R sessions or on a computing cluster, and a scenario added later starts from the same burn-in without repeating it.
First, choose a folder for the files. In a real study, this is
usually the working folder, so simDir could simply be
".", or another folder set aside for the study. This
article uses a temporary folder, which R deletes when the session
ends.
## Folder for the burn-in and results files
simDir = file.path(tempdir(), "BreedingSim")
dir.create(simDir, showWarnings=FALSE)The burn-in results for each year are stored in a data frame called
burninOutput, with one row per year. At the end of the
burn-in, save writes this data frame, every population
still in the pipeline and SP to a file named for the
replicate, such as BurnIn_1.RData. Naming the objects to
save keeps the file small; save.image would also work, but
it saves everything in the workspace, including populations no longer
needed.
library(AlphaSimR)
set.seed(1234)
## Global parameters
nReps = 10
nBurnin = 10
nFuture = 10
nCycles = nBurnin + nFuture
for(REP in 1:nReps){
## Data frame for this replicate's burn-in results
burninOutput = data.frame(year = 1:nBurnin,
rep = REP,
meanStage1 = numeric(nBurnin),
varStage1 = numeric(nBurnin),
meanStage3 = numeric(nBurnin))
## Create founder haplotypes
founderPop = runMacs(nInd=60, nChr=4, segSites=1000)
## Set simulation parameters
SP = SimParam$
new(founderPop)$
addTraitA(1000)
## Fill breeding program pipeline
Parents = newPop(founderPop)
# Year 5 (Stage 3)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 3 (Stage 1)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 2 (Seedlings)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
Seedlings = F1
# Year 1 (Crossing)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
## Burn-in years under the current program
for(year in 1:nBurnin){
# Year 5 (Stage 3)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=4, varE=4)
# Year 3 (Stage 1)
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 2 (Seedlings)
Seedlings = F1
# Year 1 (Crossing)
Parents = c(Stage3, Stage2)
F1 = randCross(Parents, nCrosses=100, nProgeny=10)
# Report mean and variance
burninOutput$meanStage1[year] = meanG(Stage1)
burninOutput$varStage1[year] = varG(Stage1)
burninOutput$meanStage3[year] = meanG(Stage3)
}
## Save the state at the end of the burn-in
save(SP, F1, Seedlings, Stage1, Stage2, Stage3, burninOutput,
file=file.path(simDir, paste0("BurnIn_", REP, ".RData")))
}
list.files(simDir)
#> [1] "BurnIn_1.RData" "BurnIn_10.RData" "BurnIn_2.RData" "BurnIn_3.RData"
#> [5] "BurnIn_4.RData" "BurnIn_5.RData" "BurnIn_6.RData" "BurnIn_7.RData"
#> [9] "BurnIn_8.RData" "BurnIn_9.RData"Run the scenarios from the saved burn-in
Each scenario loads the burn-in file for a replicate with
load, which puts the saved objects back into the workspace
under their saved names, replacing any objects of the same name. The
scenario then runs the future years and records them in a data frame
called output, which starts with the replicate’s burn-in
results. When every replicate is done, the scenario saves its results to
a file of its own with saveRDS.
Loading a file also gives each scenario its own copy of
SP. That matters because SimParam is an R6
object, which is not copied when it is assigned: a scenario that changed
SP, even only by moving on its count of individuals, would
otherwise change it for every scenario after it. If you keep the state
in memory instead of in a file, copy it with
SP$clone(deep=TRUE) before each scenario.
In a real study, each scenario usually has a script of its own, so that the scenarios can run as separate jobs. Here, each pass of the loop over scenarios does what one such script would do.
for(scenarioName in c("Current", "Alternative")){
## Settings used in the future years
if(scenarioName == "Current"){
nCrosses = 100
nRepStage2 = 4
}else{
nCrosses = 80
nRepStage2 = 8
}
results = list()
for(REP in 1:nReps){
## Load the state at the end of this replicate's burn-in
load(file.path(simDir, paste0("BurnIn_", REP, ".RData")))
## Data frame for this replicate's results, starting with the burn-in
output = data.frame(year = 1:nCycles,
rep = REP,
scenario = scenarioName,
meanStage1 = numeric(nCycles),
varStage1 = numeric(nCycles),
meanStage3 = numeric(nCycles))
output$meanStage1[1:nBurnin] = burninOutput$meanStage1
output$varStage1[1:nBurnin] = burninOutput$varStage1
output$meanStage3[1:nBurnin] = burninOutput$meanStage3
## Future years under the scenario's program
for(year in (nBurnin+1):nCycles){
# Year 5 (Stage 3)
Stage3 = selectInd(Stage2, nInd=10)
Stage3 = setPheno(Stage3, reps=8, varE=4)
# Year 4 (Stage 2)
Stage2 = selectInd(Stage1, nInd=50)
Stage2 = setPheno(Stage2, reps=nRepStage2, varE=4)
# Year 3 (Stage 1)
Stage1 = setPheno(Seedlings, reps=1, varE=4)
# Year 2 (Seedlings)
Seedlings = F1
# Year 1 (Crossing)
Parents = c(Stage3, Stage2)
F1 = randCross(Parents, nCrosses=nCrosses, nProgeny=10)
# Report mean and variance
output$meanStage1[year] = meanG(Stage1)
output$varStage1[year] = varG(Stage1)
output$meanStage3[year] = meanG(Stage3)
}
## Save this replicate's results
results = append(results, list(output))
}
## Save this scenario's results
results = do.call(rbind, results)
saveRDS(results, file.path(simDir, paste0(scenarioName, ".rds")))
}In the companion code for the paper, the pieces of this code are also
split into scripts that are run with source, as described
under Miscellaneous comments below: the global parameters, the creation
of founders, the filling of the pipeline and the advancing of one year
each have a script, so the burn-in and the future years call the same
code for advancing a year.
Summarize the results
Once every scenario has finished, read their results files and combine them into one data frame.
results = do.call(rbind, lapply(c("Current", "Alternative"), function(s)
readRDS(file.path(simDir, paste0(s, ".rds")))))
head(results)
#> year rep scenario meanStage1 varStage1 meanStage3
#> 1 1 1 Current -0.09274229 1.0624931 1.183718
#> 2 2 1 Current -0.02655426 0.8474687 1.318144
#> 3 3 1 Current 0.91732504 0.6363464 1.562563
#> 4 4 1 Current 0.99483335 0.8068788 1.337990
#> 5 5 1 Current 0.90321451 0.8085924 2.247885
#> 6 6 1 Current 1.68286422 0.7582465 2.156072Before plotting, put every replicate on the same footing. Number the years from the end of the burn-in, so that its last year is year 0 and the future years are 1 to 10, and subtract each replicate’s mean in year 0 from its means in every year, so that every replicate starts the future years at zero. The plots then show the change from the end of the burn-in. The replicates are blocks in the design of this experiment: each has its own founders and burn-in, and its scenarios share them. Removing each block’s starting level removes the differences between replicates in where they start, which would otherwise blur the difference between the scenarios. The variance is left as it is.
## Number the years from the last year of the burn-in
results$year = results$year - nBurnin
## Subtract each replicate's mean in year 0
base = results[results$year == 0, ]
i = match(paste(results$scenario, results$rep),
paste(base$scenario, base$rep))
results$meanStage1 = results$meanStage1 - base$meanStage1[i]
results$meanStage3 = results$meanStage3 - base$meanStage3[i]Average the replicates within each scenario and year, and plot the mean of genetic values in Stage 1 and Stage 3 and the variance of genetic values in Stage 1 over the future years. The two scenarios share the burn-in, so they start from the same point in year 0.
avg = aggregate(cbind(meanStage1, varStage1, meanStage3) ~ scenario + year,
data=results[results$year >= 0, ], FUN=mean)
plot(meanStage1 ~ year, data=avg[avg$scenario == "Current", ],
type="l", ylim=range(avg$meanStage1), xlab="Year",
ylab="Change in mean", main="Mean Stage 1")
lines(meanStage1 ~ year, data=avg[avg$scenario == "Alternative", ], lty=2)
legend("topleft", legend=c("Current", "Alternative"), lty=1:2)
plot(meanStage3 ~ year, data=avg[avg$scenario == "Current", ],
type="l", ylim=range(avg$meanStage3), xlab="Year",
ylab="Change in mean", main="Mean Stage 3")
lines(meanStage3 ~ year, data=avg[avg$scenario == "Alternative", ], lty=2)
legend("topleft", legend=c("Current", "Alternative"), lty=1:2)
plot(varStage1 ~ year, data=avg[avg$scenario == "Current", ],
type="l", ylim=range(avg$varStage1), xlab="Year", ylab="Variance",
main="Variance Stage 1")
lines(varStage1 ~ year, data=avg[avg$scenario == "Alternative", ], lty=2)
legend("topright", legend=c("Current", "Alternative"), lty=1:2)
The two stages respond differently. The alternative’s advantage is a more accurate Stage 2 trial, and that decides directly which clones reach Stage 3, so Stage 3 is better from year 2, when the first clones tested under the alternative’s Stage 2 reach it. Stage 1 benefits only through the parents, and only partly. The 10 Stage 3 clones are a sixth of the 60 parents, and the other 50, the Stage 2 clones, are chosen by the Stage 1 trial, which the alternative does not improve. So the advantage that reaches Stage 1 is a fraction of the one in Stage 3, and small next to the variation between replicates. A scenario can look little better in one stage and clearly better in another, so it is worth recording more than one stage.
To compare the scenarios, average each replicate’s results over the future years, and take the difference between the scenarios within each replicate. The mean of a stage in a single year is noisy, particularly for Stage 3, which holds only 10 clones, and averaging over the future years reduces that noise. Taking the difference within each replicate accounts for the replicates as blocks, as setting year 0 to zero does for the plots: the scenarios in a replicate share its starting level, so it cancels from their difference. The standard error of the difference then shows whether the difference between the scenarios is larger than the variation that remains.
## Average over the future years for each scenario and replicate
future = results[results$year > 0, ]
futureAvg = aggregate(cbind(meanStage1, meanStage3) ~ scenario + rep,
data=future, FUN=mean)
## Difference between the scenarios within each replicate
current = futureAvg[futureAvg$scenario == "Current",
c("meanStage1", "meanStage3")]
alternative = futureAvg[futureAvg$scenario == "Alternative",
c("meanStage1", "meanStage3")]
diffScenario = alternative - current
rbind(mean=colMeans(diffScenario),
se=apply(diffScenario, 2, sd)/sqrt(nReps))
#> meanStage1 meanStage3
#> mean 0.05062770 0.16026415
#> se 0.02580158 0.03588961Ten replicates keep this article quick to build, but they are too few for a reliable conclusion; with five, the difference in Stage 3 does not show at all. A real study would use enough replicates for the standard errors to be small next to the difference between the scenarios, and would look at the genetic variance as well as the mean, because a scenario that gains faster by using up genetic variance may fall behind over a longer horizon.
Miscellaneous comments
You can write chunks of code as R scripts and call one script from
another using the source function. I typically do this to
modularize my code. I rarely write a simulation as single script, as
shown in this example.
You may also consider defining your own functions to produce tidier code. See this help document for an example of how to write a function:
?`function`A convenient way to avoid overwriting populations is saving them to a list. This requires more memory and makes coding a bit more complicated, so I rarely use this approach. However, it does let you save all data from your simulation which can come in handy when you forget to measure something that you realize you need later. Below is a brief demonstration:
library(AlphaSimR)
founderPop = quickHaplo(nInd=50, nChr=4, segSites=1000, inbred=TRUE)
SP = SimParam$
new(founderPop)$
addTraitA(1000)
Parents = newPop(founderPop)
# Create list for generations F1 through F10
Pop = vector("list", 10)
# Produce F1s from a random biparental cross
Pop[[1]] = randCross(Parents, nCrosses=1, nProgeny=1000)
# Produce F2 through F10 generations using selfing
for(i in 2:10){
Pop[[i]] = self(Pop[[i-1]])
}
# Calculate genetic variance by generation
lapply(Pop, varG)
#> [[1]]
#> Trait1
#> Trait1 2.985944e-33
#>
#> [[2]]
#> Trait1
#> Trait1 0.2226239
#>
#> [[3]]
#> Trait1
#> Trait1 0.3416949
#>
#> [[4]]
#> Trait1
#> Trait1 0.3864036
#>
#> [[5]]
#> Trait1
#> Trait1 0.413633
#>
#> [[6]]
#> Trait1
#> Trait1 0.4305148
#>
#> [[7]]
#> Trait1
#> Trait1 0.4412737
#>
#> [[8]]
#> Trait1
#> Trait1 0.4428282
#>
#> [[9]]
#> Trait1
#> Trait1 0.4442569
#>
#> [[10]]
#> Trait1
#> Trait1 0.444045