Genomic Selection in AlphaSimR
Chris Gaynor
2026-12-01
Source:vignettes/GenomicSelection.Rmd
GenomicSelection.RmdIntroduction
Genomic selection is selection on a prediction of an individual’s
genetic merit made from its marker genotypes (Whittaker et al. 2000; Meuwissen et al. 2001).
AlphaSimR provides a family of ridge regression BLUP
(RR-BLUP) models for making these predictions. They are fitted in C++
and are meant to be re-fitted many times over the course of a
simulation, so they are deliberately narrow in scope: they are fast,
they take their data directly from a population object, and they return
an object that AlphaSimR knows how to turn back into
estimated values for any population you like.
This vignette is mostly about using those functions: which one to call, what to hand it, and where the call belongs in a breeding cycle. The model each one fits is described later, in a section you can skip on a first reading.
Two earlier documents are assumed. vignette("Genome")
explains how QTL and SNP chips are defined and how genotypes are stored
and pulled. The Quantitative
Genetics in AlphaSimR article on the AlphaSimR website explains the
distinction between a genetic value and a breeding value, and why a
breeding value is a property of a reference population rather
than of an individual on its own. That distinction reappears below,
because it determines what setEBV gives you.
Setting up an example
The example below is used throughout.
set.seed(1234)
founderPop = runMacs(nInd = 500, nChr = 10, segSites = 100)
SP = SimParam$new(founderPop)
# Reserve enough segregating sites for both the QTL and the SNP chip
SP$restrSegSites(minQtlPerChr = 20, minSnpPerChr = 50, overlap = FALSE)
SP$addTraitAD(nQtlPerChr = 20, meanDD = 0.4)
SP$addSnpChip(nSnpPerChr = 50)
SP$setVarE(h2 = 0.4)
pop = newPop(founderPop, simParam = SP)Two choices here are worth copying into your own simulations.
runMacs rather than quickHaplo. Genomic
prediction works because markers are in linkage disequilibrium with QTL,
and quickHaplo samples haplotypes at linkage equilibrium. A
simulation built on quickHaplo will show almost no
predictive ability in the founder population unless the QTL themselves
are used as markers, which makes it a poor choice for demonstrating or
benchmarking genomic selection. Selection and mating in a finite
population do create some linkage disequilibrium, but it builds up
slowly: a generation or two of crossing does little to change the
picture.
In AlphaSimR, QTL and SNP chip sites are kept separate
by default, in order to avoid inflating accuracy. Once a site is
designated for use as a QTL, it cannot be selected for the SNP chip, and
vice versa. This separation occurs automatically without invoking the
restrSegSites function. Overlapping of these sites is
permitted only if specifically requested with
restrSegSites(overlap = TRUE).
The restrSegSites call above isn’t strictly needed. With
one addTrait call and one addSnpChip call,
whichever comes first chooses from all 100 sites on each chromosome, and
the second chooses from what is left. Twenty QTL and 50 SNPs fit easily
either way.
It becomes necessary when you add several traits in separate calls or
several SNP chips. Calls of the same type don’t exclude each other’s
sites: a second chip can reuse SNPs from the first, as real chips often
share markers. But every call removes its sites from what the other type
can use. When several calls of one type come first, between them they
can claim more sites than the other type can spare. Without
restrSegSites, the order of the calls then decides whether
the setup works. Calling restrSegSites first sets the sites
aside before anything is chosen, so the order no longer matters.
Here, two chips of 70 and 50 SNPs are added before a 20-QTL trait. Between them the chips cover about 85 of each chromosome’s 100 sites, which leaves too few for the trait:
SP2 = SimParam$new(founderPop)
SP2$addSnpChip(nSnpPerChr = 70)
SP2$addSnpChip(nSnpPerChr = 50)
SP2$addTraitAD(nQtlPerChr = 20, meanDD = 0.4)
#> Error in `private$.pickLoci()`:
#> ! Not enough eligible sites, see ?SimParam and method restrSegSites()Adding the trait first works. Its 20 QTL are chosen from all 100 sites, and both chips then choose from the remaining 80:
SP2 = SimParam$new(founderPop)
SP2$addTraitAD(nQtlPerChr = 20, meanDD = 0.4)
SP2$addSnpChip(nSnpPerChr = 70)
SP2$addSnpChip(nSnpPerChr = 50)Reserving the sites first makes the original order work too:
SP2 = SimParam$new(founderPop)
SP2$restrSegSites(minQtlPerChr = 20, minSnpPerChr = 80, overlap = FALSE)
SP2$addSnpChip(nSnpPerChr = 70)
SP2$addSnpChip(nSnpPerChr = 50)
SP2$addTraitAD(nQtlPerChr = 20, meanDD = 0.4)The three steps
Every genomic selection analysis in AlphaSimR has the
same shape.
- Assemble a training population carrying both phenotypes and genotypes.
-
Fit a model to it, producing an object of
RRsol-class. -
Apply that solution to the selection candidates
with
setEBV, which fills theirebvslot.
Selection then proceeds with the ordinary selection functions, using
use="ebv".
# 1. Training population: phenotyped and genotyped
trainPop = setPheno(pop[1:400], simParam = SP)
# Selection candidates: genotyped only
candidates = pop[401:500]
# 2. Fit
ans = RRBLUP(trainPop, simParam = SP)
# 3. Predict
candidates = setEBV(candidates, ans, simParam = SP)
# Accuracy, measured on individuals that did not train the model
cor(ebv(candidates)[, 1], gv(candidates)[, 1])
#> [1] 0.3685519A training population is an ordinary Pop-class object.
There is no special class and no registration step; a model reads the
response and the genotypes out of whatever population you hand it. The
only requirements are that the population carries a value to train on
and that the SNP chip you intend to use was defined before the
population was created.
The response is chosen with the use argument, which
accepts "pheno" (the default), "gv",
"bv", "ebv" or "rand". Training
on phenotypes is the realistic choice. Training on "gv" or
"bv" is a diagnostic: it removes environmental noise and
shows what the model could achieve if phenotyping were perfect.
"rand" trains on noise and is useful for confirming that an
apparent gain really comes from the prediction.
Training populations are usually assembled from several sources, and
the natural tool for that is c():
Choosing a model
The first question is not which algorithm to use but what you are trying to predict. That answer picks the model; everything else is a matter of memory and speed.
| You want to predict | Use | Ask setEBV for |
|---|---|---|
| Merit of a parent, additive trait | RRBLUP |
"bv" or "gv"
|
| Performance of an individual with dominance | RRBLUP_D |
"gv" |
| GCA of inbreds in a two-pool hybrid program | RRBLUP_GCA |
"female", "male"
|
| Performance of a specific single cross | RRBLUP_SCA |
"gv" |
| Several correlated traits at once | Any of the above with traits=1:n
|
as for one trait |
| Exact REML estimates, or few markers and many records | Any of the above with solver="direct"
|
as for that model |
RRBLUP is the default choice. It fits
additive marker effects. If you are unsure, start here. Every model in
this table can also fit several traits at once, which is described
below.
RRBLUP_D adds a dominance covariate for
each marker. Reach for it when the trait was defined with dominance
and you care about the genetic value rather than only the
breeding value - predicting the performance of a cross or a clone, for
instance, rather than the merit of a parent (Xiang et al. 2016). If you only ever select
parents on additive merit, the extra term buys you little.
RRBLUP_GCA and
RRBLUP_SCA are for hybrid programs with
two heterotic pools. Rather than one set of additive effects they
estimate a set for each pool, so an allele can be worth something
different depending on which parent contributed it.
RRBLUP_SCA adds a dominance term on top, so specific
combining ability can be predicted as well as general combining ability
(Massman et al. 2013). Both fill the
female and male slots and leave
bv empty.
Jong et al. (2023) compared these
models for selecting inbred parents on predicted GCA in a simulated
maize program, and found that models fitting pool-specific effects
together with dominance gave the best fit and the highest genetic gain.
They also found that the ranking depends on marker density, with the
models differing more in genetic gain at low density and more in
heterosis at high density - a useful warning against assuming one model
is uniformly best. The help page for RRBLUP_SCA notes that
no consistent benefit over RRBLUP_GCA has been observed in
AlphaSimR’s own testing, so it is worth checking both in
your own simulation rather than assuming the more complex model
wins.
solver chooses how the model is solved.
RRBLUP, RRBLUP_D, RRBLUP_GCA and
RRBLUP_SCA all take it, and each fits the same model either
way. By default, with solver="cg", the model is solved by
conjugate gradient on the genotypes, which never forms a square matrix,
so its memory cost stays close to the cost of the genotypes themselves
and large training populations fit in little memory. The variance
components are then estimated on every record, as described below.
Estimating them draws random numbers, so a fit is repeated exactly by
setting the seed first. solver="direct" fits the model
directly and gives the exact REML estimates. It is quick on small
training populations, and the faster of the two when the records far
outnumber the marker effects, but its memory grows with the square of
the records or of the marker effects. On a few thousand records or fewer
it is also the more accurate choice for RRBLUP_D,
RRBLUP_GCA and RRBLUP_SCA, whose estimates by
conjugate gradient carry a Monte Carlo error that is largest there.
Fitting several traits
Giving traits more than one trait fits a multiple trait
model. The marker effects of the traits are correlated, as are their
errors, and both covariance matrices are estimated by REML, so a trait
with a low heritability can borrow information from a correlated trait
with a high one. RRBLUP, RRBLUP_D,
RRBLUP_GCA and RRBLUP_SCA all do this, fitted
directly or not, except that variance components supplied with
solver="direct" are for one trait. Every trait must be
recorded on every individual in the training population, and a missing
value stops the fit.
The example below uses two correlated traits with dominance, the second with a lower heritability:
SP2 = SimParam$new(founderPop)
SP2$restrSegSites(minQtlPerChr = 20, minSnpPerChr = 50, overlap = FALSE)
SP2$addTraitAD(nQtlPerChr = 20, mean = c(0, 0), var = c(1, 1),
meanDD = c(0.4, 0.4), varDD = c(0.04, 0.04),
corA = matrix(c(1, 0.7, 0.7, 1), nrow = 2))
SP2$addSnpChip(nSnpPerChr = 50)
SP2$setVarE(h2 = c(0.4, 0.1))
pop2 = newPop(founderPop, simParam = SP2)
trainPop2 = setPheno(pop2[1:400], simParam = SP2)
candidates2 = pop2[401:500]
# Fitted directly, to compare with the default fit below
mvModel = RRBLUP_D(trainPop2, traits = 1:2, solver = "direct", simParam = SP2)
candidates2 = setEBV(candidates2, mvModel, simParam = SP2)
# One column of estimates per trait
diag(cor(ebv(candidates2), gv(candidates2)))
#> [1] 0.2737650 0.2214099The solution holds one trait object per trait in each of its slots,
so setEBV fills one column of the ebv slot per
trait. Ve becomes the covariance matrix of the errors among
the traits. For RRBLUP, in either mode, Vu is
the covariance matrix of the marker effects. The dominance and hybrid
models have one covariance matrix per random term, and they are stored
together as a block diagonal matrix, with rows and columns named after
the term and the trait:
round(mvModel@Vu, 5)
#> a:Trait1 a:Trait2 d:Trait1 d:Trait2
#> a:Trait1 0.00585 0.00303 0.00000 0.00000
#> a:Trait2 0.00303 0.00197 0.00000 0.00000
#> d:Trait1 0.00000 0.00000 0.00036 0.00079
#> d:Trait2 0.00000 0.00000 0.00079 0.00174How the cost grows with the number of traits depends on the model.
RRBLUP, in either mode, estimates the covariance matrices
after a single rotation of the records, and a fit to several traits
takes about as long as fitting the traits one at a time. The dominance
and hybrid models cannot use that rotation. Every record and every
marker effect is counted once per trait, so a fit to three traits can
take several times as long as three single trait fits;
RRBLUPMemUse takes the number of traits into account. With
solver="cg", the default, every model keeps its memory
close to the size of the genotypes however many traits are fitted, and
estimates the covariance matrices on every record. Its time still grows
with the number of traits, because each covariance matrix has a
parameter for every pair of traits. Passing an earlier fit as
varComp, or supplying Vu and Ve,
gives REML a place to start, and with estVarComp=FALSE
avoids estimating them at all, as described next.
Fitting the same model more cheaply
Most of the cost of a fit is estimating the variance components.
Retraining a model whose variance components are already known, from an
earlier fit in the same simulation, needs only the solve for the marker
effects, and every model can be told to skip the estimation. The
simplest way is to pass the earlier fit as varComp, with
estVarComp=FALSE:
ans2 = RRBLUP(trainPop, varComp = ans, estVarComp = FALSE, simParam = SP)
candidates = setEBV(candidates, ans2, simParam = SP)
cor(ebv(candidates)[, 1], gv(candidates)[, 1])
#> [1] 0.3685519The work reduces to a single solve of the mixed model equations,
which is quick. With the default, solver="cg", the solve is
by conjugate gradient, and works for any number of traits. With
solver="direct" it is written on whichever of the markers
and the records is the smaller, and it is for one trait. Refitting the
multiple trait dominance model from above, which was fitted directly,
with its own variance components gives the same predictions:
mvFast = RRBLUP_D(trainPop2, traits = 1:2, solver = "cg",
varComp = mvModel, estVarComp = FALSE, simParam = SP2)
candidatesFast = setEBV(candidates2, mvFast, simParam = SP2)
# The direct and conjugate gradient predictions agree
diag(cor(ebv(candidatesFast), ebv(candidates2)))
#> est_GV_Trait1 est_GV_Trait2
#> 1 1The common pattern is to fit a model once at the start of a
simulation and pass that fit as varComp for every
subsequent re-training. Whether holding the variance components fixed is
acceptable depends on how far the population drifts over the simulation,
and that is a question only the simulation can answer - check against a
full re-fit before relying on it.
Leaving estVarComp at its default, TRUE,
re-estimates the variance components instead, with REML starting from
those of the earlier fit rather than from its own starting values. A
population that has changed little since the earlier fit is close to the
answer already, so REML gets there in fewer iterations, and it reaches
the same estimates as a fit started afresh, to within the tolerance of
its test of convergence. This costs nothing in accuracy, and suits a
model refitted every cycle on a training population that grows by a
generation at a time. Refitted to 8,000 records and 4,000 markers from a
fit to the 4,000 of the cycle before, the dominance and hybrid models
fitted by conjugate gradient took 2 or 3 REML iterations instead of 4 to
6, and 25 to 50 percent less time. The direct fits gain less, or for
several traits nothing, because most of their time goes on
decompositions that do not depend on where REML starts:
# The last cycle's fit is where this cycle's REML starts
gsModel = RRBLUP_D(trainPop, varComp = gsModel, simParam = SP)RRBLUP fitted to one trait is the exception. Its REML
searches over the ratio of the two variances and takes no starting
value, so an earlier fit passed to it with estVarComp=TRUE
is not used.
Every fit records the model it came from, and varComp
checks it, so a fit can only be passed to the model that produced it: an
RRBLUP_GCA fit cannot be passed to RRBLUP_D,
although both have two variance components for one trait. The fit must
also be for the same number of traits and on the same markers, because
Vu is the variance of an effect of those markers.
Vu and Ve can still be given directly,
which is the way to use values that did not come from a fit, or that
have been changed. A fit’s own Vu and Ve slots
can be passed as they are, including the block diagonal Vu
of the dominance and hybrid models, so this call is the same as the one
above:
mvFast = RRBLUP_D(trainPop2, traits = 1:2, solver = "cg",
Vu = mvModel@Vu, Ve = mvModel@Ve, estVarComp = FALSE,
simParam = SP2)For one trait, Vu holds one variance per random term:
the additive and dominance effects for RRBLUP_D, the female
and male effects for RRBLUP_GCA, and those two followed by
the dominance effects for RRBLUP_SCA. Fits saved before
varComp was added do not record their model, and are passed
as Vu and Ve in this way. A variance of zero,
which REML often estimates for a dominance term, leaves that term out of
the model, so a fit like that can be passed on as it is.
The numbered functions RRBLUP2, RRBLUP_D2,
RRBLUP_GCA2 and RRBLUP_SCA2 used to be the way
to do this, and are deprecated. With useEM=FALSE, each
gives the same result, to rounding, as its unnumbered counterpart given
the same variance components with estVarComp=FALSE and
solver="direct". Left to estimate the variance components,
they use an EM algorithm, which is slower and less reliable than the
REML of the unnumbered models.
Using the models in a breeding program
The three steps above are the whole API. What takes judgment is where
they go in a breeding cycle and what feeds them. Bančič et al. (2025) work through complete plant
breeding programs in AlphaSimR - line, clonal and hybrid -
each with a genomic selection variant, and the patterns below follow
that paper. Its scripts are a good companion to this vignette.
The examples in this section are sketches rather than runnable code; they assume a pipeline of yield trial stages with the usual names.
Replacing a phenotyping stage
The most direct use of genomic selection is to predict individuals that have not been phenotyped, which lets an early phenotyping stage be dropped altogether. In a wheat line program the headrow stage exists only to screen doubled haploids, so predicting the doubled haploids removes the need for it:
# Predict every DH and advance the best to the first yield trial
DH = setEBV(DH, gsModel, simParam = SP)
PYT = selectWithinFam(DH, famMax, use = "ebv", simParam = SP)
PYT = selectInd(PYT, nPYT, use = "ebv", simParam = SP)
PYT = setPheno(PYT, varE = varE, reps = repPYT, simParam = SP)Note the two-stage selection. Selecting within families first, then across them, limits how many entries any one cross can contribute. Genomic predictions are strongly correlated within a family, so unrestricted truncation selection on EBVs tends to fill the next stage with full sibs and burn through genetic variance faster than the equivalent phenotypic scheme.
Selecting parents earlier
The larger gain usually comes from shortening the cycle rather than from predicting more accurately. Once doubled haploids can be ranked without phenotyping, parents can be drawn from them instead of from the elite trial several years later:
DH = setEBV(DH, gsModel, simParam = SP)
newParents = selectInd(DH, nNewParents, use = "ebv", simParam = SP)
# Replace the oldest parents with the newly predicted ones
Parents = c(Parents[-(1:nNewParents)], newParents)Taken further, this becomes the two-part strategy of Gaynor et al. (2017): a product development component that still runs on phenotypes, and a population improvement component that runs entirely on EBVs and cycles several times per year.
Maintaining a training population
A model is only as good as what trained it, and in a running simulation the training population has to be maintained rather than defined once. The usual arrangement accumulates records during a burn-in and then holds the size constant with a sliding window, dropping the oldest records as new ones arrive:
if (year == startTP) {
trainPop = c(PYT, AYT, EYT)
} else if (year <= nBurnin) {
# Accumulate
trainPop = c(trainPop, PYT, AYT, EYT)
} else {
# Fixed size: drop the oldest year of records
nNew = c(PYT, AYT, EYT)@nInd
trainPop = c(trainPop[-(1:nNew)], PYT, AYT, EYT)
}Capping the size matters for more than run time. Records from many generations back describe a population that no longer exists, and the linkage disequilibrium they carry has been broken up by recombination since. A window of the last few years is both cheaper and may be more accurate than one using everything ever recorded. The value of including older lines will vary greatly between simulations and is potentially an area worth exploring in a simulation.
How often to retrain
Refitting every cycle on an updated training population is the straightforward choice and the one the examples above assume. It is also the expensive one. Four cheaper options, in rough order of how much they give up:
Refit every cycle with REML started from the last cycle’s fit, passed as
varComp. This re-estimates the variance components, to the same estimates as a fresh fit, in fewer iterations.Refit every cycle with the variance components held fixed, passing one full fit from the start as
varCompwithestVarComp=FALSE, for one trait withsolver="direct".-
Refit every cycle by conjugate gradient, the default, passing an earlier fit as
varCompwithestVarComp=FALSE, which leaves only the solve for the marker effects, whose cost grows far more slowly with the number of records than a full fit’s. This also works for several traits and for the dominance and hybrid models. Without supplied variance components, most of the time goes on estimating them, so re-estimating them only every few cycles saves most of the time: Refit every k cycles and reuse the solution in between. A solution is an ordinary object; nothing stops you applying it to several generations of candidates.
The following runs three cycles of genomic selection on the example population, refitting each cycle against a training population that accumulates the newest phenotyped generation:
gsPop = pop
gsTrainPop = setPheno(pop, simParam = SP)
for (cycle in 1:3) {
# Fit to everything phenotyped so far
gsModel = RRBLUP(gsTrainPop, simParam = SP)
# Predict and select
gsPop = setEBV(gsPop, gsModel, simParam = SP)
gsPop = selectCross(gsPop, nInd = 50, nCrosses = 100, nProgeny = 2,
use = "ebv", simParam = SP)
# Phenotype the new generation and add it to the training records
gsTrainPop = c(gsTrainPop, setPheno(gsPop, simParam = SP))
cat("cycle", cycle, " meanG =", round(meanG(gsPop), 3),
" nTrain =", nInd(gsTrainPop), "\n")
}
#> cycle 1 meanG = 0.969 nTrain = 700
#> cycle 2 meanG = 1.747 nTrain = 900
#> cycle 3 meanG = 2.562 nTrain = 1100The mean genetic value rises each cycle, and the training population grows as it does - which is exactly the cost that the options above are there to control.
Hybrid programs
In a two-pool hybrid program the training records are testcross
performance rather than line performance, and the predictions wanted are
combining abilities. RRBLUP_GCA fits both pools at once and
setEBV is then asked for the pool-specific value:
gsModel = RRBLUP_GCA(hybridTrainPop, simParam = SP)
maleDH = setEBV(maleDH, gsModel, value = "male", simParam = SP)
femaleDH = setEBV(femaleDH, gsModel, value = "female", simParam = SP)
newMaleParents = selectInd(maleDH, 10, use = "ebv", simParam = SP)
newFemaleParents = selectInd(femaleDH, 10, use = "ebv", simParam = SP)A simpler alternative, which Bančič et al.
(2025) use as their default, is to fit an ordinary
RRBLUP to the hybrid training population and read the
result as a general combining ability. That works because a
hybrid-trained additive model estimates the average effect of an allele
across the opposite pool, which is what GCA is. Fitting
RRBLUP separately within each pool on inbred performance is
a third option, and is the one to use when testcross data are not
available.
To predict the performance of a specific cross rather than
the merit of its parents, fit RRBLUP_SCA and ask for
value="gv" on the hybrid population produced by
hybridCross.
Working with EBVs
setEBV applies a solution to a population and writes the
result into the ebv slot. The value argument
chooses what is estimated: "gv" (the default) for an
estimated genetic value, "bv" for an estimated breeding
value, and "female" or "male" for estimated
general combining abilities.
For a purely additive model the distinction between "gv"
and "bv" is cosmetic: both use the same marker effects and
differ only in the intercept, so they are perfectly correlated and
select the same individuals. The distinction matters once dominance is
in the model, because then the genetic value and the breeding value are
different quantities and rank individuals differently.
append controls whether the new estimates replace the
contents of the ebv slot or are added as an extra column.
Appending is how you carry several estimates at once - a genetic value
and a breeding value from the same fit, or estimates for several traits
to be combined in an index.
The reference population
An estimated breeding value depends on allele frequencies, because an
average effect does. By default setEBV uses the frequencies
implied by the fitted model, which are those of the training population.
The targetPop argument overrides this, recomputing the
average effects
(Falconer and Mackay 1996) at the allele
frequencies of the population you supply:
candidates = setEBV(candidates, ans, value = "bv", targetPop = candidates,
append = TRUE, simParam = SP)
cor(ebv(candidates)[, 1], ebv(candidates)[, 2])
#> [1] 1For an additive model this changes nothing but the intercept, as the
correlation of one shows. For a model with dominance it genuinely
changes the ranking, and it is the right thing to do when the population
being selected has drifted away from the population the model was
trained on. In a hybrid program it is how a parent is evaluated against
the opposite pool, by passing that pool as
targetPop.
Measuring accuracy
Accuracy is the correlation between the estimate and the thing it is meant to estimate. Which “thing” depends on the decision. If you are selecting parents, breeding value is the relevant target; if you are selecting a variety to release, genetic value is.
cor(ebv(candidates)[, 1], gv(candidates)[, 1])
#> [1] 0.3685519
cor(ebv(candidates)[, 1], bv(candidates, simParam = SP)[, 1])
#> [1] 0.3460046Two mistakes are easy to make. The first is measuring accuracy in the training population. Those individuals contributed to the fit, so the correlation there is inflated and says little about performance on the individuals you actually have to select:
trainPop = setEBV(trainPop, ans, simParam = SP)
# Inflated: these individuals trained the model
cor(ebv(trainPop)[, 1], gv(trainPop)[, 1])
#> [1] 0.6648799The second is comparing a correlation against genetic value with one against breeding value and treating the difference as a property of the model. With dominance in the trait the two targets differ, and the gap between them is a property of the trait, not of the prediction.
Practical matters
Choosing the markers
By default the models use the first SNP chip. A different chip is
selected with snpChip, and useQtl=TRUE
substitutes a trait’s QTL for the chip. The QTL option is a diagnostic:
it gives an upper bound on what a model can achieve, because it removes
the imperfect linkage between markers and causal loci. Be aware that
when useQtl=TRUE the snpChip argument switches
meaning and selects which trait’s QTL to use, so those QTL need
not be the ones underlying the response you are modeling.
Size and memory
The cost of these models is driven by the number of training records
and the number of markers, and the balance between the two decides which
implementation to use. RRBLUPMemUse estimates the memory
required, and takes the model as the name of the function that fits it,
with solver for how it is fitted:
RRBLUPMemUse(nInd = 5000, nMarker = 2000, model = "RRBLUP")
#> [1] 0.0228837
RRBLUPMemUse(nInd = 5000, nMarker = 2000, model = "RRBLUP", solver = "direct")
#> [1] 0.25
RRBLUPMemUse(nInd = 5000, nMarker = 2000, model = "RRBLUP_SCA",
solver = "direct")
#> [1] 1.93048
RRBLUPMemUse(nInd = 5000, nMarker = 2000, model = "RRBLUP_SCA")
#> [1] 0.05761106The estimate covers the matrices the solvers hold at their peak, not
the population object or the rest of the session, so it is a lower bound
on what the simulation needs. Like the models, it takes
solver = "cg", the conjugate gradient fit, by default.
RRBLUPMemUse is most useful for spotting the point at which
a training population outgrows the machine.
What the models fit
This section is the background to the choices above, and can be skipped.
All of these models are ridge regressions on marker genotypes, where holds the marker covariates, the marker effects are treated as random with a common variance , and holds the fixed effects discussed in the next section. The shrinkage applied to the marker effects is set by the ratio , so the variance components have to be estimated before the effects can be.
Markers are coded on the same scale AlphaSimR uses for
trait effects: for a diploid, the additive covariate takes the values
-1, 0 and 1 for the three genotypes, and the dominance covariate takes
the value 1 for the heterozygote and 0 otherwise. A model fitted with
useQtl=TRUE therefore estimates effects that are directly
comparable with the true QTL effects in SP$traits, which is
convenient for checking a model against the truth. Effects estimated on
a SNP chip belong to markers that are not the QTL, so they have no true
counterpart to compare with.
A fitted model is returned as an RRsol-class object with
seven slots:
class(ans)
#> [1] "RRsol"
#> attr(,"package")
#> [1] "AlphaSimR"
ans@Vu
#> [,1]
#> [1,] 0.004590639
ans@Ve
#> [,1]
#> [1,] 1.961579Vu and Ve hold the estimated marker and
residual variances, and model names the function that
fitted them, which is what varComp checks. The remaining
four - gv, bv, female and
male - hold trait objects, the same kind of object
SimParam uses to define a real trait. This is what makes a
solution portable: a fitted model is stored as an estimated trait, so
applying it to a new population is the same operation as evaluating a
genetic value, and it works on any population carrying the same
markers.
Which slots are filled depends on the model. RRBLUP and
RRBLUP_D fill gv and bv; the GCA
and SCA models fill gv, female and
male and leave bv empty. A model fitted to
several traits holds one trait object per trait in each slot it fills.
Asking setEBV for a value the model did not produce raises
an error rather than returning something misleading.
How the equations are solved
The ways of fitting described below differ only in arithmetic, not in
the model. The direct fits, with solver="direct", come
first, and the conjugate gradient fits of the default after them.
For a single trait, RRBLUP fitted directly uses the
approach of FaST-LMM (Lippert et al.
2011): the problem is transformed by an eigendecomposition, and
the variance components are then found by maximizing the restricted
likelihood (Patterson and Thompson 1971)
along a single dimension, with the fixed effects re-estimated at every
step. The matrix decomposed has the dimension of the smaller of the
number of records and the number of markers, because a matrix and its
transpose share their nonzero eigenvalues. This is fast and
reliable.
The other unnumbered models have more than one variance component, so
they cannot be reduced to a single dimension. RRBLUP_D,
RRBLUP_GCA and RRBLUP_SCA estimate theirs with
average information REML (Gilmour et al.
1995). They can work either with the variance matrix of the
records, whose dimension is the number of records, or with Henderson’s
mixed model equations, whose dimension is the number of fixed effects
plus the number of marker effects, and they choose whichever is cheaper.
Both give the same estimates. With many more records than markers the
second is far faster: a dominance model fitted to 5000 records and 500
markers takes well under a second. RRBLUP fitted to several
traits estimates unstructured covariance matrices among the traits by
REML, following Zhou and Stephens (2014).
It rotates the records by an eigendecomposition of the smaller of the
two cross products, after which the work in each iteration grows only
linearly with the number of records. No such rotation exists for more
than one random term, so RRBLUP_D, RRBLUP_GCA
and RRBLUP_SCA fitted to several traits use average
information REML on whichever of the two forms is cheaper, now with one
row per record and trait or per marker effect and trait. Their cost
therefore grows quickly with the number of traits, and
RRBLUPMemUse takes the number of traits into account.
Given their variance components with
estVarComp=FALSE, and with
solver="direct", the models estimate nothing. They evaluate
the same model the REML of RRBLUP_D,
RRBLUP_GCA and RRBLUP_SCA fits, with a single
term for RRBLUP, once at the supplied values, on whichever
of the variance matrix of the records and Henderson’s equations is
cheaper, and a term whose variance is zero is left out.
RRBLUPMemUse with useEM=FALSE reports the
memory this needs; without it, RRBLUPMemUse reports the
memory of the full fit for each model and choice of
solver.
RRBLUP with solver="cg"
forms no square matrix to solve the model. It solves the mixed model
equations by preconditioned conjugate gradient, iterating over the
genotypes rather than over a stored coefficient matrix (Strandén and Lidauer 1999). Neither the
coefficient matrix nor a numeric copy of the genotypes is ever formed,
so its memory cost stays close to the cost of the genotypes themselves,
and both halves of each iteration are shared across
nThreads.
It is fitted as the dominance and hybrid models are below, as the
case of a single random term, and so estimates its variance components
the same way, on every record. On a large training population that takes
longer than the direct fit when the records far outnumber the markers:
with 4,000 markers and 50,000 records it took 14 seconds where
solver="direct" took 9, while raising the memory in use by
0.26 GB where the direct fit raised it by 2.25 GB. To estimate the
variance components on a subset of the records instead, fit
RRBLUP to the subset and pass that fit to a fit on every
record as varComp, with estVarComp=FALSE, so
that only the marker effects are solved for on every record.
RRBLUP_D, RRBLUP_GCA and
RRBLUP_SCA with solver="cg" have two
or three random terms, each with its own variance, or for several traits
its own covariance matrix, so the effects of every term and trait are
solved together as one system by conjugate gradient, as are those of
several traits in RRBLUP. The responses are first whitened
by Ve, which makes the coefficient matrix the identity plus
a positive semidefinite matrix whatever the variance components are, and
the iteration is preconditioned by scaling each term and trait and
deflating the largest eigenvalues. An iteration costs about as much as
one product with the genotypes for each term and trait, so the time
taken grows with the number of terms times the number of traits, while
the memory stays close to the size of the genotypes.
The variance components are estimated by average information REML on
every record, with every solve done by conjugate gradient. REML needs
traces of the inverse of the mixed model equations, which conjugate
gradient does not give, so they are estimated by Monte Carlo from five
sets of records of every trait simulated from the model, which are drawn
once per fit and solved for together with the records at every
iteration. The simulated records come from the simulation’s random
numbers, so a fit is repeated exactly from a seed whatever
nThreads is. The estimates carry the Monte Carlo error of
five samples, so they differ a little from those of
solver="direct", but the predictions barely do: fitted to
one to three traits on 2,000 to 50,000 individuals with 4,000 markers,
the estimated breeding values of every model correlated with those of
solver="direct" above 0.998, and above 0.9998 from 8,000
individuals. The time saved grows with the training population. On
20,000 individuals two traits of RRBLUP_D took 31 seconds
rather than 165, and raised the memory in use by 0.16 GB where the
direct fit raised it by 11.6 GB. For several traits, each covariance
matrix is kept positive semidefinite, so a genetic correlation of one,
or a term with no variance, is reached without leaving the parameter
space.
Some combinations of effects cannot be told apart by the records at
all. For inbred lines, whose two haplotypes are the same, the maternal
and paternal codes of RRBLUP_GCA coincide, and only the
prior decides how an effect is split between the two parents. The solver
finds those combinations at each marker and removes them exactly, so the
split follows the variance components however large the variance ratio.
Iteration stops only when the residual bounds the error of the marker
effects, as well as being small next to the data, because effects that
only the prior holds, such as effects that cancel across markers in
complete linkage disequilibrium, can otherwise stay far from their
values while the residual looks small. At variance ratios near the
limits of double precision, when the error variance is many orders of
magnitude below the genetic variance, a fit can warn that rounding
limits the accuracy of the solution, giving how much the effects still
change between restarts, or that the iteration stalled. Those warnings
mean the problem is beyond what the arithmetic can resolve, not that the
model is wrong, and they do not arise for heritabilities a simulation
would use.
RRBLUP_SCA fits diploids only, in either mode, because
its model splits each genome into one maternal and one paternal
haplotype.
Fixed effects
The models fit an intercept by default, and that is all most
simulations need. The fixEff slot of a population labels
each record with a group, and the models fit those groups as fixed
effects. The label is set by the fixEff argument of
setPheno and is carried by the population from then on:
batch1 = setPheno(pop[1:200], fixEff = 1L, simParam = SP)
batch2 = setPheno(pop[201:400], fixEff = 2L, simParam = SP)
table(c(batch1, batch2)@fixEff)
#>
#> 1 2
#> 200 200Internally each model applies
as.integer(factor(pop@fixEff)), so the labels need not be
consecutive or start at one; only the distinct values matter. The design
matrix uses sum-to-zero coding with an intercept in the first column, so
a population with a single fixEff level reduces to fitting
an intercept alone.
It is worth being explicit about what fixEff does
not do. It does not add anything to the phenotype.
AlphaSimR will not shift the mean of batch2
simply because it was labeled 2. The label lets a model
absorb differences that you created. If you generate all
records the same way, the fitted fixed effects estimate nothing.
This detail matters in one situation in particular: combining
populations phenotyped in different environments into a single training
population, when the trait has a genotype-by-environment
component. A trait created with varGxE and
varEnv - through addTraitAG,
addTraitADG and their relatives - has an environment effect
that shifts the mean of every record taken in that environment, with the
environment drawn by the p argument of
setPheno. Records from a first-year trial and a second-year
trial are then on genuinely different scales. Pooling them without a
label leaves that difference in the residual, where it inflates
,
shrinks the marker effects too hard and lowers accuracy. Labeling each
trial with its own fixEff lets the model absorb the
shift:
# Each trial phenotyped in its own environment, and labeled as such
PYT = setPheno(PYT, reps = repPYT, p = pYear, fixEff = year, simParam = SP)
AYT = setPheno(AYT, reps = repAYT, p = pYear, fixEff = year, simParam = SP)
trainPop = c(trainPop, PYT, AYT)The sliding-window training population described earlier is exactly this case, since it spans several years of trials. For a trait with no GxE component, and for records generated identically, the labels can be left alone.
Using external software
The AlphaSimR models cover ridge regression and its
close relatives. For anything else - a Bayesian model, a GBLUP with a
particular relationship matrix, a machine learning method - export the
genotypes and do the prediction elsewhere.
Genotypes come out as an ordinary matrix, with individuals in rows and markers in columns, coded as allele dosages:
geno = pullSnpGeno(trainPop, snpChip = 1, simParam = SP)
dim(geno)
#> [1] 400 500
geno[1:5, 1:5]
#> 1_2 1_4 1_6 1_8 1_10
#> 1 0 0 0 0 0
#> 2 0 1 2 0 0
#> 3 1 1 1 1 0
#> 4 1 0 1 0 0
#> 5 2 0 1 0 0The matching marker map, which most external software will want,
comes from getSnpMap:
head(getSnpMap(snpChip = 1, simParam = SP))
#> id chr site pos
#> 1_2 1_2 1 2 0.01268219
#> 1_4 1_4 1 4 0.02324462
#> 1_6 1_6 1 6 0.05512589
#> 1_8 1_8 1 8 0.09208273
#> 1_10 1_10 1 10 0.11034062
#> 1_11 1_11 1 11 0.11402233pullQtlGeno and pullSegSiteGeno do the same
for QTL and for all segregating sites, and the pull*Haplo
family returns haplotypes rather than genotypes. For software that reads
files rather than matrices, writePlink writes a population
in PLINK format and writeRecords writes phenotype
records.
Bringing predictions back is a matter of writing them into the
ebv slot directly. setEBV is a convenience for
AlphaSimR’s own solutions, not a requirement:
# 'pred' is a vector of predictions from an external package,
# in the same order as the individuals in candidates
candidates@ebv = as.matrix(pred)The slot must be a numeric matrix with one row per individual; any
number of columns is allowed, and the selection functions index it with
their trait argument. Once it is filled, the population
behaves exactly as it would after setEBV, and every
selection function with use="ebv" will work.
Two R packages worth mentioning here are rrBLUP and
sommer (Covarrubias-Pazaran
2016). Both accept the matrices produced above without
modification: rrBLUP fits a mixed model with a single
marker or relationship kernel, and sommer fits mixed models
with arbitrary covariance structures. EMMREML (Akdemir and Godfrey 2015) is another option for
models with known covariance structures.