Statistics tutorial · Chapter 12

Simulation

38 min read · 6 sections

The analyses in the Analysis › Simulate menu build data from a model that you set, and then let you repeat the experiment as many times as needed. Random XY Data produces curves (Y as a function of X, plus a random error), Random Groups produces groups of values, Random 2×2 Table draws a 2×2 table according to one of three study designs; Monte Carlo Simulation repeats a simulation and the analysis of its data hundreds or thousands of times, then summarizes the results obtained. Because the truth is known (you chose it), you can measure what a method really does: the power of a test, its type I error rate when its assumptions are not met, the coverage of a confidence interval, the bias and precision of an estimate. The notions of type I and type II error, power and confidence interval are presented in chapter 10; the tests and fits repeated in the examples are covered in chapters 14, 15 and 17.


Common principles#

Random number generator#

All four analyses use the same pseudo-random generator, xoshiro256** (Blackman and Vigna, 2021): a 256-bit state, initialized from the seed by the SplitMix64 algorithm (Steele, Lea and Flood, 2014), produces a sequence of 64-bit numbers entirely determined by the seed. The distributions used are derived from it as follows:

uniform U         u = (k + 0.5) / 2⁵³, k = the 53 high-order bits of the number drawn
                  (0 < u < 1: never exactly 0 or 1)
