Package 'speed'

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

Help Index


Add buffers to an existing design

Description

Add buffers to an existing design

Usage

add_buffers(design_obj, type)

Arguments

design_obj

A design object (with class "design") from the design() function

type

The type of buffer to add

Value

The modified design object with buffers added


Generate plots for designs generated in speed

Description

Generate plots for designs generated in speed

Usage

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,
  ...
)

Arguments

object

An experimental design object generated from speed().

...

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 FALSE). A value of FALSE will expand the plot to the edges of the plotting area i.e. remove white space between plot and axes.

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 "colour blind" (or "color blind", both equivalent to "viridis"), "magma", "inferno", "plasma", "cividis", "rocket", "mako" or "turbo". Other palettes from scales::brewer_pal() are also possible.

row

A variable to plot a column from object as rows.

column

A variable to plot a column from object as columns.

block

A variable to plot a column from object as blocks.

treatments

A variable to plot a column from object as treatments.

legend

Logical (default FALSE). If TRUE, displays the legend for treatment colors.

Value

A ggplot2 object.

See Also

speed()

Examples

# 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"))

Calculate Adjacency Score for Design

Description

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.

Usage

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
)

Arguments

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 "row").

col_column

Name of the column representing columns (default "col").

ring_dists

A vector of positive integers, ring radii to score over. (default 1, i.e. only the immediate neighbourhood).

ring_weights

Per-ring weights aligned with ring_dists (default 1).

ring_type

Ring shape: "manhattan" (default; diamond ring) or "chebyshev" (square ring). See ring_offsets().

relationship

Optional pairwise-relationship lookup produced by prep_relationship(). When supplied, each neighbour pair contributes relationship[cell, neighbour] rather than 1 for matches and 0 otherwise. NA-padded cells off the design edge contribute 0. Defaults to NULL, which keeps the strict identity match. Pass the raw matrix through prep_relationship() first; the score functions consume only the prepped form.

by

Optional column name grouping plots into separate grids (e.g. "site" for a multi-environment trial). Each grid is scored on its own and the counts summed, so no adjacency is counted between plots at different sites. NULL (default) treats the design as a single grid, which errors if two plots share a coordinate.

grid_index

Optional pre-built list of indices from grid_indices(), passed to build_design_matrix() to skip coordinate validation. speed() supplies one so the annealing loop does not revalidate every iteration; leave it NULL for a one-off call. Supplying it ignores by, which the indices already encode.

Value

A non-negative numeric value: the number of same-treatment edges in the row/column adjacency graph.

See Also

adjacency_score_vec()

Examples

# 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

Calculate Balance Score for Experimental Design

Description

Calculates a balance score that measures how evenly treatments are distributed across spatial factors in an experimental design. Lower scores indicate better balance.

Usage

calculate_balance_score(layout_df, swap, spatial_cols)

Arguments

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

Value

Numeric value representing the total balance score. Lower values indicate better balance of treatments across spatial factors.

Examples

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"))

Even Distribution Calculation

Description

A metric that represents the even distribution of each item with their minimum spanning tree (mst).

Usage

calculate_ed(design_matrix, current_ed = NULL, swapped_items = NULL)

Arguments

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

Value

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

See Also

objective_function_piepho()

Examples

design_matrix <- matrix(c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrow = 3, ncol = 3)
calculate_ed(design_matrix)

Calculate Efficiency Factor according Piepho

Description

Calculates an efficiency factor of a design according to Piepho 2015.

Usage

calculate_efficiency_factor(
  design_df,
  item,
  row_column = "row",
  col_column = "col"
)

Arguments

design_df

A data frame containing the experimental design with spatial coordinates

item

A column name of the items in the design (e.g., treatment, variety, genotype, etc)

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")

Value

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.

References

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

Examples

# `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"))

Neighbour Balance Calculation

Description

A metric that counts the occurrence of the same adjacent pairs. Only horizontal and vertical pairs are counted.

