EDI (Experimental Design and Inference) draws randomness in several
different places — design allocation, non-parametric/Bayesian/parametric
bootstrap, randomization-based inference, and Monte Carlo simulation —
from several different RNG sources (R’s own generator, a portable C++
reimplementation of it, and, in exactly two documented cases, hardware
entropy that is not reproducible at all). This page is the
single place that explains which mechanism applies where, so individual
class/function documentation can link here instead of repeating it. See
vignette("notation-glossary") for the symbols referenced
below.
What a design’s seed guarantees: fixed vs sequential
designs
Every Design constructor accepts a seed
argument and stores it. How it is applied differs between the
two design families, and so does what the seed guarantees.
Fixed designs (DesignFixed*): the seed is
applied at the start of every draw.
private$maybe_set_seed(), which is
if (!is.null(private$seed)) set.seed(private$seed), runs
inside each call that draws an allocation
(assign_w_to_all_subjects(),
draw_ws_according_to_design()). It sets R’s global
generator and does not restore the caller’s previous state.
Therefore:
- Two designs constructed with the same
seedand data produce identical allocations, whatever the global RNG state was and whatever ran in between. - Calling a draw method a second time on the same object
re-seeds, so it repeats the first draw rather than
advancing to a fresh one. If you want
rdifferent replicate columns, request them in one call (draw_ws_according_to_design(r)), not viarsingle-draw calls. - Each draw leaves R’s global stream at the state right after that seeded draw, so code after it in your session sees the same random numbers every time.
Sequential designs (DesignSeqOneByOne*): each
assignment is seeded from the seed and the subject’s index.
Subject t’s assignment
(add_one_subject_to_experiment_and_assign()) runs under
set.seed() of a seed derived from (seed,
t), with the session’s .Random.seed saved
before and restored after. Construction does not touch the generator.
Therefore:
- The allocation depends only on the seed and the subjects’ data (the
covariates and, for the KK21 designs, the responses recorded before each
assignment). Random-number use between assignments (a
runif(), another design’s draw, an unseeded bootstrap) does not change it. - Your own random-number stream is left exactly as it was: the same
runif()sequence comes out with or without assignments in between. - The seed is stored in the design, so a design saved with
saveRDS()and reloaded withreadRDS()continues exactly as an uninterrupted run would, with no extra code. -
draw_ws_according_to_design()on a seeded sequential design runs under a seed derived from (seed,"redraw"), also inside a save/restore, so repeated calls return the same draws (as on a fixed design) and do not move your stream.
This applies to every sequential design, including those whose
per-subject draw runs in C++ (Atkinson, Pocock-Simon, the KK matching
kernels): they draw from R’s generator, or seed a local one from a
single R draw, so the per-subject seed governs them too. This ships in
the first release after 1.0.4 (listed under “EDI (development version)”
in NEWS); in the EDI 1.0.4 release and earlier the sequential seed was
applied once, in the constructor, and every later assignment drew from
the global stream wherever it was. A development build installed before
that release still reports version 1.0.4, in
packageVersion("EDI") and in a saved design’s
get_edi_version_created(), but already seeds per subject,
so a version stamp of “1.0.4” alone does not tell you which rule drew a
design’s allocation.
seed = NULL (the default, both
families) leaves R’s ambient RNG state untouched: draws consume whatever
state R’s global stream happens to be in, exactly like any other call to
sample()/runif().
The chunk below checks each of these statements.
library(EDI)
#> Welcome to EDI v1.0.5
set.seed(1)
n = 20
X = data.frame(x1 = rnorm(n), x2 = rnorm(n))
# Fixed design: the seed is applied at the start of every draw.
fixed = DesignFixedBernoulli$new(n = n, response_type = "continuous", seed = 42, verbose = FALSE)
fixed$add_all_subjects_to_experiment(X)
a = fixed$draw_ws_according_to_design(1)
invisible(runif(3)) # unrelated random-number use in between
b = fixed$draw_ws_according_to_design(1)
identical(a, b) # the second call re-seeds and repeats the first draw
#> [1] TRUE
# Sequential design: each assignment is seeded from (seed, subject index).
enroll_all = function(extra_draws = 0) {
des = DesignSeqOneByOneBernoulli$new(n = n, response_type = "continuous", seed = 42, verbose = FALSE)
for (i in 1:n) {
invisible(runif(extra_draws)) # random-number use between assignments
des$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
}
des$get_w()
}
identical(enroll_all(), enroll_all(3)) # three runif() draws before each assignment: same allocation
#> [1] TRUE
# The session's own stream is untouched by seeded assignments.
set.seed(7); u_alone = runif(2)
set.seed(7); u_around = c(runif(1), {enroll_all(); runif(1)})
identical(u_alone, u_around)
#> [1] TRUEA seeded sequential trial can be saved and continued in another session without saving anything but the design:
des = DesignSeqOneByOneBernoulli$new(n = n, response_type = "continuous", seed = 42, verbose = FALSE)
for (i in 1:10) des$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
trial_file = tempfile(fileext = ".rds")
saveRDS(des, trial_file)
for (i in 11:n) des$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
uninterrupted = des$get_w()
set.seed(999) # stands in for a new session's state
resumed = readRDS(trial_file)
for (i in 11:n) resumed$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
identical(resumed$get_w(), uninterrupted)
#> [1] TRUEWith seed = NULL, a sequential design draws each
assignment from the session’s stream. To pause such a trial and continue
it exactly, save the generator state next to the design and restore it
before the next assignment:
set.seed(42)
des0 = DesignSeqOneByOneBernoulli$new(n = n, response_type = "continuous", verbose = FALSE)
for (i in 1:10) des0$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
trial_file0 = tempfile(fileext = ".rds")
saveRDS(list(design = des0, rng = .Random.seed), trial_file0)
for (i in 11:n) des0$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
uninterrupted0 = des0$get_w()
set.seed(999) # a new session's state
saved = readRDS(trial_file0)
assign(".Random.seed", saved$rng, envir = globalenv())
for (i in 11:n) saved$design$add_one_subject_to_experiment_and_assign(X[i, , drop = FALSE])
identical(saved$design$get_w(), uninterrupted0)
#> [1] TRUESeveral fixed designs do their heavy random work in C++ on local
generators (DesignFixedGreedy,
DesignFixedGreedyDOptimal, and
DesignFixedOptimal, which uses per-chain generators for its
annealing solver plus an R-level mirror coin; each has a subsection
below). They take their master seed from R’s stream after
maybe_set_seed(), so the constructor’s seed
still governs the draw. The OpenMP kernels derive their local stream
from each logical draw index, so a fixed seed gives the same result at
every configured thread count. Every concrete design is
seed-reproducible in the sense above: a fixed design on every draw, a
sequential design on every assignment.
DesignFixedOptimal: deterministic solves, seeded coin
and chains
DesignFixedOptimal computes one optimal allocation
rather than drawing from a randomization distribution, so most of its
“draw” is not random at all:
-
The exact
"ompr"MILP path is fully deterministic — same data, same arguments, same allocation, no RNG consumed by the solve itself. -
The mirror coin is R-seeded. With
mirror_coin = TRUE(the default) and a verified co-optimal mirror atprob_T = 0.5, onerunif(1)draw from R’s live stream decides betweenw*and1 - w*. Under the constructor’sseed,maybe_set_seed()runs before the solve, so the flip is reproducible; the MILP path is therefore “deterministic up to the seeded label flip.” -
The annealing solver seeds one
edi_rng::RRngper chain (not per thread), each from oneR::unif_rand()draw before the parallel region — so a givenset.seed()reproduces the identical search under any OpenMP thread count, the same guarantee the greedy-family designs give through per-draw-index streams (see below). Wheninitial_tempis auto-calibrated, the calibration probe also consumes R’s stream (and is therefore covered by the same seed). Annealing carries certificate"annealing_converged", never"global": Hajek (1988) guarantees convergence in probability only under a logarithmic cooling schedule, and the practical geometric schedule used here is asymptotically motivated, not a finite-time proof. -
BRT replicates replay the coin-inclusive mechanism:
each replicate’s re-optimization (reduced annealing by default,
solver_args$brt_*) and its own mirror flip consume the worker’s seeded stream, so bootstrap randomization p-values are reproducible underset.seed()like every other BRT in the package.
The portable cross-language RNG: edi_rng::RRng
Most C++ backends that need bulk random draws (Pocock-Simon
minimization’s pocock_simon_assign_cpp, the bootstrap-index
generators
bootstrap_indices.cpp/bootstrap_match_indices.cpp,
weighted-distance sampling, and others) do not call
back into R’s unif_rand() for every individual draw — that
has real per-call overhead. Instead they use a two-step pattern:
- Draw exactly one value from R’s live RNG stream via
R::unif_rand(), and convert it to a 32-bit integer seed (edi_rng::seed_from_unif01()). - Seed a fresh
edi_rng::RRnginstance (RNG.h) from that one integer, and do every subsequent draw against that instance instead of R’s own generator.
edi_rng::RRng is a portable, from-scratch
reimplementation of R’s own Mersenne-Twister + Inversion
generator (not a wrapper around it) — the same generator,
byte-for-byte, callable from C++ or Python without linking against R’s
runtime. This is what makes a given seed produce identical draws
in R and in the Python bindings (edi_kernels)
using the same core, and is why individual function docstrings describe
this as “seeded from one R::unif_rand() draw into
edi_rng::RRng.”
Consequence worth internalizing: because only one
unif_rand() value is consumed from R’s stream per call, R’s
own .Random.seed afterward has advanced by exactly one
draw, not by however many draws happened inside the C++ function — so
R-level code interleaving several such calls still gets a well-defined,
reproducible (if not obviously predictable) sequence of R-level draws in
between them.
The one documented exception: continuing R’s live stream bit-for-bit
pocock_simon_redraw_w_cpp is the only
function in the package that does not use the one-draw-seeded
pattern above. It instead reads R’s live .Random.seed
directly, continues R’s Mersenne-Twister stream exactly where it left
off for every draw inside the loop, and writes the advanced state back
to .Random.seed when done — so its output is bit-identical
to what a subject-by-subject R-level loop calling
unif_rand() directly would have produced (verified against
an independent pure-R reference implementation in
test-pocock-simon-redraw-buffers.R). This requires
RNGkind(c("Mersenne-Twister", "Inversion")) — R’s default —
and errors if .Random.seed is not the expected 626-element
Mersenne-Twister state vector (e.g. if RNGkind() was
changed). Every other Pocock-Simon/bootstrap function in the package
uses the one-draw-seeded independent-RRng pattern instead,
specifically so that it does not need to make this assumption
about .Random.seed’s internal shape.
Seed-reproducible via per-draw local generators:
DesignFixedGreedyDOptimal
Historical note: the two classes this design merges
(DesignFixedAOptimal/DesignFixedDOptimal)
originally seeded their exchange-search kernels’ initial random shuffles
from std::random_device (hardware entropy), which made
their draws genuinely not reproducible via seed. The RNG
migration (see the SEXP-removal spec’s RNG section) replaced that with
one edi_rng::RRng generator per logical draw, derived from
a master seed taken from R’s own stream (R::unif_rand())
inside
d_optimal_search_cpp()/a_optimal_search_cpp(),
and the merged DesignFixedGreedyDOptimal class inherits
that behavior: repeated calls with the same seed
return identical allocations (verified empirically in
test-greedy-d-optimal-merged.R, and reflected in the
seed_reproducible_draw registry field). Because
randomization-based inference
(compute_rand_two_sided_pval(),
compute_rand_confidence_interval()) generates its reference
distribution by calling the design’s own
draw_ws_according_to_design() (see below), randomization
p-values/CIs against this design are exactly reproducible with
seed set, like every other design’s.
Seed-reproducible despite being parallel: greedy-family designs
DesignFixedGreedy,
DesignFixedMatchingGreedyPairSwitching,
DesignFixedGreedyDOptimal, and
DesignFixedRerandomization run candidate searches in
parallel via OpenMP. Each call first takes one master seed from R’s
stream, then derives an edi_rng::RRng stream from the
candidate’s logical draw index. private$maybe_set_seed()
therefore governs the result, while OpenMP only changes which worker
computes a candidate. The returned allocations are identical at every
set_num_cores() setting. Rerandomization evaluates
fixed-size waves and retains the first accepted draw indices, so it also
remains deterministic while stopping after a bounded amount of extra
work.
Randomization inference reuses the design’s own draw mechanism
InferenceRand’s generate_permutations(r)
does not implement its own permutation-drawing logic; it duplicates the
design object (des_obj$duplicate()) and calls that
duplicate’s draw_ws_according_to_design(r) — the exact same
entry point assign_w_to_all_subjects() uses.
Consequences:
-
Seeding. The permutations are drawn under an
effective seed: the inference object’s
set_seed()(or constructorseed) if set, otherwise the design’s ownseed. The draw runs inside a save/restore of the caller’s.Random.seed, so a randomization p-value or CI is reproducible given that seed whatever the global RNG state was, and the call leaves the caller’s RNG stream untouched. (The duplicated design itself has no seed, so before this was wired in the draws came from whatever the global stream held at the first call.) With neither seed set the draws come from the global stream at the first call, as before. Because the effective seed is set right before the duplicate draws, this holds for sequential designs as well as fixed ones: a randomization p-value on a sequential trial does not depend on where the global stream was when the trial ended. -
Draw reuse / caching: the generated permutation
matrix is cached on the design, keyed on
r, the effective seed and a stable signature of the design’s structural parameters (class,n,prob_T,m,strata_cols). A second call for the samerand seed against a structurally-identical design reuses the cached matrix rather than drawing again – so, for example, computing both a randomization p-value and a randomization confidence interval (which internally makes several p-value evaluations at differentdelta) against the same object draws the reference permutation set once. Inference objects with different seeds on one design no longer share draws. Callinference$clear_randomization_cache()to drop the design’s cached permutations and force a redraw. -
Custom permutations.
permutations = list(w_mat = <n x r numeric 0/1 matrix>, m_mat = NULL)can be passed to the randomization methods to supply the draws directly (bypassing both the draw and the cache). -
Caveat. Calling
draw_ws_according_to_design()yourself on a seeded fixed design runsmaybe_set_seed(), i.e.set.seed()on the global RNG, and does not restore it, so it overwrites the caller’s stream. On a seeded sequential design the same call runs under a seed derived from the design’s seed and restores the caller’s stream; on an unseeded sequential design it draws from, and advances, the caller’s stream.
An inference object’s own seed
set_seed() on an inference object (or its constructor’s
seed) governs that object’s resampling: the randomization
draws above and the bootstrap. Each such call sets the seed inside a
save/restore of the caller’s .Random.seed, so the result is
the same whatever the global state was, and the caller’s stream is left
exactly as it was. This is the same for fixed and sequential designs.
Compare runs at the same num_cores setting. Without an
inference seed, the bootstrap draws from the global stream (so
set.seed() before the call reproduces it), and an inference
object reuses its own bootstrap distribution on later calls with the
same B instead of drawing again.
saved$design$add_all_subject_responses(rnorm(n))
inf = InferenceAllSimpleMeanDiffPooledVar$new(saved$design, verbose = FALSE)
inf$set_seed(3)
p_first = inf$compute_rand_two_sided_pval(r = 199, show_progress = FALSE)
ci_first = inf$compute_bootstrap_confidence_interval(B = 499, type = "percentile",
show_progress = FALSE)
# A fresh object with the same seed, after unrelated random-number use.
invisible(runif(10))
stream_before = .Random.seed
inf2 = InferenceAllSimpleMeanDiffPooledVar$new(saved$design, verbose = FALSE)
inf2$set_seed(3)
inf2$clear_randomization_cache() # force a fresh draw of the permutations
identical(p_first, inf2$compute_rand_two_sided_pval(r = 199, show_progress = FALSE))
#> [1] TRUE
identical(ci_first, inf2$compute_bootstrap_confidence_interval(B = 499, type = "percentile",
show_progress = FALSE))
#> [1] TRUE
identical(stream_before, .Random.seed) # the caller's stream was not touched
#> [1] TRUEBootstrap resampling
-
Non-parametric bootstrap: the default fallback is
sample.int(n, n, replace = TRUE)— plain R-level sampling, governed by R’s ambient RNG state /set.seed()exactly like any base-R code. Block/pair/cluster-structured designs instead calldes_obj$draw_bootstrap_indices(bootstrap_type), which for most designs routes to the one-draw-seedededi_rng::RRngC++ backends described above (draw_matching_bootstrap_sample_cpp,stratified_bootstrap_indices_cpp,resample_group_rows_cpp) — reproducible viaset.seed()acting on R’s stream at the point the one seeding draw is taken. -
Bayesian bootstrap: weights are drawn as
stats::rgamma(length(idx), shape = 1, rate = 1), one Gamma(1,1) draw per exchangeable resampling unit (subject or block), which is the standard construction of Dirichlet\((1,\dots,1)\) weights (a Dirichlet draw is a Gamma\((1,1)\) vector normalized to sum to the unit count — seevignette("notation-glossary")’s “Resampling and randomization” section). This is plain R-levelrgamma(), governed by R’s ambient RNG state. -
Parametric bootstrap / warm-start / factorization
reuse: several inference classes cache a factorization or
warm-start state across bootstrap replicates purely for speed
(see
get_warm_start_dispatch_policy()/set_warm_start_dispatch_policy()); this caching does not change which random draws are made, only how fast each replicate’s model fit converges.
Machine-dependent performance defaults:
tune_EDI_for_this_machine()
Every performance-policy default mentioned above — whether an
inference class’s C++ backend uses a smart_cold_start OLS
warm-up or a plain zero start, whether resampling reuses a previous
replicate’s warm start (and at what sample size that stops paying off),
which optimizer algorithm a family uses by default, and at what sample
size parallel bootstrapping starts to beat serial execution — was
measured empirically on the maintainer’s machine. These are
speed judgments, not statistical ones: core count, cache sizes,
and BLAS backend all affect which setting wins, so a default that is
net-positive on the maintainer’s machine can be net-negative on yours,
and vice versa.
tune_EDI_for_this_machine() re-runs those same
benchmarks on your own hardware, keeps only the settings that win by a
real margin (median improvement past a noise threshold, not any
transient win), and persists the result to a per-user config file that
every subsequent library(EDI) re-applies automatically.
This does not weaken anything this vignette documents: tuning never
changes which random draws are made or which
estimate/CI a fit produces — only how fast it gets there. Concretely,
every accepted change is re-fit once under both settings before being
kept, and any disagreement in the result discards that change rather
than applying it (the same “measure, don’t assume” discipline this
vignette applies to RNG behavior, applied here to timing behavior). The
one axis with a partial exception is the parallel/core-count benchmark
itself, since forked workers draw from an independent RNG stream by
construction — that axis compares the (core-count-invariant) point
estimate instead of the resampling distribution, for exactly the reason
a bootstrap CI is expected to differ across independent Monte
Carlo draws.
To see what has been tuned on your machine, call
get_local_EDI_optimization(); to discard it and return to
the shipped defaults, call clear_local_EDI_optimization().
Setting EDI_SKIP_LOCAL_TUNING=1 (e.g. before
library(EDI)) skips the automatic import for one session
without deleting the saved file — useful when isolating whether a saved
tuning is responsible for an observed timing difference.
Simulation (SimulationFramework): per-replication and
per-cache-job seeds
SimulationFramework$new(seed = ...) does
not rely on a single global set.seed()
call covering the entire run. At the top of run(), if
seed is non-NULL, R’s
.Random.seed is saved (to be restored via
on.exit() when run() returns, so a simulation
run never leaks RNG state into the caller’s session) and
set.seed(private$seed) is called once — but the more
important mechanism is per-unit deterministic seed
derivation:
- Each replication
i(within aw-rep loop) is dispatched withrep_seed = seed + i, and the worker executing that replication callsset.seed(rep_seed)itself before drawing anything. - Each cache-building job (pre-generating the design/SE caches used
across replications) is dispatched with
cache_seed = seed + 1000003L + job_idx— a large additive offset specifically chosen so the cache-job seed range and the replication seed range do not collide for any realisticNrep_W/ cell count.
Why this matters for parallel execution: because
every unit of work carries its own explicit seed and calls
set.seed() itself, the ambient RNG state of whichever
worker process executes it is irrelevant — this is what makes a
SimulationFramework run reproducible regardless of
num_cores, regardless of whether the fork-cluster or
mirai-daemon backend is used, and regardless of the order
in which the scheduler happens to dispatch replications/cache
jobs across workers. Each saved on-disk cache record
additionally stores the RNG state present right after that cache object
was built (rng_after); restore_rng (default
FALSE on cache loads) controls whether a cache
hit replays that saved state into the current session.
Since a cache hit skips the computation that would have consumed that
randomness anyway, leaving restore_rng = FALSE is the
correct default — cache hits are RNG-inert (they neither consume nor
need to replay randomness), while a cache miss (an
actual fresh .run_simulation_cache_job() call) still
explicitly seeds itself via the same
seed + 1000003L + job_idx derivation as any other cache
job.
Consequence: a SimulationFramework
run’s results are reproducible across separate run()
invocations with the same seed and the same
(design_classes_and_params, inference_classes_and_params, n, p, betaT, ...)
configuration. (Historically this carried an exception for the two
pre-merge optimal-design classes, whose kernels were not seeded from R’s
stream; since the RNG migration and the
DesignFixedGreedyDOptimal merge, no such exception
exists.)
Monte Carlo error
None of B_boot, r_rand, or
Nrep_W/Nrep_Y_w has a closed-form “this value
is large enough” answer baked into the package — larger values reduce
simulation noise at the cost of runtime, and the right value is
estimand/design-specific. Rules of thumb used elsewhere in statistics
apply directly here:
- A randomization or bootstrap p-value built from
r/Bdraws has Monte Carlo standard error on the order of \(\sqrt{\hat p (1-\hat p) / r}\) (treating “did this draw’s statistic exceed the observed one” as a Bernoulli(\(\hat p\)) indicator) — e.g.r= 999 gives a Monte Carlo SE of roughly \(0.016\) at \(\hat p \approx 0.5\), tighter near the tails that usually matter for a decision at \(\alpha = 0.05\). - A bootstrap confidence interval’s endpoints
(percentile or BCa) are themselves noisy quantile estimates from
Bdraws; their Monte Carlo error shrinks roughly like \(O(1/\sqrt{B})\), but unlike the p-value case there is no single clean formula — the standard practical guidance is to re-run with a different seed and confirm the interval doesn’t move appreciably before trusting aB_bootchoice for a final reported result. - A
SimulationFrameworkoperating characteristic (MSE,coverage,power/sizeinSimulationFrameworkReport$summarize()) is itself a Monte Carlo estimate overNrep_W * Nrep_Y_wreplications;coverage_pval/size_pval(exact two-sided binomial test p-values against the nominal \(1-\alpha\)/\(\alpha\) target) are provided specifically so a large enoughNrep_Wcan be chosen to distinguish “genuinely miscalibrated” from “within Monte Carlo noise of nominal” rather than eyeballing a point estimate.
Reproducing a documented example
To exactly reproduce a design allocation, bootstrap replicate, or simulation run shown in this package’s own examples/vignettes/published comparisons:
- Use the same R version and the default
RNGkind()(c("Mersenne-Twister", "Inversion", "Rejection")) — the portableedi_rng::RRngreimplementation andpocock_simon_redraw_w_cpp’s live-stream continuation both assume the Mersenne-Twister + Inversion normal-sampling kind specifically. - Pass an explicit
seedto theDesign/SimulationFrameworkconstructor (andset_seed()on inference objects) rather than relying on ambient RNG state. For fixed and seeded sequential designs that is enough (a seeded sequential design also continues exactly after a reload). A sequential design withseed = NULLdraws from the global stream, so reproducing it needs the same random-number use before each assignment, and a design reloaded from disk needs its saved.Random.seedrestored (see above). - For parallel
SimulationFrameworkruns,num_coresand the fork/miraibackend choice do not need to match the original run for reproducibility (per-unit seed derivation makes them irrelevant) — onlyseedand the simulation configuration do.
