| Title: | Generate Spatially Efficient Experimental Designs |
|---|---|
| Description: | The Speed package optimises spatial experimental designs by rearranging treatments to improve statistical efficiency while maintaining statistical validity. It employs customisable optimisation metrics, with a default approach that balances minimising treatment adjacency and maintaining spatial balance. Users can supply their own optimisation metrics to tailor designs to specific experimental requirements. The package also includes visualisation tools that allow users to inspect optimised designs. |
| Authors: | Sam Rogers [aut, cre], Wasin Pipattungsakul [aut], Julian Taylor [aut], University of Adelaide [cph, fnd] (https://adelaide.edu.au/), Grains Research and Development Corporation [cph, fnd] (https://grdc.com.au/) |
| Maintainer: | Sam Rogers <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.11 |
| Built: | 2026-12-03 11:25:10 UTC |
| Source: | https://github.com/biometryhub/speed |
Add buffers to an existing design
add_buffers(design_obj, type)add_buffers(design_obj, type)
design_obj |
A design object (with class "design") from the design() function |
type |
The type of buffer to add |
The modified design object with buffers added
Generate plots for designs generated in speed
autoplot(object, ...) ## S3 method for class 'design' autoplot( object, rotation = 0, size = 4, margin = FALSE, palette = "default", row = NULL, column = NULL, block = NULL, treatments = NULL, legend = FALSE, ... )autoplot(object, ...) ## S3 method for class 'design' autoplot( object, rotation = 0, size = 4, margin = FALSE, palette = "default", row = NULL, column = NULL, block = NULL, treatments = NULL, legend = FALSE, ... )
object |
An experimental design object generated from |
... |
Arguments passed to methods. |
rotation |
Rotate the x axis labels and the treatment group labels within the plot. Allows for easier reading of long axis or treatment labels. Number between 0 and 360 (inclusive) - default 0 |
size |
Increase or decrease the text size within the plot for treatment labels. Numeric with default value of 4. |
margin |
Logical (default |
palette |
A string specifying the colour scheme to use for plotting or a vector of custom colours to use as the palette. Default is equivalent to "Spectral". Colour blind friendly palettes can also be provided via options |
row |
A variable to plot a column from |
column |
A variable to plot a column from |
block |
A variable to plot a column from |
treatments |
A variable to plot a column from |
legend |
Logical (default |
A ggplot2 object.
# Create a design with blocks df <- data.frame( row = rep(1:6, each = 4), col = rep(1:4, times = 6), treatment = rep(LETTERS[1:8], 3), block = rep(1:3, each = 8)) # Optimise while respecting blocks result <- speed(df, "treatment", swap_within = "block", seed = 42) # Plot the design with block boundaries autoplot(result) # Show legend autoplot(result, legend = TRUE) # Colour blind friendly colours autoplot(result, palette = "colour-blind") # Alternative colour scheme autoplot(result, palette = "plasma") # Custom colour palette autoplot(result, palette = c("#ef746a", "#3fbfc5", "#81ae00", "#c37cff", "#304702", "#dde024", "#630380ff", "#df7700"))# Create a design with blocks df <- data.frame( row = rep(1:6, each = 4), col = rep(1:4, times = 6), treatment = rep(LETTERS[1:8], 3), block = rep(1:3, each = 8)) # Optimise while respecting blocks result <- speed(df, "treatment", swap_within = "block", seed = 42) # Plot the design with block boundaries autoplot(result) # Show legend autoplot(result, legend = TRUE) # Colour blind friendly colours autoplot(result, palette = "colour-blind") # Alternative colour scheme autoplot(result, palette = "plasma") # Custom colour palette autoplot(result, palette = c("#ef746a", "#3fbfc5", "#81ae00", "#c37cff", "#304702", "#dde024", "#630380ff", "#df7700"))
Counts adjacent plots, immediate horizontal and vertical neighbours by default, that share the same treatment. Lower scores indicate better separation. The distance of plots to be considered adjacent can be adjusted with arguments provided.
Identity matches are counted per item with adjacency_neighbours();
a relationship is scored with adjacency_score_vec().
Pass a relationship matrix to score neighbour pairs by a graded
similarity (e.g. genetic relatedness) instead of a strict identity match.
calculate_adjacency_score( layout_df, swap, row_column = "row", col_column = "col", ring_dists = 1, ring_weights = 1, ring_type = c("manhattan", "chebyshev"), relationship = NULL, by = NULL, grid_index = NULL )calculate_adjacency_score( layout_df, swap, row_column = "row", col_column = "col", ring_dists = 1, ring_weights = 1, ring_type = c("manhattan", "chebyshev"), relationship = NULL, by = NULL, grid_index = NULL )
layout_df |
A data frame containing the design. |
swap |
Column name of the treatments to be scored. |
row_column |
Name of the column representing rows (default |
col_column |
Name of the column representing columns
(default |
ring_dists |
A vector of positive integers, ring radii to score over.
(default |
ring_weights |
Per-ring weights aligned with |
ring_type |
Ring shape: |
relationship |
Optional pairwise-relationship lookup produced by
|
by |
Optional column name grouping plots into separate grids (e.g.
|
grid_index |
Optional pre-built list of indices from |
A non-negative numeric value: the number of same-treatment edges in the row/column adjacency graph.
# Example 1: design with no same-treatment adjacencies design_no_adj <- data.frame( row = c(1, 1, 1, 2, 2, 2, 3, 3, 3), col = c(1, 2, 3, 1, 2, 3, 1, 2, 3), treatment = c("A", "B", "A", "B", "A", "B", "A", "B", "A") ) calculate_adjacency_score(design_no_adj, "treatment") # 0 # Example 2: design with adjacencies design_with_adj <- data.frame( row = c(1, 1, 1, 2, 2, 2, 3, 3, 3), col = c(1, 2, 3, 1, 2, 3, 1, 2, 3), treatment = c("A", "A", "A", "B", "B", "B", "A", "A", "A") ) calculate_adjacency_score(design_with_adj, "treatment") # 6 # Example 3: graded relationship between A and B rel <- prep_relationship(matrix( c(1, 0.3, 0.3, 1), nrow = 2, dimnames = list(c("A", "B"), c("A", "B")) )) calculate_adjacency_score(design_no_adj, "treatment", relationship = rel) # 3.6: each of the 12 A-B edges contributes 0.3# Example 1: design with no same-treatment adjacencies design_no_adj <- data.frame( row = c(1, 1, 1, 2, 2, 2, 3, 3, 3), col = c(1, 2, 3, 1, 2, 3, 1, 2, 3), treatment = c("A", "B", "A", "B", "A", "B", "A", "B", "A") ) calculate_adjacency_score(design_no_adj, "treatment") # 0 # Example 2: design with adjacencies design_with_adj <- data.frame( row = c(1, 1, 1, 2, 2, 2, 3, 3, 3), col = c(1, 2, 3, 1, 2, 3, 1, 2, 3), treatment = c("A", "A", "A", "B", "B", "B", "A", "A", "A") ) calculate_adjacency_score(design_with_adj, "treatment") # 6 # Example 3: graded relationship between A and B rel <- prep_relationship(matrix( c(1, 0.3, 0.3, 1), nrow = 2, dimnames = list(c("A", "B"), c("A", "B")) )) calculate_adjacency_score(design_no_adj, "treatment", relationship = rel) # 3.6: each of the 12 A-B edges contributes 0.3
Calculates a balance score that measures how evenly treatments are distributed across spatial factors in an experimental design. Lower scores indicate better balance.
calculate_balance_score(layout_df, swap, spatial_cols)calculate_balance_score(layout_df, swap, spatial_cols)
layout_df |
A data frame representing the current design |
swap |
A column name of the items to be swapped |
spatial_cols |
Column name(s) of the spatial factors |
Numeric value representing the total balance score. Lower values indicate better balance of treatments across spatial factors.
layout_df <- data.frame( row = rep(1:3, each = 3), col = rep(1:3, times = 3), treatment = rep(letters[1:3], 3) ) calculate_balance_score(layout_df, "treatment", c("row", "col"))layout_df <- data.frame( row = rep(1:3, each = 3), col = rep(1:3, times = 3), treatment = rep(letters[1:3], 3) ) calculate_balance_score(layout_df, "treatment", c("row", "col"))
A metric that represents the even distribution of each item with their minimum spanning tree (mst).
calculate_ed(design_matrix, current_ed = NULL, swapped_items = NULL)calculate_ed(design_matrix, current_ed = NULL, swapped_items = NULL)
design_matrix |
A matrix representing the design |
current_ed |
Named list of the current ed calculation |
swapped_items |
The items that had just been swapped |
Named list containing:
- Named list containing:
msts - Named list of items and their mst
min_mst - The lowest mst
min_items - Pairs of items with the lowest mst
design_matrix <- matrix(c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrow = 3, ncol = 3) calculate_ed(design_matrix)design_matrix <- matrix(c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrow = 3, ncol = 3) calculate_ed(design_matrix)
Calculates an efficiency factor of a design according to Piepho 2015.
calculate_efficiency_factor( design_df, item, row_column = "row", col_column = "col" )calculate_efficiency_factor( design_df, item, row_column = "row", col_column = "col" )
design_df |
A data frame containing the experimental design with spatial coordinates |
item |
A column name of the items in the design (e.g., |
row_column |
Name of the column giving the row of the design (default: "row") |
col_column |
Name of the column giving the column of the design (default: "col") |
A numeric value representing the efficiency factor of the design, between 0 and 1. Higher values indicate more efficient designs.
Errors with a speed_efficiency_rank condition if the design cannot support
the estimate - that is, if some treatment contrast is not estimable once row
and column effects are eliminated, whether because too few residual degrees
of freedom remain or because a treatment is confounded with a row or column.
Such a design has no efficiency factor; before this check the formula
returned a plausible-looking value, usually above 1.
Piepho, H. P., Williams, E., & Michel, V. (2015). Nonresolvable Row-Column Designs with an Even Distribution of Treatment Replications. Journal of Agricultural, Biological, and Environmental Statistics, 21, 227-242 (2016). https://doi.org/10.1007/s13253-015-0241-2
# `initialise_design_df()` fills `items` down columns, so the literal below is # column-major; the grid it produces is # a b d c # e a f b # c f e d df_design <- initialise_design_df(c( "a", "e", "c", "b", "a", "f", "d", "f", "e", "c", "b", "d" ), 3, 4) calculate_efficiency_factor(df_design, "treatment") # Not every design can support the estimate. Here each treatment fills one # grid row, so the treatment differences cannot be separated from the row # effects and there is no efficiency factor to report: # a a a a # b b b b # c c c c confounded <- initialise_design_df(rep(c("a", "b", "c"), 4), 3, 4) try(calculate_efficiency_factor(confounded, "treatment"))# `initialise_design_df()` fills `items` down columns, so the literal below is # column-major; the grid it produces is # a b d c # e a f b # c f e d df_design <- initialise_design_df(c( "a", "e", "c", "b", "a", "f", "d", "f", "e", "c", "b", "d" ), 3, 4) calculate_efficiency_factor(df_design, "treatment") # Not every design can support the estimate. Here each treatment fills one # grid row, so the treatment differences cannot be separated from the row # effects and there is no efficiency factor to report: # a a a a # b b b b # c c c c confounded <- initialise_design_df(rep(c("a", "b", "c"), 4), 3, 4) try(calculate_efficiency_factor(confounded, "treatment"))
A metric that counts the occurrence of the same adjacent pairs. Only horizontal and vertical pairs are counted.
calculate_nb(design_matrix, pair_mapping = NULL)calculate_nb(design_matrix, pair_mapping = NULL)
design_matrix |
A matrix representing the design |
pair_mapping |
A named vector of pairs generated from create_pair_mapping |
Named list containing:
nb - Table of pairs of items and their number of occurrence
max_nb - The highest number of occurrence
max_pairs - Vector of pairs of items with the highest number of occurrence
design_matrix <- matrix(c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrow = 3, ncol = 3) calculate_nb(design_matrix)design_matrix <- matrix(c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrow = 3, ncol = 3) calculate_nb(design_matrix)
Create an item pair mapping for calculate_nb.
create_pair_mapping(items)create_pair_mapping(items)
items |
Vector of items for the design |
Named vector of item pairs as a character separated by ",":
"<item 2>,<item 1>" - "<item 1>,<item 2>"
"<item 3>,<item 1>" - "<item 1>,<item 3>"
...
"
"
"<item 3>,<item 2>" - "<item 2>,<item 3>"
"<item 4>,<item 2>" - "<item 2>,<item 4>"
...
"
"
...
"
"<item 1>,<item 1>" - "<item 1>,<item 1>"
"<item 2>,<item 2>" - "<item 2>,<item 2>"
...
"
"
treatments <- c(rep(1:10, 4), rep(11:16, 3), rep(17:27, 2)) create_pair_mapping(treatments)treatments <- c(rep(1:10, 4), rep(11:16, 3), rep(17:27, 2)) create_pair_mapping(treatments)
Calculate the weight of edges from vertices.
get_edges(vertices)get_edges(vertices)
vertices |
Named list of vertices containing:
|
Named list containing:
- A vector of edge weights
design_matrix <- matrix(c(1, 2, 2, 1, 3, 2, 1, 3, 3), nrow = 3, ncol = 3) vertices <- get_vertices(design_matrix) edges <- get_edges(vertices)design_matrix <- matrix(c(1, 2, 2, 1, 3, 2, 1, 3, 3), nrow = 3, ncol = 3) vertices <- get_vertices(design_matrix) edges <- get_edges(vertices)
Get the vertices of each item in a design matrix.
get_vertices(design_matrix)get_vertices(design_matrix)
design_matrix |
A matrix representing the design |
Named list containing:
- A list of (vertex 1, vertex 2, ...)
design_matrix <- matrix(c(1, 2, 2, 1, 3, 2, 1, 3, 3), nrow = 3, ncol = 3) vertices <- get_vertices(design_matrix)design_matrix <- matrix(c(1, 2, 2, 1, 3, 2, 1, 3, 3), nrow = 3, ncol = 3) vertices <- get_vertices(design_matrix)
Initialise a design data frame with or without blocking.
initialise_design_df( items = NULL, nrows = NULL, ncols = NULL, block_nrows = NULL, block_ncols = NULL, splits = NULL, designs = NULL, design_col = "site" ) initialize_design_df( items = NULL, nrows = NULL, ncols = NULL, block_nrows = NULL, block_ncols = NULL, splits = NULL, designs = NULL, design_col = "site" )initialise_design_df( items = NULL, nrows = NULL, ncols = NULL, block_nrows = NULL, block_ncols = NULL, splits = NULL, designs = NULL, design_col = "site" ) initialize_design_df( items = NULL, nrows = NULL, ncols = NULL, block_nrows = NULL, block_ncols = NULL, splits = NULL, designs = NULL, design_col = "site" )
items |
Items to be placed in the design. Either a single numeric value
(the number of equally replicated items), or a vector of items. (default:
|
nrows |
Number of rows in the design (default: |
ncols |
Number of columns in the design (default: |
block_nrows |
Number of rows in each block (default: |
block_ncols |
Number of columns in each block (default: |
splits |
Deprecated; use |
designs |
A list of named arguments describing design specifications,
required if |
design_col |
A column name to distinguish different designs (default:
|
A data frame containing the design
initialise_design_df( items = c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrows = 3, ncols = 3 ) # blocking initialise_design_df(rep(1:8, 4), 8, 4, 2, 2) # another blocking example initialise_design_df( items = paste0("T", 1:6), nrows = 4, ncols = 6, block_nrows = 2, block_ncols = 3 ) # MET initialise_design_df( items = c(rep(1:10, 6), rep(11:20, 8)), designs = list( a = list(nrows = 10, ncols = 3), b = list(nrows = 10, ncols = 5), c = list(nrows = 10, ncols = 6) ) ) # MET with different items for each site initialise_design_df( designs = list( a = list(items = 1:30, nrows = 10, ncols = 6), b = list(items = 1:25, nrows = 10, ncols = 5), c = list(items = 16:30, nrows = 10, ncols = 3) ) )initialise_design_df( items = c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrows = 3, ncols = 3 ) # blocking initialise_design_df(rep(1:8, 4), 8, 4, 2, 2) # another blocking example initialise_design_df( items = paste0("T", 1:6), nrows = 4, ncols = 6, block_nrows = 2, block_ncols = 3 ) # MET initialise_design_df( items = c(rep(1:10, 6), rep(11:20, 8)), designs = list( a = list(nrows = 10, ncols = 3), b = list(nrows = 10, ncols = 5), c = list(nrows = 10, ncols = 6) ) ) # MET with different items for each site initialise_design_df( designs = list( a = list(items = 1:30, nrows = 10, ncols = 6), b = list(items = 1:25, nrows = 10, ncols = 5), c = list(items = 16:30, nrows = 10, ncols = 3) ) )
Build a split plot design from the ground up, given the nested unit structure and how many times the largest unit is replicated. The field dimensions are derived from the nested structure, and any number of split levels is supported (split-plot, split-split-plot, and so on).
initialise_split_design_df(splits, rep_dim = c(1, 1))initialise_split_design_df(splits, rep_dim = c(1, 1))
splits |
A named list of nested-unit specifications, ordered from the innermost (smallest) level to the outermost (the replicated unit, e.g. the block). Each entry is itself a list with:
|
rep_dim |
Length-2 integer vector |
A data frame with row and col columns plus one ID (and optional
treatment) column per split level.
# split-plot: 4 blocks (2x2) of 3x4 cells; each block holds 3 wholeplots # (1x4, treatments A-C), each wholeplot holds 4 subplots (1x1, treatments a-d) initialise_split_design_df( splits = list( subplot = list(items = letters[1:4]), wholeplot = list(items = LETTERS[1:3], nrows = 1, ncols = 4), block = list(nrows = 3, ncols = 4) ), rep_dim = c(2, 2) ) # split-split-plot: an extra level nested inside the subplot initialise_split_design_df( splits = list( subsubplot = list(items = 1:2), subplot = list(items = letters[1:4], nrows = 1, ncols = 2), wholeplot = list(items = LETTERS[1:3], nrows = 1, ncols = 8), block = list(nrows = 3, ncols = 8) ), rep_dim = c(2, 1) )# split-plot: 4 blocks (2x2) of 3x4 cells; each block holds 3 wholeplots # (1x4, treatments A-C), each wholeplot holds 4 subplots (1x1, treatments a-d) initialise_split_design_df( splits = list( subplot = list(items = letters[1:4]), wholeplot = list(items = LETTERS[1:3], nrows = 1, ncols = 4), block = list(nrows = 3, ncols = 4) ), rep_dim = c(2, 2) ) # split-split-plot: an extra level nested inside the subplot initialise_split_design_df( splits = list( subsubplot = list(items = 1:2), subplot = list(items = letters[1:4], nrows = 1, ncols = 2), wholeplot = list(items = LETTERS[1:3], nrows = 1, ncols = 8), block = list(nrows = 3, ncols = 8) ), rep_dim = c(2, 1) )
Objective Function for Factorial Design Optimization
objective_function_factorial( layout_df, swap, spatial_cols, interaction_weight = 1, main_weight = 1, factorial_separator = "-", ... )objective_function_factorial( layout_df, swap, spatial_cols, interaction_weight = 1, main_weight = 1, factorial_separator = "-", ... )
layout_df |
A data frame representing the current design |
swap |
A column name of the items to be swapped |
spatial_cols |
Column name(s) of the spatial factors |
interaction_weight |
Weight for the balance of interactions (default: 1) |
main_weight |
Weight for the score of main treatments (default: 1) |
factorial_separator |
A character used to separate treatments in the factorial design (default: "-") |
... |
Arguments passed on to
|
treatment_a <- paste0("A", 1:8) treatment_b <- paste0("B", 1:3) treatments <- with(expand.grid(treatment_a, treatment_b), paste(Var1, Var2, sep = "-")) df <- initialise_design_df(treatments, 24, 3, 8, 3) objective_function_factorial(df, "treatment", c("row", "col", "block"))treatment_a <- paste0("A", 1:8) treatment_b <- paste0("B", 1:3) treatments <- with(expand.grid(treatment_a, treatment_b), paste(Var1, Var2, sep = "-")) df <- initialise_design_df(treatments, 24, 3, 8, 3) objective_function_factorial(df, "treatment", c("row", "col", "block"))
Create an objective function including even distribution and neighbor balance introduced by Piepho 2018.
objective_function_piepho( design, swap, spatial_cols, current_score_obj = NULL, swapped_items = NULL, pair_mapping = NULL, row_column = "row", col_column = "col", by = NULL, grid_index = NULL, ... )objective_function_piepho( design, swap, spatial_cols, current_score_obj = NULL, swapped_items = NULL, pair_mapping = NULL, row_column = "row", col_column = "col", by = NULL, grid_index = NULL, ... )
design |
A data frame representing the spatial information of the design |
swap |
A column name of the items to be swapped |
spatial_cols |
Column name(s) of the spatial factors |
current_score_obj |
A named list containing the current score |
swapped_items |
Items swapped after |
pair_mapping |
A named vector of pairs generated from create_pair_mapping |
row_column |
Name of column representing the row of the design (default: "row") |
col_column |
Name of column representing the column of the design (default: "col") |
by, grid_index
|
Optional grouping of plots into separate grids; see
|
... |
Extra parameters passed from speed |
A function which returns a named list of numeric values with one required name score representing
the score of the design (lower is better) with a signature function(design_df, swap, spatial_cols, ...).
An objective may optionally return a components element: a named numeric vector of the additive pieces
that sum to score (e.g. c(adjacency = ..., balance = ...)). When present, summary.design() reports
this as a faithful score decomposition. See signature
details in objective_function_signature.
Piepho, H. P., Michel, V., & Williams, E. (2018). Neighbor balance and evenness of distribution of treatment replications in row-column designs. Biometrical journal. Biometrische Zeitschrift, 60(6), 1172-1189. https://doi.org/10.1002/bimj.201800013
objective_function(), create_pair_mapping()
design_df <- initialise_design_df( items = c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrows = 3, ncols = 3 ) pair_mapping <- create_pair_mapping(design_df$treatment) objective_function_piepho(design_df, "treatment", c("row", "col"), pair_mapping = pair_mapping) # usage in speed, speed(..., obj_function = objective_function_piepho, pair_mapping = pair_mapping)design_df <- initialise_design_df( items = c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrows = 3, ncols = 3 ) pair_mapping <- create_pair_mapping(design_df$treatment) objective_function_piepho(design_df, "treatment", c("row", "col"), pair_mapping = pair_mapping) # usage in speed, speed(..., obj_function = objective_function_piepho, pair_mapping = pair_mapping)
Default Objective Function for Design Optimization
objective_function_signature(layout_df, swap, spatial_cols, ...) objective_function( layout_df, swap, spatial_cols, adj_weight = 1, bal_weight = 1, row_column = "row", col_column = "col", current_score_obj = NULL, swapped_items = NULL, ... )objective_function_signature(layout_df, swap, spatial_cols, ...) objective_function( layout_df, swap, spatial_cols, adj_weight = 1, bal_weight = 1, row_column = "row", col_column = "col", current_score_obj = NULL, swapped_items = NULL, ... )
layout_df |
A data frame representing the current design |
swap |
A column name of the items to be swapped |
spatial_cols |
Column name(s) of the spatial factors |
... |
Extra parameters passed from speed |
adj_weight |
Weight for adjacency score (default: 1) |
bal_weight |
Weight for balance score (default: 1) |
row_column |
Name of column representing the row of the design (default: "row") |
col_column |
Name of column representing the column of the design (default: "col") |
current_score_obj |
Score object of the design before the swap (default: |
swapped_items |
Items swapped after |
A numeric value representing the score of the design (lower is better)
layout_df <- data.frame( row = rep(1:3, each = 3), col = rep(1:3, times = 3), treatment = rep(letters[1:3], 3) ) objective_function(layout_df, "treatment", c("row", "col"))layout_df <- data.frame( row = rep(1:3, each = 3), col = rep(1:3, times = 3), treatment = rep(letters[1:3], 3) ) objective_function(layout_df, "treatment", c("row", "col"))
Create and verify optimization parameters. These parameters are used to control the behaviour of simulated annealing algorithm.
optim_params( swap_count = 1, swap_all_blocks = FALSE, adaptive_swaps = FALSE, start_temp = 100, cooling_rate = 0.99, random_initialisation = 0, adj_weight = NULL, bal_weight = NULL, stop_at_optimal = TRUE )optim_params( swap_count = 1, swap_all_blocks = FALSE, adaptive_swaps = FALSE, start_temp = 100, cooling_rate = 0.99, random_initialisation = 0, adj_weight = NULL, bal_weight = NULL, stop_at_optimal = TRUE )
swap_count |
Number of treatment swaps per iteration (default: 1). |
swap_all_blocks |
Logical; if |
adaptive_swaps |
Logical; if |
start_temp |
Starting temperature for simulated annealing (default: 100). A higher start temperature allows the algorithm to accept worse solutions early on, encouraging exploration of the solution space and helping to avoid local optima. Lower values make the algorithm greedier from the start, which can speed up convergence but increases the risk of getting stuck in a poor solution. A good starting temperature allows moderately worse solutions to be accepted with a probability of 70-90% at the beginning of the optimisation. |
cooling_rate |
Rate at which temperature decreases for simulated annealing (default: 0.99). This
controls how quickly the algorithm shifts from exploration to exploitation. The temperature is updated at
each iteration by multiplying it by this rate: |
random_initialisation |
Number of times to randomly shuffle items within |
adj_weight, bal_weight
|
Deprecated. Weights for the adjacency and balance scores. Pass
them to |
stop_at_optimal |
Logical; if |
A named list of optimization parameters.
speed() for examples
Creates two plots showing the progression of the optimization:
Objective score over iterations
Temperature decay over iterations
plot_progress(result)plot_progress(result)
result |
A list containing the optimization results with the following elements:
|
No return value; prints two ggplot objects showing:
Progress of the objective score
Cooling schedule (temperature decay)
# Create a simple design df <- data.frame( row = rep(1:3, each = 3), col = rep(1:3, times = 3), treatment = rep(LETTERS[1:3], 3) ) # Optimise the design result <- speed(df, "treatment") # Plot optimization progress plot_progress(result)# Create a simple design df <- data.frame( row = rep(1:3, each = 3), col = rep(1:3, times = 3), treatment = rep(LETTERS[1:3], 3) ) # Optimise the design result <- speed(df, "treatment") # Plot optimization progress plot_progress(result)
Validates relationship and packs it into a flat numeric vector plus
row/column level vectors that adjacency_score_vec() can index into in
constant time per cell. speed() calls this once before the SA loop so
the per-iteration cost stays in the lookup itself. Direct callers of
calculate_adjacency_score() must wrap their matrix with this function
before passing - the score functions consume the prepped form only.
prep_relationship(relationship, treatments = NULL)prep_relationship(relationship, treatments = NULL)
relationship |
A numeric matrix with rownames and colnames covering every treatment value to be scored. |
treatments |
Optional character vector of treatment values that
|
A list with flat (column-major flattened matrix), row_levels,
col_levels, and n_row.
Print method for speed design objects
## S3 method for class 'design' print(x, ...)## S3 method for class 'design' print(x, ...)
x |
Design object returned by speed function |
... |
Additional arguments passed to print |
x invisibly
Print method for design summaries
## S3 method for class 'summary.design' print(x, ...)## S3 method for class 'summary.design' print(x, ...)
x |
A |
... |
Unused; for S3 compatibility. |
x invisibly.
Optimises the spatial layout of experimental designs using simulated annealing to minimise treatment adjacency and maintain treatment balance across spatial factors. Works with regular or irregular spatial designs.
speed( data, swap, swap_within = "1", spatial_factors = ~row + col, grid_factors = list(dim1 = "row", dim2 = "col"), iterations = 10000, early_stop_iterations = 2000, obj_function = objective_function, swap_all = FALSE, linked_cols = NULL, optimise = NULL, optimise_params = optim_params(), quiet = FALSE, seed = NULL, ... )speed( data, swap, swap_within = "1", spatial_factors = ~row + col, grid_factors = list(dim1 = "row", dim2 = "col"), iterations = 10000, early_stop_iterations = 2000, obj_function = objective_function, swap_all = FALSE, linked_cols = NULL, optimise = NULL, optimise_params = optim_params(), quiet = FALSE, seed = NULL, ... )
data |
A data frame containing the experimental design with spatial coordinates |
swap |
A column name of the items to be swapped (e.g., |
swap_within |
A string specifying the variable that defines a boundary
within which to swap treatments. Specify |
spatial_factors |
A one-sided formula specifying spatial factors to
consider for balance (default: |
grid_factors |
A named list specifying grid factors to construct a
matrix for calculating adjacency score, An optional third element, |
iterations |
Maximum number of iterations for the simulated annealing
algorithm (default: 10000). For hierarchical designs, can be a named list
with names matching |
early_stop_iterations |
Number of iterations without improvement before
early stopping (default: 2000). For hierarchical designs, can be a named
list with names matching |
obj_function |
Objective function used to calculate score (lower is
better) (default: |
swap_all |
Logical; Whether to swap all matching items or a single item at a time (default: FALSE) |
linked_cols |
Character vector of column names that travel with the
|
optimise |
A list of named arguments describing optimising parameters; see more in example. |
optimise_params |
Parameters used to control the behaviour of
simulated annealing algorithm. See |
quiet |
Logical; if TRUE, suppresses progress messages (default: FALSE) |
seed |
A numeric value for random seed. If provided, it ensures
reproducibility of results (default: |
... |
Other arguments passed to objective functions. For hierarchical
designs, set an |
This function provides a very general interface for producing experimental
designs of different types. For hierarchical designs such as split-plots,
strip plots, split-split plots and similar nested structures, the key
arguments (swap, swap_within, iterations, early_stop_iterations and
obj_function) can be provided as named lists where each name corresponds
to a level in the hierarchy (e.g., "wholeplot", "subplot"). When these
arguments are provided as named lists with matching names, the optimisation
is applied sequentially at each hierarchical level, starting with the first
level and progressing through the hierarchy. This allows for different
optimisation parameters and objective functions to be applied at different
levels of the design structure. For simple (non-hierarchical) designs, these
arguments can be provided as single values. For more examples and detailed
usage, see the package vignettes.
linked_cols names columns that describe the treatment rather than the plot,
so that a value paired with a treatment stays paired with it wherever the
search moves it. They take no part in scoring, and are returned in their
input class and position. Columns used as swap_within, spatial factors or
grid factors cannot be linked, since they describe where a plot is rather
than what is on it.
A named list links different columns at different levels, e.g.
list(wp = "wholeplot_label", sp = "subplot_label"). A bare character vector
applies to every level, which in a hierarchical design is only valid when
every level swaps the same column, as in a multi-environment trial - a column
can only travel with one swap column.
A later level's swap column may be linked to an earlier one, which carries a
child treatment along when its parent moves: linking sp_trt at the
whole-plot level of a split-plot moves each sub-plot treatment with its
whole-plot treatment, before the sub-plot level then optimises it. The
carrying level must come first, or it would undo the child level's work.
On a level with swap_all = TRUE whole treatment groups move at once, so a
linked column with more than one value per treatment travels with its
treatment group rather than being paired plot for plot.
Arguments for the objective function, such as adj_weight, bal_weight or
relationship, can be passed with ..., or set per level with an obj_args
field of a level in optimise, e.g.,
optimise = list(wp = list(..., obj_args = list(adj_weight = 0))).
A level's obj_args override ... argument by argument. Setting
adj_weight and bal_weight through optim_params() is deprecated.
A list containing:
design_df - Data frame of optimised design
score - Final optimisation score
scores - Vector of scores across iterations (for simple designs) or named list of score vectors (for hierarchical designs)
temperatures - Vector of temperatures across iterations
iterations_run - Total number of iterations performed
stopped_early - Logical indicating if optimisation stopped early (for simple designs) or named logical vector (for hierarchical designs)
treatments - Vector of unique treatments (for simple designs) or named list of treatment vectors (for hierarchical designs)
seed - Random seed used for reproducibility of the design. If not set
in the function, the seed is set to the third element of .Random.seed, or
drawn at random if the RNG has not been used yet.
metadata - A list describing how the design was produced: the captured
call, the ordered levels, the resolved row_column / col_column
names, and a per_level list recording each level's swap variable,
spatial factors, adjacency/balance weights, requested iterations, starting
temperature, cooling rate, objective function, achieved score and the
stop_reason that ended the level. Used by
summary() to recompute per-level evaluation metrics.
# Create a simple design with 3 replicates of 4 treatments in a 4x3 layout df <- data.frame( row = rep(1:4, times = 5), col = rep(1:5, each = 4), treatment = rep(LETTERS[1:4], 5) ) # Optimise the design result <- speed(df, swap = "treatment", seed = 42) autoplot(result) # Keep a label column travelling with its treatment df$treatment_name <- paste("Variety", df$treatment) result <- speed(df, swap = "treatment", linked_cols = "treatment_name", seed = 42) head(result$design_df) # Hierarchical split-plot design df_split <- data.frame( row = rep(1:12, each = 4), col = rep(1:4, times = 12), block = rep(1:4, each = 12), wholeplot = rep(1:12, each = 4), wholeplot_treatment = rep(rep(LETTERS[1:3], each = 4), times = 4), subplot_treatment = rep(letters[1:4], 12) ) result <- speed(df_split, swap = list(wp = "wholeplot_treatment", sp = "subplot_treatment"), swap_within = list(wp = "block", sp = "wholeplot"), swap_all = TRUE, seed = 42) # Plot wholeplot allocations within blocks autoplot(result, treatments = "wholeplot_treatment") # Plot subplot allocations within wholeplots autoplot(result, treatments = "subplot_treatment", block = "wholeplot") # Using optimise parameter # Multi-Environment Trial (MET) design # With 7 replicates of 100 lines in this design, each line will appear # twice at two different sites and once at the rest of the sites. lines <- rep(1:100, 7) df_site <- initialise_design_df(1, 28, 5, 14, 5) df_initial <- rbind(df_site, df_site, df_site, df_site, df_site) df_initial$lines <- lines df_initial$site <- rep(c("a", "b", "c", "d", "e"), each = 140) df_initial$site_row <- paste(df_initial$site, df_initial$row, sep = "_") df_initial$site_col <- paste(df_initial$site, df_initial$col, sep = "_") df_initial$site_block <- paste(df_initial$site, df_initial$block, sep = "_") # Low iterations keeps the example quick; raise it for a real design. optimise <- list( connectivity = list( spatial_factors = ~site, iterations = 500, early_stop_iterations = 100 ), balance = list( swap_within = "site", spatial_factors = ~ site_col + site_block, iterations = 500, early_stop_iterations = 100 ) ) result <- speed( data = df_initial, swap = "lines", optimise = optimise, optimise_params = optim_params(random_initialisation = TRUE), adj_weight = 0, seed = 112, quiet = TRUE ) head(table(result$design_df$lines, result$design_df$site)) # Plot the MET design with facets autoplot(result, treatments = "lines") + ggplot2::facet_wrap(~site)# Create a simple design with 3 replicates of 4 treatments in a 4x3 layout df <- data.frame( row = rep(1:4, times = 5), col = rep(1:5, each = 4), treatment = rep(LETTERS[1:4], 5) ) # Optimise the design result <- speed(df, swap = "treatment", seed = 42) autoplot(result) # Keep a label column travelling with its treatment df$treatment_name <- paste("Variety", df$treatment) result <- speed(df, swap = "treatment", linked_cols = "treatment_name", seed = 42) head(result$design_df) # Hierarchical split-plot design df_split <- data.frame( row = rep(1:12, each = 4), col = rep(1:4, times = 12), block = rep(1:4, each = 12), wholeplot = rep(1:12, each = 4), wholeplot_treatment = rep(rep(LETTERS[1:3], each = 4), times = 4), subplot_treatment = rep(letters[1:4], 12) ) result <- speed(df_split, swap = list(wp = "wholeplot_treatment", sp = "subplot_treatment"), swap_within = list(wp = "block", sp = "wholeplot"), swap_all = TRUE, seed = 42) # Plot wholeplot allocations within blocks autoplot(result, treatments = "wholeplot_treatment") # Plot subplot allocations within wholeplots autoplot(result, treatments = "subplot_treatment", block = "wholeplot") # Using optimise parameter # Multi-Environment Trial (MET) design # With 7 replicates of 100 lines in this design, each line will appear # twice at two different sites and once at the rest of the sites. lines <- rep(1:100, 7) df_site <- initialise_design_df(1, 28, 5, 14, 5) df_initial <- rbind(df_site, df_site, df_site, df_site, df_site) df_initial$lines <- lines df_initial$site <- rep(c("a", "b", "c", "d", "e"), each = 140) df_initial$site_row <- paste(df_initial$site, df_initial$row, sep = "_") df_initial$site_col <- paste(df_initial$site, df_initial$col, sep = "_") df_initial$site_block <- paste(df_initial$site, df_initial$block, sep = "_") # Low iterations keeps the example quick; raise it for a real design. optimise <- list( connectivity = list( spatial_factors = ~site, iterations = 500, early_stop_iterations = 100 ), balance = list( swap_within = "site", spatial_factors = ~ site_col + site_block, iterations = 500, early_stop_iterations = 100 ) ) result <- speed( data = df_initial, swap = "lines", optimise = optimise, optimise_params = optim_params(random_initialisation = TRUE), adj_weight = 0, seed = 112, quiet = TRUE ) head(table(result$design_df$lines, result$design_df$site)) # Plot the MET design with facets autoplot(result, treatments = "lines") + ggplot2::facet_wrap(~site)
speed (Deprecated)Deprecated. These options()-based parameters are no longer recommended.
Please use optim_params() instead for a reproducible way to specify optimisation
parameters.
This page describes the options you can set to control the behaviour of the speed
package, especially technical options in the speed() function controlling the
behaviour of the optimisation algorithm.
speed.swap_countNumber of treatment swaps per iteration (default: 1).
speed.swap_all_blocksLogical; if TRUE, performs swaps in all blocks at each iteration (default: FALSE).
speed.adaptive_swapsLogical; if TRUE, adjusts swap parameters based on temperature (default: FALSE).
speed.start_tempStarting temperature for simulated annealing (default: 100). A higher start temperature allows the algorithm to accept worse solutions early on, encouraging exploration of the solution space and helping to avoid local optima. Lower values make the algorithm greedier from the start, which can speed up convergence but increases the risk of getting stuck in a poor solution. A good starting temperature allows moderately worse solutions to be accepted with a probability of 70-90% at the beginning of the optimisation.
speed.cooling_rateRate at which temperature decreases for simulated annealing (default: 0.99).
This controls how quickly the algorithm shifts from exploration to exploitation.
The temperature is updated at each iteration by multiplying it by this rate:
T_i = start_temp * cooling_rate^i.
A higher cooling rate (e.g. 0.995-0.999) results in slower cooling and a longer
exploration phase, which is generally better for complex or noisy optimisation
landscapes. Lower values (e.g. 0.95-0.98) cool quickly, leading to faster
convergence but greater risk of premature convergence to a suboptimal design.
speed.random_initialisationNumber of times to randomly shuffle items within swap_within; the
design with the best score is used as an initial design. (default: 0)
speed.adj_weightWeight for adjacency score (default: 1).
speed.bal_weightWeight for balance score (default: 1).
You can set these options using base::options(), either at the start of a session
or within your code:
options(speed.swap_count = 5, speed.swap_all_blocks = TRUE)
optim_params() for the current, non-deprecated way to set optimisation parameters.
Produces a richer, statistically meaningful evaluation of a design than
print(). Where print() is a compact output,
summary() decomposes the optimised score and reports structural and
evaluation metrics that let you interrogate and defend a design.
## S3 method for class 'design' summary( object, efficiency = FALSE, connectedness = NULL, concurrence = NULL, neighbour = NULL, ... )## S3 method for class 'design' summary( object, efficiency = FALSE, connectedness = NULL, concurrence = NULL, neighbour = NULL, ... )
object |
A |
efficiency |
Logical (default |
connectedness |
|
concurrence |
|
neighbour |
|
... |
Unused; for S3 compatibility. |
The returned object is a list of class "summary.design"; it can be assigned
and queried programmatically (e.g. s <- summary(d); s$per_level[[1]]$score).
Printing it is handled by print.summary.design().
What the evaluation metrics report:
Connectedness: whether every pairwise treatment difference is
estimable (statistically distinguishable) once row, column and any block
effects are accounted for. A disconnected design is usually not desirable as
it confounds some comparisons with the layout itself, no matter how many
replicates there are. Adjusts for the design's actual input spatial factors
(row, column, and any block or site factor), not just columns literally
named row/col.
Concurrence: how many blocks each pair of treatments shares (lambda);
equal lambda across all pairs indicates a balanced incomplete-block
design. Uninformative for complete blocks such as SBBD/split-plot, where
every pair always shares every block.
Replicate spread: how many distinct blocks each treatment's replicates reach, and how many treatments land more than once in a single block. The block counterpart of replicate span: a block factor is nominal, so there is no distance to measure along, but the number of blocks a treatment reaches is still well defined. Reported whenever a block factor is present, including for complete blocks (where concurrence is skipped) - there it confirms every treatment reaches every block.
Replicate span: how far apart a treatment's own replicates are placed
along the two grid axes (whichever columns grid_factors resolved to,
reported by name). For each replicated treatment, the closest its
replicates come to each other, counted inclusively - so a span of 1 means
two replicates share a row, 2 means they are in adjacent rows, and larger
is better. The printed figure is the worst case across all replicated
treatments; the two axes are minimised independently, so they may come from
different treatments. Only the grid axes are measured: a span is a
distance, and a non-grid spatial factor such as block or site has no
ordering to measure along.
Efficiency: the A-efficiency factor, a row–column model metric (see
calculate_efficiency_factor()); the heaviest of these metrics to
compute, hence opt-in.
Neighbour balance: how often treatment pairs end up side by side, using rook adjacency (left–right and up–down, not diagonal). Reported in two parts, because they mean opposite things. Self-adjacency counts treatments placed beside another plot of themselves; zero is the desirable outcome and is what the optimiser works towards. Pair balance covers the distinct treatment pairs: the min, max and variance of their adjacency counts, and how many never end up adjacent at all. Every possible pair is counted, so pairs that never neighbour register as zero rather than being omitted.
A list of class "summary.design":
hierarchical - TRUE for a multi-level (e.g. split-plot) design.
layout - n_plots, nrow, ncol, row_column, col_column,
has_grid (TRUE when the design is reportable as a single grid), and
grid_reason (why not, or NA). nrow/ncol count the rows and columns
the design occupies, so a design with a gap in its coordinates (a missing
plot, or a removed buffer) reports fewer than the coordinates span. Both are
NA unless has_grid.
levels - character vector of level names (e.g. "wp"/"sp"; a single
name for a simple design).
per_level - one element per level (named by levels), each a list with:
swap, n_treatments, treatments.
replication - counts, min, mean, max, equal, distribution.
spatial_factors - named vector of the number of levels of each spatial factor.
evaluation - replicate_span, connectedness, concurrence,
block_spread, efficiency, neighbour; each a list with an
available flag and either its value(s) or a reason it wasn't
computed.
score - initial, final, optimal (NA when not applicable), components.
optim - objective, start_temp, cooling_rate,
iterations_requested, iterations_run, stopped_early, and
stop_reason: one of "optimal", "no_improvement", "frozen" or
"iterations" (NA for designs produced before it was recorded).
score - the overall optimised score (summed across levels for a hierarchical design).
seed - the seed used for reproducibility.
flags - hit_iteration_cap, unequal_replication, disconnected.
call - the captured speed() call.
df <- data.frame( row = rep(1:4, times = 3), col = rep(1:3, each = 4), treatment = rep(LETTERS[1:3], 4) ) design <- speed(df, swap = "treatment", swap_within = "1", spatial_factors = ~ row + col, iterations = 100, seed = 1) summary(design) # Opt in to the (heavier) A-efficiency factor summary(design, efficiency = TRUE)df <- data.frame( row = rep(1:4, times = 3), col = rep(1:3, each = 4), treatment = rep(LETTERS[1:3], 4) ) design <- speed(df, swap = "treatment", swap_within = "1", spatial_factors = ~ row + col, iterations = 100, seed = 1) summary(design) # Opt in to the (heavier) A-efficiency factor summary(design, efficiency = TRUE)