Usage

calculate_nb(design_matrix, pair_mapping = NULL)

Arguments

design_matrix

A matrix representing the design

pair_mapping

A named vector of pairs generated from create_pair_mapping

Value

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

See Also

objective_function_piepho()

Examples

design_matrix <- matrix(c(1, 2, 2, 1, 3, 3, 1, 3, 3), nrow = 3, ncol = 3)
calculate_nb(design_matrix)

Create Pair Mapping

Description

Create an item pair mapping for calculate_nb.

Usage

create_pair_mapping(items)

Arguments

items

Vector of items for the design

Value

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 1>" - "<item 1>,"

  • ",<item 1>" - "<item 1>,"

  • "<item 3>,<item 2>" - "<item 2>,<item 3>"

  • "<item 4>,<item 2>" - "<item 2>,<item 4>"

  • ...

  • ",<item 2>" - "<item 2>,"

  • ",<item 2>" - "<item 2>,"

  • ...

  • "," - ","

  • "<item 1>,<item 1>" - "<item 1>,<item 1>"

  • "<item 2>,<item 2>" - "<item 2>,<item 2>"

  • ...

  • "," - ","

  • "," - ","

Examples

treatments <- c(rep(1:10, 4), rep(11:16, 3), rep(17:27, 2))
create_pair_mapping(treatments)

Get Weighted Edges

Description

Calculate the weight of edges from vertices.

Usage

get_edges(vertices)

Arguments

vertices

Named list of vertices containing:

  • - A list of (vertex 1, vertex 2, ...)

Value

Named list containing:

  • - A vector of edge weights

See Also

get_vertices()

Examples

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 Vertices of Each Item

Description

Get the vertices of each item in a design matrix.

Usage

get_vertices(design_matrix)

Arguments

design_matrix

A matrix representing the design

Value

Named list containing:

  • - A list of (vertex 1, vertex 2, ...)

See Also

get_edges()

Examples

design_matrix <- matrix(c(1, 2, 2, 1, 3, 2, 1, 3, 3), nrow = 3, ncol = 3)
vertices <- get_vertices(design_matrix)

Initialise Design Data Frame

Description

Initialise a design data frame with or without blocking.

Usage

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"
)

Arguments

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: NULL)

nrows

Number of rows in the design (default: NULL)

ncols

Number of columns in the design (default: NULL)

block_nrows

Number of rows in each block (default: NULL)

block_ncols

Number of columns in each block (default: NULL)

splits

Deprecated; use initialise_split_design_df() instead. A named list of nested-unit specifications, ordered from the outermost level to the innermost. Each entry is itself a list with nrows and ncols (the dimensions of one unit at that level, in cells) and an optional items (treatments to allocate across the units at that level, one item per unit, ordered by parent then within-parent ID). For each level, ⁠<name>⁠ and ⁠<name>_treatment⁠ columns are added (the latter only if items is provided). Used to build hierarchical layouts such as split-plot, split-split-plot, and strip-plot designs. (default: NULL)

designs

A list of named arguments describing design specifications, required if nrows and ncols are absent. (default: NULL)

design_col

A column name to distinguish different designs (default: "site")

Value

A data frame containing the design

Examples

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 a Split-Plot Design Data Frame

Description

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).

Usage

initialise_split_design_df(splits, rep_dim = c(1, 1))

Arguments

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:

  • nrows, ncols - the dimensions of one unit at that level, in cells. The innermost level is always 1x1, so its nrows/ncols may be omitted.

  • items - optional treatments to allocate across the units at that level, one item per unit. A single number is expanded to T1, T2, ...; a shorter vector is reused to fill each parent unit. The outermost entry defines the replicated unit; rep_dim tiles it across the field. For each level a ⁠<name>⁠ ID column is added, plus a ⁠<name>_treatment⁠ column wherever items is supplied.

rep_dim

Length-2 integer vector c(row_reps, col_reps) giving the replicate dimension of the whole structure (default: c(1, 1)).