normal Z          Marsaglia polar method: u, v uniform on ]−1; 1[, s = u² + v²,
                  start over while s ≥ 1; z₁ = u·√(−2·ln s / s), z₂ = v·√(−2·ln s / s)
                  (z₂ is kept for the next call)
chi-square χ²(ν)  2 × Gamma(ν/2), gamma variable drawn by the Marsaglia and Tsang method
Student T(ν)      Z / √(χ²(ν) / ν)
Cauchy C          tan(π·(U − 0.5))
Poisson(λ)        λ < 30: the smallest k such that U₁·U₂·…·U(k+1) ≤ e^(−λ)
                  λ ≥ 30: PTRS transformed rejection (Hörmann, 1993)
binomial(n, p)    number of successes whose rank, a sum of geometric waiting times,
                  stays ≤ n (Devroye, 1986); if p > 0.5: n − Bin(n, 1 − p)

The polar method is a variant of the Box-Muller transform (1958) that avoids computing sines and cosines. A pseudo-random generator is deterministic: with the same version of Variance, the same seed gives exactly the same numbers, which makes a simulation reproducible.

Seeds and reproducibility#

Each analysis in the family has a "Random seed" option:

  • 0** (default): automatic seed. Variance draws one when the analysis is created and keeps it with the analysis: changing the parameters does not change the numbers drawn. **Run Simulation Again (Shift+F9; Analysis menu, ribbon, or the Run Simulation Again button of the results sheet) draws a new seed, hence new data, and the analyses that depend on it are recomputed. The three data simulations do not display this seed: you will not be able to cite it.
  • An integer ≥ 1: fixed seed. The data are identical at every computation, even after Run Simulation Again.

Two simulations started with the same seed draw the same random numbers: in this chapter, the first normal deviate of seed 1 is 1.884, whether it is added to a curve or to a group of values. Comparing two scenarios with the same seed ("common random numbers") isolates the effect of the parameters; in return, the two results are not independent.

Error models#

Random XY Data and Random Groups share the Random error tab. For each value, μ is the true value (Y given by the equation, or the group mean) and σ is the number entered in "SD (or % for relative error, scale for Cauchy)" (1 by default); Z is a standard normal variable.

"Random error"Simulated valueMean and spread of the simulated value
Gaussian (absolute SD) (default)μ + σ·Zmean μ, SD σ
Gaussian (relative, % of Y)μ + μ·(σ/100)·Zmean μ, SD equal to σ% of the absolute value of μ (constant coefficient of variation)
Double Gaussian (5% of points with 10× SD)μ + σ·Z, or μ + 10σ·Z with probability 0.05mean μ, SD σ·√(0.95 + 0.05 × 100) = 2.44σ
Poissoninteger drawn from a Poisson distribution with parameter max(μ, 0); σ is ignoredmean μ, SD √μ
t distributionμ + σ·T(ν), ν = "Degrees of freedom (t distribution)" (3 by default, at least 1)mean μ if ν > 1; SD σ·√(ν / (ν − 2)) if ν > 2, infinite otherwise
Lorentzian (Cauchy)μ + σ·Cneither mean nor SD; median μ, quartiles μ − σ and μ + σ
No random errorμno spread

For the t distribution, σ is therefore a scale factor and not the standard deviation: with 3 degrees of freedom, the SD is 1.73σ. "Fraction of outliers (%)" (0 by default) adds outliers: each value, independently of the others and with a probability equal to this percentage, is shifted by ±10 × max(SD of the point, 0.1·|μ|), the sign being drawn by a coin flip; the SD of the point is σ, or |μ|·σ/100 with relative error, or √μ with Poisson. A non-finite value (equation undefined for some X, for example) is left empty.

Good practice#

  • Fix the seed and report it, together with the number of simulations, all the parameters (distributions, means, SDs, sample sizes) and the Variance version: this is what makes a simulation verifiable by others.
  • Give the Monte Carlo error: a proportion estimated over N simulations has a standard error √(p(1 − p)/N), and Variance displays its 95% confidence interval. 1,000 simulations give an order of magnitude (± 2.5 points around 80%), not enough to distinguish 94% from 95%.
  • Compute power before the study, for the smallest effect size judged important (scientifically or clinically) and a realistic variability, never with the effect observed after the fact: "observed power" is merely a transformation of the P value (chapter 10; Hoenig and Heisey, 2001).
  • A simulation is only as good as its assumptions: error distribution, SD, independence of observations, design, sample size actually analyzable (losses to follow-up, exclusions). Simulate several plausible scenarios (larger SD, skewed distribution, outliers) and report them all.
  • Check a case with a known answer first: under the null hypothesis, with data that satisfy the assumptions of the test, the fraction of P < 0.05 should be close to 0.05; with normal data, the 95% CI of a mean should contain the true value 95% of the time. Morris, White and Crowther (2019) propose a framework for describing a simulation study: aims, data-generating mechanism, estimand, methods compared, performance measures.

Random XY Data#

Random XY Data creates an XY table whose Y values follow a chosen equation, with parameter values set by you, plus a random error: a series of X values, one or more data sets, one or more replicates per X. Because the true parameters are known, you can check that a fit recovers them and, with Monte Carlo Simulation, how precisely a given experimental design (number and position of the X values, replicates) allows them to be estimated.

When to use it#

  • Planning a dose-response or kinetic experiment: how many X values, over what range, how many replicates to estimate K, an EC50 or a half-life with the desired precision (chapter 17).
  • Checking that a fitting method (weighting, outlier detection, model comparison) behaves well with the expected error model.
  • Teaching or testing: data whose truth is known.
  • Not for completing real data or replacing missing measurements.

Assumptions and checks#

The simulated model assumes:

  • independent errors: each point, each replicate and each data set receives its own error; replicates are therefore not repeated measurements on the same subject (no subject effect, no correlation);
  • the same error distribution everywhere, except for relative error (SD proportional to Y) and the Poisson distribution (variance equal to Y);
  • exact X values: no error is added to the X values;
  • the same parameters for all data sets: the data sets "Simulated A", "Simulated B"… differ only by the noise.

Before using a simulation, compare it with real or pilot data: same curve shape, same spread (Sy.x of a fit), same relationship between spread and level of Y (constant or proportional). Also reread the parameter values displayed in the Simulate tab.

Step by step in Variance#

  1. Make any table active: the simulation reads the table only if you ask it for its X values. Choose Analysis › Simulate › Random XY Data.
  2. X values tab:
    • "X values": "Generate a series" (default) or "Use the X values of the input table" (the X values of the active table, rows without X ignored; if the table has no X column, the series is generated without warning);
    • "Starting X" (0), "Increment" (1) and "Number of X values" (10, from 1 to 100,000) define the series.
  3. Y values tab:
    • "Equation": an equation from the library (chapter 17) or an equation saved in the project; "Exponential decay, one phase" by default;
    • "Custom equation": a typed equation (same syntax as in chapter 17); if this field is not empty, it replaces the equation chosen in the list;
    • "Parameter values": one line per parameter, "Name = value" (by default "Y0 = 100", "Plateau = 10", "K = 0.3"). Names are not case-sensitive; the value can be a constant expression ("ln(2)/2") and is written with a decimal point. A missing parameter takes the value 1 (a warning reports it), and a name that is not a parameter of the equation is rejected with a message;
    • "Number of data sets" (1, from 1 to 100) and "Replicates per X" (1, from 1 to 100).
  4. Random error tab: distribution, SD, degrees of freedom, fraction of outliers and seed (see "Error models" above).
  5. OK. Variance creates the results sheet "Random XY Data of …" and an XY graph of the simulated points.
  6. To analyze the simulated data, keep this results sheet (or its graph) active and choose the analysis, for example Analysis › Curves and Regression › Nonlinear Regression; you can also use Analyze These Results on the ⊞ "Simulated data" tab. Run Simulation Again (Shift+F9) then draws new data and the fit is redone.

Calculations#

X(i)        = x₀ + i·Δx                 i = 0, …, n − 1
              (x₀: "Starting X", Δx: "Increment", n: "Number of X values")
              or the X values of the input table
μ(i)        = f(X(i); θ)                θ: values of "Parameter values" (1 if missing)
Y(i, j, k)  = μ(i) + error              j: data set, k: replicate

The error follows the distribution chosen in "Random error" (table of error models). The random numbers are consumed data set by data set, then X by X, then replicate by replicate: changing the number of data sets or replicates therefore changes the values drawn for the following points. The default equation:

Exponential decay, one phase
   Y = (Y0 − Plateau)·exp(−K·X) + Plateau
   Y0: value at X = 0; Plateau: limiting value; K: rate constant
   half-life = ln 2 / K; time constant Tau = 1 / K

Reading the results#

The Simulate tab recalls the model: "Equation" (name of the equation, or "Custom equation"), "X values" (number of X values), "Data sets", "Replicates", then one line per parameter with the value actually used: this is where a misspelled name is spotted (value 1). The ⊞ "Simulated data" output table is an XY table: the X values, then one data set per simulation ("Simulated A", "Simulated B"…) with one subcolumn per replicate.

Worked example#

Keep all the default settings ("Exponential decay, one phase", Y0 = 100, Plateau = 10, K = 0.3, X from 0 to 9, Gaussian error with SD 1) and set "Random seed" to 1. The simulated Y values depart from the true curve μ = 90·exp(−0.3·X) + 10 by normal deviations with SD 1:

X     μ (true)    Simulated Y    deviation
0     100.000     101.884        +1.884
1      76.674      76.863        +0.190
2      59.393      59.831        +0.438
3      46.591      45.799        −0.792
4      37.107      38.190        +1.083
5      30.082      30.234        +0.153
6      24.877      25.381        +0.505
7      21.021      21.218        +0.197
8      18.165      17.328        −0.837
9      16.048      16.031        −0.017

Fit these data with Nonlinear Regression and the "Exponential decay, one phase" equation (other options at their defaults). Variance displays, among other things:

Fitted parameters
Y0                              101.5
Plateau                         10.25
K                               0.3055
HalfLife                        2.269
Std. Error
K                               0.008185
95% CI (profile likelihood)
K                               0.2862 to 0.3253
HalfLife                        2.131 to 2.422
Goodness of Fit
R squared                       0.9995
Sy.x                            0.7184

The fit recovers the true values (K = 0.3; half-life = ln 2 / 0.3 = 2.310), both within their confidence intervals. A single data set says nothing about the precision of the design, however: repeat the experiment 1,000 times with Monte Carlo Simulation (details in the section devoted to it): "Number of simulations" 1000, "Random seed" 1, "Results to tabulate" "K; HalfLife", and clear "Count a simulation when the result" (no counting). The Summary tab gives:

            Mean      SD        2.5th percentile    Median    97.5th percentile    N
K           0.2992    0.01129   0.2769              0.2991    0.3228               1000
HalfLife    2.32      0.08794   2.147               2.318     2.503                1000

With this design, K is estimated without noticeable bias: the mean of the 1,000 estimates (0.2992) departs from 0.3 by 0.0008, about two Monte Carlo errors (0.01129 / √1000 = 0.00036), which is negligible compared with the spread. Its standard deviation (0.0113, or 3.8% of K) measures the expected precision, and 95% of the estimates fall between 0.277 and 0.323. The half-life, a nonlinear function of K, is slightly overestimated on average (2.320 versus 2.310, i.e. + 0.4%): this is the expected effect of the curvature of ln 2 / K. To compare designs, change the X values of the simulation (for example 20 values spaced by 0.5): the Monte Carlo simulation is recomputed with the same seed.

Reporting the results#

"Data were simulated (Variance, Random XY Data) according to Y = (Y0 − Plateau)·exp(−K·X) + Plateau, with Y0 = 100, Plateau = 10 and K = 0.3, for X = 0 to 9 (step of 1, one measurement per X) and a Gaussian error with SD 1 (seed 1). Over 1,000 simulated data sets (seed 1), nonlinear regression estimated K at 0.299 on average (standard deviation 0.011; 95% of the estimates between 0.277 and 0.323)."

Common pitfalls#

  • Misspelled parameter name: "Platau = 10" is rejected with a message that lists the parameters of the equation; an omitted parameter equals 1, and a warning reports it.
  • Decimal comma in "Parameter values": write "K = 0.3".
  • t distribution: the SD field is a scale factor; the actual SD is σ·√(ν / (ν − 2)).
  • Relative error near Y = 0: the SD, proportional to Y, becomes almost zero; for negative Y, it applies to the absolute value.
  • Poisson: the SD field is ignored and a negative Y gives 0; reserve this distribution for counts.
  • Replicates mistaken for repeated measurements: they are independent; there is no subject effect.
  • Automatic seed: without a fixed seed, the data change at every Run Simulation Again and the seed used is displayed nowhere.

Random Groups#

Random Groups creates a One factor table of several groups ("Group A", "Group B"…), each with the same number of values: each value is the mean of its group plus a random error drawn according to one of the error models. It is the basic building block for studying by simulation the power of a group comparison (t test, ANOVA, nonparametric tests), the behavior of a test when the errors are not normal, or the coverage of the confidence interval of a mean.

When to use it#

  • Computing before the study the power, or the required sample size, of a group comparison (with Monte Carlo Simulation).
  • Studying a test when the errors are not normal: heavy tails ("t distribution", "Lorentzian (Cauchy)"), contamination ("Double Gaussian", "Fraction of outliers (%)"), counts ("Poisson").
  • Checking the coverage of the CI of a mean.
  • Limits: all groups have the same sample size and the same error model, with the same σ. The SDs differ from one group to another only if they depend on the mean (relative error, Poisson): with equal means, the variances are therefore equal, and the classic scenario "unequal variances under the null hypothesis" (Welch versus Student, chapter 14) cannot be simulated. No paired data, no skewed continuous distribution (log-normal).

Assumptions and checks#

The simulated model is Y = μ(group) + error, all errors being independent. The rows therefore have no meaning: the 3rd value of group A and the 3rd of group B are not linked, and a paired test on these data would find no pairing. The target effect size is computed with the true SD of the model (table of error models): d = (μB − μA) / σ for the absolute Gaussian error, but the SD is 2.44σ for "Double Gaussian" and 1.73σ for the t distribution with 3 degrees of freedom. Compare the spread and shape of the simulated data with those of pilot data (Descriptive Statistics, graph of individual values).

Step by step in Variance#

  1. Make any table active (its content is not read) and choose Analysis › Simulate › Random Groups.
  2. Data tab:
    • "Number of data sets" (3 by default, from 1 to 100) and "Values per data set" (10, from 1 to 100,000);
    • "Means" ("10, 12, 15"): one mean per group, separated by commas or spaces, reused in order if there are fewer than groups (with 4 groups and "10, 12, 15", group D receives 10). With decimal commas, separate the means with semicolons: "10,5; 20" gives 10.5 and 20.
  3. Random error tab: see "Error models".
  4. OK. Variance creates the results sheet "Random Groups of …" and a graph of the individual values of each group.
  5. Analyze the simulated data by keeping this sheet active, for example with Analysis › Compare Groups › Two-Group Comparisons (which by default compares the first two groups, chapter 14) or One-Way ANOVA.

Calculations#

Y(g, i) = μ(g) + error         g: group (A, B, …), i = 1, …, n ("Values per data set")
μ(g)    = the g-th number of "Means", going back to the start of the list when it is exhausted

The values are drawn group by group: all of group A, then all of group B, and so on. The error follows the chosen model; "Fraction of outliers (%)" then adds the outliers described above.

Reading the results#

The Simulate tab contains only "Data sets" and "Values per data set"; the means and the error model are reread in the parameters (Settings…, Ctrl+Shift+A). The ⊞ "Simulated data" output table is a One factor table with one data set per group.

Worked example#

What the error models generate. A single group of 100,000 values, "Means" 10, σ = 2, seed 7; Descriptive Statistics applied to each simulation gives (rounded values):

"Random error"                 mean        SD          expected SD
Gaussian (absolute SD)         10.001      1.996       2
Gaussian (relative, % of Y)    10.000      0.1996      0.2 (2% of 10)
Double Gaussian                 9.990      4.863       4.879 (2.44 × 2)
Poisson                        10.004      3.170       3.162 (√10; σ ignored)
t distribution (3 df)          10.021      3.488       3.464 (2 × √3)
Lorentzian (Cauchy)             8.796    433.5         none

For the Cauchy distribution, the sample mean and SD estimate nothing: a few extreme values (from −64,090 to +52,156 here) dominate them. The median (9.99) and the interquartile range (3.98), on the other hand, recover the center 10 and the distance 2σ = 4 between the quartiles.

Two small groups. Set "Number of data sets" 2, "Values per data set" 5, "Means" "10, 15", SD 10 and seed 1: the true difference is 5, half an SD (d = 0.5). Variance draws:

Group A    28.844    11.898    14.383     2.077    20.829     mean 15.61
Group B    16.525    20.045    16.971     6.630    14.828     mean 15.00

The unpaired t test (Two-Group Comparisons, default options) gives P = 0.9067 (t = −0.121, 8 df) and a 95% CI of the difference B − A from −12.17 to 10.95: with 5 values per group, the sample even reverses the direction of the true difference. This is not an anomaly: the power of this design is only 11% (exact computation by the noncentral t distribution). The Monte Carlo Simulation section shows how to estimate it by simulation and choose the sample size.

Reporting the results#

"Two groups of 64 values were simulated (Variance, Random Groups): means 10 and 15, Gaussian error with SD 10 (d = 0.5), seed 1." Always state the error model, the true SD when the SD field is not one (t distribution, Double Gaussian) and the seed.

Common pitfalls#

  • Decimal comma in "Means": without a semicolon in the list, the comma separates two means ("10,5" gives 10 and 5).
  • Reused means: with fewer means than groups, the list starts over from the beginning without warning.
  • σ is not always the SD: the effect size d = Δ / SD must use the true SD of the model (t distribution, Double Gaussian); for the Cauchy distribution, the "means" are centers (medians) and a test comparing means has no defined object.
  • Groups of the same size and the same σ: it is impossible to simulate unequal sample sizes, or unequal SDs with equal means.
  • No pairing: the rows do not link the groups; a paired test on these data makes no sense.
  • Poisson: the SD field is ignored; "Means" are the λ parameters (≥ 0).

Random 2×2 Table#

Random 2×2 Table draws a 2×2 table of counts, with rows "Exposed / treated" and "Control" and columns "Outcome" and "No outcome", by binomial draws that respect one of three study designs: each fixes different totals. It is used to estimate the power of a comparison of two proportions (Fisher's exact test, chi-square) and the actual error rate of these tests on small sample sizes.

When to use it#

  • Before a trial, a cohort or a case-control study: power of the planned test for the expected proportions and the envisaged sample size.
  • Finding the actual type I error rate of Fisher's exact test or the chi-square test (with or without Yates correction) for a small sample size.
  • Teaching what each design fixes and the effect measures that make sense in it: relative risk in a prospective design, odds ratio in a case-control design (chapter 15).

Assumptions and checks#

  • Independent subjects, with the same probability within a group: no clusters (several patients from the same ward), no heterogeneity that would create overdispersion.
  • Prospective or experimental design: the row totals are fixed (n₁ exposed or treated, n₂ controls); the number of events follows a binomial distribution with probability p₁ or p₂.
  • Case-control design: the column totals are fixed (n₁ cases in "Outcome", n₂ controls in "No outcome"); the number of exposed subjects follows a binomial distribution with probability p₁ among the cases and p₂ among the controls. p₁ and p₂ are then exposure probabilities.
  • Cross-sectional design: only the total N = n₁ + n₂ is fixed; each subject falls in row 1 with the probability "Cross-sectional: probability of being in row 1", then has the event with the probability p₁ or p₂ of its row.

The probabilities should come from the literature or a pilot study, not from the hoped-for result, and the simulated design must be that of the planned study.

Step by step in Variance#

  1. Make any table active and choose Analysis › Simulate › Random 2×2 Table.
  2. Design tab:
    • "Design": "Prospective / experimental (fixed row totals)" (default), "Case-control (fixed column totals)" or "Cross-sectional (fixed grand total)";
    • "Subjects in row 1 (or column 1)" and "Subjects in row 2 (or column 2)" (100 and 100);
    • "Probability of outcome in row 1 (or exposure in column 1)" (0.3) and "Probability of outcome in row 2 (or exposure in column 2)" (0.15);
    • "Cross-sectional: probability of being in row 1" (0.5), used by the cross-sectional design only;
    • "Random seed" (0 = automatic seed).
  3. OK. Variance creates the results sheet "Random 2×2 Table of …", without a graph.
  4. Keep this sheet active and choose Analysis › Compare Groups › Contingency Table Tests (chapter 15): for a 2×2 table, the default test is Fisher's exact test.

Calculations#

                        Outcome    No outcome
Exposed / treated          a           b
Control                    c           d

Prospective      a ~ Bin(n₁, p₁)    b = n₁ − a      c ~ Bin(n₂, p₂)    d = n₂ − c
Case-control     a ~ Bin(n₁, p₁)    c = n₁ − a      b ~ Bin(n₂, p₂)    d = n₂ − b
Cross-sectional  N = n₁ + n₂ ;  r₁ ~ Bin(N, π)     (π: probability of being in row 1)
                 a ~ Bin(r₁, p₁)    b = r₁ − a      c ~ Bin(N − r₁, p₂)    d = N − r₁ − c

The first two designs draw their two binomials in the same order: with the same seed, they give the same two counts, placed differently. For planning, the true effect measures are deduced from the probabilities: in a prospective design, relative risk RR = p₁ / p₂ (2 with the default values) and odds ratio OR = [p₁ / (1 − p₁)] / [p₂ / (1 − p₂)] (2.43); in a case-control design, the exposure odds ratio computed in the same way is also the disease odds ratio, but the relative risk cannot be estimated.

Reading the results#

The Simulate tab displays "Design" (the label of the chosen design) and "Total subjects" (always n₁ + n₂). The ⊞ "Simulated contingency table" output table is a contingency table ready to be analyzed.

Worked example#

With the default settings (prospective design, 100 subjects per row, probabilities 0.30 and 0.15) and seed 1, Variance draws:

                        Outcome    No outcome
Exposed / treated          30          70
Control                    13          87

The two-sided Fisher's exact test gives P = 0.0055, and the relative risk is 2.308 (95% CI: 1.281 to 4.158), an interval that contains the true value 2. With the same seed, the case-control design gives 30 exposed among 100 cases and 13 among 100 controls (columns 30/70 and 13/87), and the cross-sectional design 28/81 and 17/74 (109 subjects in the first row, 91 in the second).

Power. Analyze the table with Contingency Table Tests (Fisher's test by default), then run Monte Carlo Simulation on the simulation sheet (next section) with 10,000 simulations, seed 1 and the default counting ("P value" < 0.05). "Proportion meeting the criterion" is 0.668 ("95% CI of the proportion (Wilson score)": 0.6587 to 0.6772); the exact enumeration of the 101 × 101 possible tables gives 0.669. With only 1,000 simulations, one gets 0.633 (0.6027 to 0.6623): this interval misses the true value, which happens to a 95% CI once in twenty, and is a reminder to take enough simulations. The uncorrected chi-square ("Test": "Chi-square") is more powerful here: 0.731 (0.7222 to 0.7396; exact value 0.729).

Type I error rate on small sample sizes. Take 20 subjects per row and two equal probabilities (null hypothesis true), and repeat each of the three tests 10,000 times (seed 1):

p₁ = p₂, 20 per row            Fisher             Chi-square         Chi-square (Yates)
0.30 (expected counts 6)       0.0238 (0.0248)    0.0532 (0.0533)    0.0203 (0.0214)
0.10 (expected counts 2)       0.0122 (0.0118)    0.0390 (0.0387)    0.0046 (0.0041)

In parentheses, the exact values obtained by enumeration: the Monte Carlo estimates depart from them by less than two standard errors. Fisher's "exact" test and the Yates correction are conservative: their actual type I error risk is 0.4 to 2.5% for a nominal level of 5%, which is paid for in power. The uncorrected chi-square stays close to 5% or below here, even with expected counts of 2, below the usual rule (at least 5). This result holds for these designs: simulate your own before drawing a rule from it.

Reporting the results#

"Power was estimated by simulation (Variance, Random 2×2 Table and Monte Carlo Simulation, 10,000 tables, seed 1): with 100 patients per arm and risks of 30% and 15%, the two-sided Fisher's exact test at the 5% level would have a power of 66.8% (95% CI: 65.9 to 67.7%)."

Common pitfalls#

  • Meaning of the parameters depends on the design: in case-control, "row 1" and "row 2" become the columns (cases, controls) and the probabilities are exposure probabilities.
  • Cross-sectional design: only the sum n₁ + n₂ matters; the split between rows depends on "Cross-sectional: probability of being in row 1".
  • Relative risk in case-control: the analysis computes it by default, but it is meaningless; choose "Odds ratio" in "Effect size (2×2)".
  • Clustered data: several patients per center or repeated measurements create an overdispersion that the simulation ignores; the real power would be lower.
  • "Exact" does not mean "of exact level": Fisher's test computes its conditional P value exactly, but its actual type I error rate is below the chosen level.
  • Forgetting that the Monte Carlo follows the repeated analysis: changing its options (one-sided test, another test…) restarts the N simulations; with many simulations, this takes time.

Monte Carlo Simulation#

Monte Carlo Simulation repeats the same simulated experiment N times: at each round, it draws a new data set with the parameters of an existing simulation sheet, applies to it an existing analysis with exactly the same options, and records the requested results. It summarizes their distribution (mean, SD, percentiles) and counts the hits, that is, the simulations in which a result meets a condition (for example "P value" < 0.05), with the confidence interval of that fraction. Depending on the simulated scenario, the proportion meeting the criterion estimates a power (alternative hypothesis true), a type I error rate (null hypothesis true) or, through the duality between a test and a confidence interval, the complement of a coverage rate.

When to use it#

  • Power, or required sample size, of any test for any design, without a formula: before the study, for the smallest effect size judged important.
  • Actual type I error rate of a test when its assumptions are not met (non-normal distribution, outliers, small sample sizes).
  • Coverage of a confidence interval.
  • Bias and precision of an estimate (K, EC50, mean…) for a given design (example of Random XY Data).
  • Not for computing after the study an "observed power" from the observed effect: it brings nothing more than the P value (chapter 10; Hoenig and Heisey, 2001).

Assumptions and checks#

  • The conclusions hold only for the simulated scenario: error distribution, SD, effect, sample sizes, design and analysis. Vary the uncertain assumptions (sensitivity analysis).
  • The simulations must succeed: a simulation whose analysis fails (a fit that does not converge, a group without variance) is discarded, and the results then concern only the successful simulations. Check "Simulations failed" and "Simulations with that result".
  • The Monte Carlo error must be small compared with the difference you care about: read the CI of the proportion meeting the criterion and increase N if needed.
  • Control: start with a scenario whose answer is known (null hypothesis true, assumptions of the test met); the fraction of P < 0.05 should be compatible with 0.05.

Step by step in Variance#

  1. Create the simulation of the scenario (Random XY Data, Random Groups or Random 2×2 Table).
  2. With the simulation sheet active, run the analysis to repeat with its final options (for example Two-Group Comparisons).
  3. Go back to the simulation's results sheet (or to its graph) and choose Analysis › Simulate › Monte Carlo Simulation. Started from another sheet, or without an analysis of the simulated data, it stops on a message that says so.
  4. Simulations tab: "Number of simulations" (1000 by default, from 1 to 1,000,000) and "Random seed" (0 = automatic seed, renewed by Run Simulation Again; otherwise an integer from 1 to 2⁴⁰ ≈ 1.1 × 10¹²).
  5. Values to collect tab:
    • "Analysis to repeat": name of the results sheet of the analysis to repeat, as it appears in the navigator (case-insensitive); empty = the first analysis of the simulated data in the project;
    • "Results to tabulate": row labels of the results, separated by ";" (case-insensitive); empty = all the numeric values of the first results tab (24 at most).
  6. Criterion tab: "Count a simulation when the result" (title of a row, "P value" by default; empty = no counting), "is" (<, ≤, > or ≥) and "than" (0.05).
  7. Options tab: significant digits and P value format displayed.
  8. OK. Each simulation redoes the whole analysis: start with 1,000 simulations, especially for a nonlinear regression. No graph is created; to see the distribution of a result, use Plot These Results or Analyze These Results (for example Frequency Distribution) on the ⊞ "Tabulated values" tab.

The Monte Carlo simulation is recomputed when its parameters, those of the simulation or those of the repeated analysis change.

Calculations#

s = "Random seed" (or the automatic seed if 0), reduced modulo 2⁴⁰
for k = 1, 2, …, N:
    data(k)     = the simulation, with its parameters and the seed s + k
    results(k)  = the repeated analysis, with its options, applied to data(k)
    on error: simulation counted in "Simulations failed"
    otherwise: each tabulated result is recorded; if the "Count a simulation when the result" row exists
               with a numeric value, M = M + 1, and H = H + 1 if the condition is true

Proportion meeting criterion  p̂ = H / M
95% CI (Wilson)               center     = (p̂ + z²/(2M)) / (1 + z²/M)
                              half-width = z / (1 + z²/M) × √[ p̂(1 − p̂)/M + z²/(4M²) ]
                              z = 1.95996; bounds brought back into [0; 1]
Summary (m values)            mean, SD (denominator m − 1), percentiles 2.5, 50 and 97.5, N = m
percentile p                  h = (m + 1)·p; x(⌊h⌋) + (h − ⌊h⌋)·[x(⌊h⌋ + 1) − x(⌊h⌋)]
                              (x(1) ≤ … ≤ x(m); minimum if h ≤ 1, maximum if h ≥ m)

The simulation sheet's own seed is ignored: the Monte Carlo simulation imposes s + k. "First random seed" displays s + 1; without failures, row r of "Tabulated values" therefore comes from seed s + r, and entering this seed in the simulation sheet reproduces that data set (handy for examining an atypical result). Two consequences:

  • neighboring seeds give almost the same study: seeds s and s + 1 share N − 1 data sets (seed 1: 809 simulations out of 1,000 meet the criterion in example 1; seed 2: 810). For independent repetitions, choose seeds more than N apart;
  • two scenarios run with the same seed use the same random numbers, which makes their comparison more precise, without making them independent.

The interval is the Wilson score interval (1927), recommended by Brown, Cai and DasGupta (2001); it is always 95%. The Monte Carlo standard error of a proportion is √(p(1 − p)/N), hence the 95% half-widths (≈ 1.96 standard errors):

              N = 1,000    N = 10,000    N = 100,000
p = 0.05      ± 0.0135     ± 0.0043      ± 0.0014
p = 0.80      ± 0.0248     ± 0.0078      ± 0.0025
p = 0.95      ± 0.0135     ± 0.0043      ± 0.0014

For a half-width h, N ≈ 1.96² × p(1 − p) / h² simulations are needed: 6,146 for a power of about 80% to ± 1 point, 7,299 for a risk of about 5% to ± 0.5 point. For a tabulated mean, the Monte Carlo error is SD / √m. The 2.5th and 97.5th percentiles rest on the 25 most extreme values out of 1,000: they require more simulations.

Reading the results#

  • Summary tab: one row per tabulated result, titled like the original row (followed by the column title in parentheses when that row has several numeric columns); columns "Mean", "SD", "2.5th percentile", "Median", "97.5th percentile" and "N" (number of simulations where the value was numeric); "no value" if it never was.
  • Criterion tab: "Criterion" (for example "P value < 0.05"), "Simulations with that result" (M), "Simulations meeting the criterion" (H), "Proportion meeting the criterion" and "95% CI of the proportion (Wilson score)". If the row was never found: "Simulations with that result" is 0, with a "Note" row.
  • Simulations tab: "Simulation repeated", "Analysis repeated", "Simulations requested", "Simulations completed", "Simulations failed", "First random seed" and, if there was a failure, "First failure" (its message).
  • ⊞ Tabulated values table: one data set per tabulated result, one row per successful simulation.

Only numeric cells (numbers, P values, integers) are tabulated: text rows ("P value tails", "Difference significant at α = 0.05") and intervals ("95% CI") are ignored. A title present in several tabs is tabulated once per tab, with the tab name in square brackets: for a t test, "Results to tabulate" = "P value" gives "P value [Results]", that of the test, and "P value [Residuals]", that of the D'Agostino-Pearson normality test of the residuals. The hit always uses the first row bearing that title, here the P value of the t test.

Worked example#

1. Power of a t test. Let us take the scenario of chapter 10: two groups, a difference of 5 for an SD of 10 (d = 0.5), two-sided test at α = 0.05, 64 subjects per group.

  1. Random Groups: "Number of data sets" 2, "Values per data set" 64, "Means" "10, 15", "Gaussian (absolute SD)", SD 10, seed 1.
  2. Two-Group Comparisons on these data, default options (unpaired, equal SDs, two-sided).
  3. Monte Carlo Simulation: 1000 simulations, seed 1, other options at their defaults.
Summary                       Mean      SD       2.5th percentile   Median     97.5th percentile   N
P value                       0.04375   0.1097   2.421e-6           0.005085   0.3936              1000
Mean of column A (Group A)    10.01     1.214    7.762              9.988      12.38               1000
Mean of column B (Group B)    15.05     1.262    12.66              15.04      17.5                1000

Criterion
Criterion                                P value < 0.05
Simulations with that result             1000
Simulations meeting the criterion        809
Proportion meeting the criterion         0.809
95% CI of the proportion (Wilson score)  0.7835 to 0.8322

The estimated power is 80.9% (95% CI: 78.3 to 83.2%). Checking the interval: z² = 3.8415, center = (0.809 + 0.00192) / 1.00384 = 0.8078, half-width = 1.9525 × √(0.809 × 0.191 / 1000 + 0.00000096) = 1.9525 × 0.01247 = 0.0243, that is 0.7835 to 0.8322. The exact computation by the noncentral t distribution (126 df, noncentrality parameter 0.5 × √32 = 2.828, critical value 1.979) gives 0.8015, within the interval. With 10,000 simulations (same seed, hence the same first 1,000 data sets), one obtains 0.7944 (0.7864 to 0.8022); with 20 subjects per group, 0.355 (0.3259 to 0.3852) for an exact value of 0.338. To choose the sample size, repeat with several n and keep the smallest one that reaches the target power, increasing N near the target.

2. Type I error rate when normality is not met. Replace the error with "Double Gaussian (5% of points with 10× SD)" (SD 10), take "Means" "10, 10" (null hypothesis true) and 10 or 64 values per group; compare the t test and the Mann-Whitney test ("Distribution of the data": "Not Gaussian: nonparametric test"), with 10,000 simulations and seed 1. The last column takes "Means" "10, 15" again:

                                   H0 true (10 and 10)       H1 (10 and 15)
Error             Test             n = 10      n = 64        n = 64
Gaussian          t                0.0488      0.0528        0.7944
                  Mann-Whitney     0.0425      0.0511        0.7783
Double Gaussian   t                0.0304      0.0379        0.2842
                  Mann-Whitney     0.0424      0.0490        0.7071

The Monte Carlo error is about ± 0.004 near 0.05 and ± 0.009 for the powers. With normal errors, both tests respect their level (the exact Mann-Whitney is a little below 5% for n = 10, its distribution being discrete). With contamination, the t test does not reject too often: it becomes conservative (3.0 to 3.8%). But its power collapses (28% instead of 79%), because the outliers multiply the SD by 2.44, whereas the Mann-Whitney keeps its level and most of its power (71%). With Cauchy errors ("Lorentzian (Cauchy)"), the contrast is extreme: under H0, the t test rejects in 1.9 to 2.1% of the simulations; under H1 (means 10 and 15, scale 5, n = 64), its power is 7.7% against 82.1% for the Mann-Whitney. A test can therefore keep an acceptable type I risk and still be a poor choice: it is its power in realistic scenarios that decides. Other departures, such as unequal variances with unequal sample sizes or non-independent observations, on the contrary push the rate above 5%; Random Groups cannot simulate them (sample size and σ common to all groups, independent values).

3. Coverage of a confidence interval. The 95% CI of a mean excludes a value μ₀ exactly when the one-sample t test of μ₀ (two-sided) gives P < 0.05. The proportion of simulations meeting the criterion, for the test of the true mean, is therefore the non-coverage rate.

  1. Random Groups: 1 data set of 10 values, "Means" "10", "Gaussian (absolute SD)", SD 2, seed 1.
  2. One-Sample Tests (Options tab): "Test" "One sample t test", "Hypothetical value" 10, confidence level 95%.
  3. Monte Carlo Simulation: 10,000 simulations, seed 1, criterion "P value" < 0.05.

One obtains 492 simulations out of 10,000 that meet the criterion: "Proportion meeting the criterion" 0.0492 (0.04513 to 0.05361), a coverage of 95.1% (94.6 to 95.5%), as expected for normal data. With counts ("Means" "1", "Random error" "Poisson", "Hypothetical value" 1), "Simulations with that result" is 9,998: two samples in which all the values were equal have no P value. The fraction is 0.05951 (0.05504 to 0.06432): coverage falls to 94.0% (93.6 to 94.5%), a small but clear deficit for these very skewed data with n = 10. With 1,000 simulations, the normal case gives 0.052 (0.03987 to 0.06756), a coverage between 93.2 and 96.0%: such a one-point deficit would have gone unnoticed.

Reporting the results#

"Power was estimated by Monte Carlo simulation (Variance, 10,000 simulations, seed 1): for two groups of 64 subjects drawn from normal populations, a difference of 5 units and a standard deviation of 10 (d = 0.5), the two-sided unpaired t test at the 5% level would have a power of 79.4% (95% CI: 78.6 to 80.2%)." Describe the scenario fully (distribution, parameters, sample sizes, analysis and options), the number of simulations, the seed and the Monte Carlo CI.

Common pitfalls#

  • "Observed power": computing it after the study with the observed effect brings nothing; power is computed beforehand, for an effect judged important.
  • Too few simulations: 1,000 simulations give ± 2.5 points around 80%; always report the CI of the fraction.
  • Neighboring seeds: seeds 1 and 2 share 999 data sets out of 1,000; they are not two independent repetitions.
  • Two "P value" columns: when tabulating "P value" for a t test, the second column is the P value of the normality test of the residuals; leave "Results to tabulate" empty or choose rows with a unique title.
  • Empty "Analysis to repeat" when several analyses concern the simulated data: the first one created is repeated; check "Analysis repeated".
  • Discarded simulations: failures ("Simulations failed") and missing results ("Simulations with that result" < N) make the results conditional on the successful simulations.
  • Criterion row not found: with nonlinear regression, the default "P value" row does not exist; "Simulations with that result" is 0 and a "Note" reports it. Clear the field or choose an existing row.
  • Intervals cannot be tabulated: for a coverage, go through the duality with a test, as in example 3.
  • Direction of the condition: "<" excludes equality, and the criterion concerns the P value as displayed (one-sided if the analysis is).

References#

Books:

  • Cohen J. Statistical Power Analysis for the Behavioral Sciences, 2nd ed. Lawrence Erlbaum Associates, 1988.
  • Devroye L. Non-Uniform Random Variate Generation. Springer, 1986.
  • Knuth DE. The Art of Computer Programming, vol. 2: Seminumerical Algorithms, 3rd ed. Addison-Wesley, 1997.

Articles:

  • Blackman D, Vigna S. Scrambled linear pseudorandom number generators. ACM Transactions on Mathematical Software 2021;47(4):36.
  • Box GEP, Muller ME. A note on the generation of random normal deviates. The Annals of Mathematical Statistics 1958;29:610-611.
  • Brown LD, Cai TT, DasGupta A. Interval estimation for a binomial proportion. Statistical Science 2001;16:101-133.
  • Hoenig JM, Heisey DM. The abuse of power: the pervasive fallacy of power calculations for data analysis. The American Statistician 2001;55:19-24.
  • Hörmann W. The transformed rejection method for generating Poisson random variables. Insurance: Mathematics and Economics 1993;12:39-45.
  • Hyndman RJ, Fan Y. Sample quantiles in statistical packages. The American Statistician 1996;50:361-365.
  • Marsaglia G, Bray TA. A convenient method for generating normal variables. SIAM Review 1964;6:260-264.
  • Marsaglia G, Tsang WW. A simple method for generating gamma variables. ACM Transactions on Mathematical Software 2000;26:363-372.
  • Morris TP, White IR, Crowther MJ. Using simulation studies to evaluate statistical methods. Statistics in Medicine 2019;38:2074-2102.
  • Steele GL, Lea D, Flood CH. Fast splittable pseudorandom number generators. ACM SIGPLAN Notices 2014;49(10):453-472.
  • Tukey JW. A survey of sampling from contaminated distributions. In: Olkin I et al. (eds.), Contributions to Probability and Statistics. Stanford University Press, 1960:448-485.
  • Wilson EB. Probable inference, the law of succession, and statistical inference. Journal of the American Statistical Association 1927;22:209-212.