Value

A data frame with row and col columns plus one ID (and optional treatment) column per split level.

Examples

# 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

Description

Objective Function for Factorial Design Optimization

Usage

objective_function_factorial(
  layout_df,
  swap,
  spatial_cols,
  interaction_weight = 1,
  main_weight = 1,
  factorial_separator = "-",
  ...
)

Arguments

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 objective_function

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: NULL)

swapped_items

Items swapped after current_score_obj (default: NULL)

Examples

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"))

Objective Function with Metric from Piepho

Description

Create an objective function including even distribution and neighbor balance introduced by Piepho 2018.

Usage

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,
  ...
)

Arguments

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 current_score_obj (default: NULL)

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 calculate_adjacency_score(). Neighbour balance sums across grids, while evenness of distribution is scored per grid and the scores summed, reported both in total and per grid. A grid with no treatment replicated inside it contributes 0.

...

Extra parameters passed from speed

Value

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.

References

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

See Also

objective_function(), create_pair_mapping()

Examples

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 functions

Description

Default Objective Function for Design Optimization

Usage

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,
  ...
)

Arguments

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: NULL)

swapped_items

Items swapped after current_score_obj (default: NULL)

Value

A numeric value representing the score of the design (lower is better)

Examples

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

Description

Create and verify optimization parameters. These parameters are used to control the behaviour of simulated annealing algorithm.

Usage

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
)

Arguments

swap_count

Number of treatment swaps per iteration (default: 1).

swap_all_blocks

Logical; if TRUE, performs swaps in all blocks at each iteration (default: FALSE).

adaptive_swaps

Logical; if TRUE, adjusts swap parameters based on temperature (default: FALSE).

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: 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.

random_initialisation

Number of times to randomly shuffle items within swap_within; the design with the best score is used as an initial design (default: 0).

adj_weight, bal_weight

Deprecated. Weights for the adjacency and balance scores. Pass them to speed() directly or through a level's obj_args in optimise instead.

stop_at_optimal

Logical; if TRUE, stops the level as soon as the best score reaches the lowest score its layout allows (default: TRUE). The bound is only derivable for the default objective_function() with non-negative weights and no relationship matrix; otherwise the level runs to its usual stopping rules regardless of this setting.

Value

A named list of optimization parameters.

See Also

speed() for examples


Plot Optimization Progress

Description

Creates two plots showing the progression of the optimization:

  1. Objective score over iterations

  2. Temperature decay over iterations

Usage

plot_progress(result)

Arguments

result

A list containing the optimization results with the following elements:

  • scores - Numeric vector of objective scores for each iteration

  • temperatures - Numeric vector of temperatures for each iteration

Value

No return value; prints two ggplot objects showing:

  • Progress of the objective score

  • Cooling schedule (temperature decay)

Examples

# 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)

Validate and Flatten a Relationship Matrix for Lookup

Description

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.

Usage

prep_relationship(relationship, treatments = NULL)

Arguments

relationship

A numeric matrix with rownames and colnames covering every treatment value to be scored.

treatments

Optional character vector of treatment values that relationship must cover. Skipped when NULL.

Value

A list with flat (column-major flattened matrix), row_levels, col_levels, and n_row.


Print method for speed design objects

Description

Print method for speed design objects

Usage

## S3 method for class 'design'
print(x, ...)

Arguments

x

Design object returned by speed function

...

Additional arguments passed to print

Value

x invisibly


Print method for design summaries

Description

Print method for design summaries

Usage

## S3 method for class 'summary.design'
print(x, ...)

Arguments

x

A "summary.design" object from summary.design().

...

Unused; for S3 compatibility.

Value

x invisibly.


Optimise Experimental Design Layout Using Simulated Annealing

Description

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.

Usage

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,
  ...
)

Arguments

data

A data frame containing the experimental design with spatial coordinates

swap

A column name of the items to be swapped (e.g., treatment, variety, genotype, etc). For hierarchical designs, provide a named list where each name corresponds to a hierarchy level (e.g., list(wp = "wholeplot_treatment", sp = "subplot_treatment")). See details for more information.

swap_within

A string specifying the variable that defines a boundary within which to swap treatments. Specify "1" or "none" for no boundary (default: "1"). Other examples might be "block" or "replicate" or even "site". For hierarchical designs, provide a named list with names matching swap to optimise a hierarchical design such as a split-plot. See details for more information.

spatial_factors

A one-sided formula specifying spatial factors to consider for balance (default: ~row + col).

grid_factors

A named list specifying grid factors to construct a matrix for calculating adjacency score, dim1 for row and dim2 for column. (default: list(dim1 = "row", dim2 = "col")). The axes apply to the whole design, so unlike swap they cannot be set per level of a hierarchical design.

An optional third element, by, names a column that groups plots into separate grids - a multi-environment trial, where each site reuses the same row/col numbering. Each grid is then scored on its own and the adjacency counts summed, so no adjacency is counted between plots at different sites, e.g. list(dim1 = "row", dim2 = "col", by = "site"). Without it, a design whose sites share coordinates is refused rather than silently pooled.

iterations

Maximum number of iterations for the simulated annealing algorithm (default: 10000). For hierarchical designs, can be a named list with names matching swap.

early_stop_iterations

Number of iterations without improvement before early stopping (default: 2000). For hierarchical designs, can be a named list with names matching swap. Optimisation also stops as soon as a level reaches the lowest score its layout allows, which is only applicable for the default objective_function(); see summary().

obj_function

Objective function used to calculate score (lower is better) (default: objective_function()). For hierarchical designs, can be a named list with names matching swap.

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 swap column, for example a variety_name label belonging to a numeric variety code (default: NULL). For hierarchical designs, can be a named list with names matching swap. See details for more information.

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 optim_params() for more details.

quiet

Logical; if TRUE, suppresses progress messages (default: FALSE)

seed

A numeric value for random seed. If provided, it ensures reproducibility of results (default: NULL).

...

Other arguments passed to objective functions. For hierarchical designs, set an obj_args field in optimise. See details for more information.

Details

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.

Value

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.

Examples

# 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)

Package Options for speed (Deprecated)

Description

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_count

Number of treatment swaps per iteration (default: 1).

speed.swap_all_blocks

Logical; if TRUE, performs swaps in all blocks at each iteration (default: FALSE).

speed.adaptive_swaps

Logical; if TRUE, adjusts swap parameters based on temperature (default: FALSE).

speed.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.

speed.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: 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_initialisation

Number 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_weight

Weight for adjacency score (default: 1).

speed.bal_weight

Weight for balance score (default: 1).

Setting options

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)

See Also

optim_params() for the current, non-deprecated way to set optimisation parameters.


Summarise a speed design

Description

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.

Usage

## S3 method for class 'design'
summary(
  object,
  efficiency = FALSE,
  connectedness = NULL,
  concurrence = NULL,
  neighbour = NULL,
  ...
)

Arguments

object

A "design" object returned by speed().

efficiency

Logical (default FALSE); if TRUE, compute the A-efficiency factor. Returns NA with a reason when its assumptions are not met (columns named row and col, and at least 3 treatments). See Details for more information.

connectedness

NULL (default) checks whether the design is connected, but skips the check for very large designs where the model fit would be expensive; TRUE forces it regardless of size; FALSE skips it. See Details for more information.

concurrence

NULL (default) computes within-block treatment concurrence only when an incomplete block factor is present; TRUE forces it even for complete blocks, FALSE skips it. See Details for more information.

neighbour

NULL (default) or TRUE reports neighbour-balance diagnostics whenever the design has a row/column grid; FALSE skips them. See Details for more information.

...

Unused; for S3 compatibility.

Details

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.

Value

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.

See Also

print.design(), speed()

Examples

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)