---
title: "Complex Agricultural Experimental Designs with speed"
author: "Sam Rogers"
date: "2026-11-11"
output:
  html_document:
    toc: true
    toc_depth: 3
    toc_float: true
    theme: flatly
    highlight: tango
vignette: >
  %\VignetteIndexEntry{Complex Agricultural Experimental Designs with speed}
  %\VignetteEngine{quarto::html}
  %\VignetteEncoding{UTF-8}
---

# Introduction

This vignette covers advanced and complex experimental designs that are used in specialised agricultural research contexts. These designs are particularly useful for plant breeding programs, large-scale variety trials, and situations where standard complete block designs are impractical due to resource constraints or the nature of the treatments.

Building on the foundational designs covered in the [Common Agricultural Experimental Designs vignette](/speed.html), these complex designs offer solutions for challenging experimental scenarios while maintaining statistical rigour through spatial optimisation with the `speed` package.


``` r
library(speed)
library(patchwork) # For combining plots
```

# Split-Split Plot Designs

## Overview

Split-split plot designs extend the hierarchical structure of [split-plot designs](/speed.html#split-plot-design) to accommodate three factors with different levels of experimental difficulty or practical constraints. This creates a three-level hierarchy of experimental units.

## Hierarchical Structure

### Whole Plots (Main Plots)

- **Largest experimental units**
- **Factor A** applied to whole plots
- **Most difficult factor to randomise**
- **Example**: Tillage systems, irrigation methods

### Sub-Plots (Split Plots)

- **Intermediate-sized units within whole plots**
- **Factor B** applied to sub-plots
- **Moderate randomisation difficulty**
- **Example**: Fertilizer treatments, planting dates

### Sub-Sub-Plots (Split-Split Plots)

- **Smallest experimental units**
- **Factor C** applied to sub-sub-plots
- **Easiest factor to randomise**
- **Example**: Varieties, pesticide treatments

## Error Structure

Complex error structure with multiple error terms:

- **Whole plot error** for Factor A effects
- **Sub-plot error** for Factor B and A×B effects  
- **Sub-sub-plot error** for Factor C and higher-order interactions

## When to Use Split-Split Plot Designs

- **Three factors with different application constraints**
- **Hierarchical treatment structure** matches practical needs
- **Sequential application** of treatments over time
- **Resource or equipment limitations** for some factors

## Examples of Applications

### Agricultural Examples

- **Tillage × Fertilizer × Variety** experiments
- **Irrigation × Planting Date × Cultivar** studies
- **Cover Crop × Nitrogen × Hybrid** trials

### Industrial Examples

- **Temperature × Pressure × Catalyst** process studies
- **Machine × Operator × Material** quality experiments

## Example: Split-Split Plot Design for Agricultural Systems Research

Consider a complex agricultural trial examining Tillage System × Nitrogen Rate × Variety interactions with three hierarchical levels.

## Setting Up Split-Split Plot Designs with speed


``` r
splits <- list(
  subsubplot = list(items = c("x", "y", "z"), nrows = 1, ncols = 1),
  subplot = list(items = c("a", "b", "c", "d"), nrows = 1, ncols = 3),
  wholeplot = list(items = c("A", "B", "C"), nrows = 4, ncols = 3),
  block = list(nrows = 4, ncols = 9)
)
split_split_df <- initialise_split_design_df(splits = splits, rep_dim = c(4, 1))
```


![Initial layout of the split-split-plot design showing systematic treatment distribution.](figures/fig-ssplot1-1.png){#fig-ssplot1 fig-align="default"}

This shows the initial split-split plot design with three-level hierarchical structure.

### Performing the Optimisation


``` r
optimise <- list(
  wp = list(
    swap = "wholeplot_treatment",
    swap_within = "block",
    iterations = 2000,
    early_stop_iterations = 1000,
    swap_all = TRUE
  ),
  sp = list(
    swap = "subplot_treatment",
    swap_within = "wholeplot",
    iterations = 5000,
    early_stop_iterations = 3000,
    swap_all = TRUE
  ),
  ssp = list(
    swap = "subsubplot_treatment",
    swap_within = "subplot",
    iterations = 20000,
    early_stop_iterations = 5000
  )
)

result_ss <- speed(split_split_df, optimise = optimise, seed = 42)
```

```
## row and col are used as row and column, respectively.
```

```
## Optimising level: wp 
## Level: wp Iteration: 1000 Score: 252 Best: 252 Since Improvement: 972 
## Early stopping at iteration 1028 for level wp 
## Optimising level: sp 
## Level: sp Iteration: 1000 Score: 132 Best: 132 Since Improvement: 594 
## Level: sp Iteration: 2000 Score: 132 Best: 132 Since Improvement: 1594 
## Level: sp Iteration: 3000 Score: 132 Best: 132 Since Improvement: 2594 
## Early stopping at iteration 3406 for level sp 
## Optimising level: ssp 
## Level: ssp Iteration: 1000 Score: 16 Best: 16 Since Improvement: 120 
## Level: ssp Iteration: 2000 Score: 12 Best: 12 Since Improvement: 349 
## Level: ssp Iteration: 3000 Score: 11 Best: 11 Since Improvement: 553 
## Level: ssp Iteration: 4000 Score: 11 Best: 11 Since Improvement: 1553 
## Level: ssp Iteration: 5000 Score: 10 Best: 10 Since Improvement: 925 
## Level: ssp Iteration: 6000 Score: 10 Best: 10 Since Improvement: 1925 
## Level: ssp Iteration: 7000 Score: 9 Best: 9 Since Improvement: 19 
## Level: ssp Iteration: 8000 Score: 9 Best: 9 Since Improvement: 1019 
## Level: ssp Iteration: 9000 Score: 9 Best: 9 Since Improvement: 2019 
## Level: ssp Iteration: 10000 Score: 7 Best: 7 Since Improvement: 985 
## Level: ssp Iteration: 11000 Score: 7 Best: 7 Since Improvement: 1985 
## Level: ssp Iteration: 12000 Score: 7 Best: 7 Since Improvement: 2985 
## Level: ssp Iteration: 13000 Score: 7 Best: 7 Since Improvement: 3985 
## Level: ssp Iteration: 14000 Score: 7 Best: 7 Since Improvement: 4985 
## Early stopping at iteration 14015 for level ssp
```

### Output of the Optimisation


``` r
result_ss
```

```
## Optimised Experimental Design
## ----------------------------
## Score: 391 
## Iterations Run: 18452 
## Stopped Early: TRUE TRUE TRUE 
## Treatments:
##   wp: A, B, C
##   sp: a, b, c, d
##   ssp: x, y, z
## Seed: 42
```

### Visualise the Output


``` r
res1 <- autoplot(result_ss, treatments = "wholeplot_treatment") + ggplot2::labs(title = "Whole plot Treatments")
res2 <- autoplot(result_ss, treatments = "subplot_treatment") + ggplot2::labs(title = "Sub-plot Treatments")
res3 <- autoplot(result_ss, treatments = "subsubplot_treatment") + ggplot2::labs(title = "Sub-sub-plot Treatments")
res1 + res2 + res3 +
  plot_layout(ncol = 2) +
  plot_annotation(title = "Optimised Split-Split Plot Design")
```


![Final layout of the split-split-plot design showing optimised treatment distribution.](figures/fig-ssplot2-1.png){#fig-ssplot2 fig-align="default"}

Above is the final output of this design. Note that there are some adjacent pairs of treatments in the sub-sub-plots. This is quite difficult to avoid in these situations, however adjusting some of the optimisation parameters may help with this. For further information, see the vignette about [changing optimisation parameters for speed](/custom_objective_functions.html).

# Strip-Plot Designs

## Overview

Strip-plot designs are extensions of split-plot designs used when both treatment factors are difficult to apply to small areas. Treatments are arranged in strips that cross each other, creating a grid pattern where intersections represent treatment combinations.

## Structure

- **Horizontal strips** for one factor (e.g., tillage methods)
- **Vertical strips** for another factor (e.g., planting dates)
- **Intersections** represent factor combinations
- **Whole plots** larger than traditional split-plot designs

## When to Use Strip-Plot Designs

- **Both factors require large application areas**
- **Machinery constraints** for both factors
- **Irrigation × cultivation** experiments
- **Planting date × row spacing** studies
- **When split-plot hierarchy doesn't fit** the practical situation

## Advantages and Limitations

### Advantages

- **Accommodates two "difficult-to-randomise" factors**
- **More flexible** than split-plot for certain applications
- **Maintains reasonable precision** for main effects
- **Practical for mechanised agriculture**

### Limitations

- **Lower precision** for interaction effects
- **Complex analysis** with multiple error terms
- **Less efficient** than a complete-block layout for most comparisons
- **Requires larger field areas**

## Example: Strip-Plot Design for Tillage × Planting Date

Consider an experiment testing 3 tillage methods and 4 planting dates where both factors require large application areas.

## Setting Up Strip-Plot Designs with speed


``` r
df_strip <- data.frame(
  row = rep(1:12, each = 6),  # 12 rows total (4 rows per block x 6 blocks)
  col = rep(1:6, times = 12),  # 6 columns
  block = rep(rep(1:2, each = 3), times = 4) + rep(0:2*2, each = 24),  # 6 blocks, 12 plots each
  
  # Horizontal strips (3 levels, applied to rows within each block)
  vertical_treatment = rep(rep(LETTERS[1:3], times = 2), times = 12),  # A, B, C
  
  # Vertical strips (4 levels, applied to columns within each block)  
  horizontal_treatment = rep(rep(letters[1:4], each = 6), times = 3),  # a, b, c, d
  
  # Plot identifier within each block
  plot_in_block = rep(1:12, times = 6)
)
```


![Initial layout of the strip plot design showing systematic treatment distribution.](figures/fig-strip-plot1-1.png){#fig-strip-plot1 fig-align="default"}

This shows the initial strip-plot layout with horizontal and vertical strips before optimisation.

### Performing the Optimisation


``` r
strip_result <- speed(df_strip,
                      swap = list(ht = "horizontal_treatment", vt = "vertical_treatment"),
                      swap_within = list(ht = "block", vt = "block"),
                      swap_all = TRUE)
```

```
## row and col are used as row and column, respectively.
```

```
## Optimising level: ht 
## Level: ht Iteration: 1000 Score: 84 Best: 84 Since Improvement: 961 
## Level: ht Iteration: 2000 Score: 84 Best: 84 Since Improvement: 1961 
## Early stopping at iteration 2039 for level ht 
## Optimising level: vt 
## Level: vt Iteration: 1000 Score: 54 Best: 54 Since Improvement: 878 
## Level: vt Iteration: 2000 Score: 54 Best: 54 Since Improvement: 1878 
## Early stopping at iteration 2122 for level vt
```

### Output of the Optimisation


``` r
strip_result
```

```
## Optimised Experimental Design
## ----------------------------
## Score: 138 
## Iterations Run: 4163 
## Stopped Early: TRUE TRUE 
## Treatments:
##   ht: a, b, c, d
##   vt: A, B, C
## Seed: -2124829786
```

### Visualise the Output


``` r
autoplot(strip_result, treatments = "horizontal_treatment") + ggplot2::labs(title = "Tillage Treatments")
```


![](figures/strip-plot-plot2-1.png){fig-align="default"}

``` r
autoplot(strip_result, treatments = "vertical_treatment") + ggplot2::labs(title = "Planting Date Treatments")
```


![](figures/strip-plot-plot2-2.png){fig-align="default"}

An optimised strip-plot design with well-arranged treatment combinations!

# Incomplete Block Designs

## Overview

When the number of treatments is large, complete blocks may be impractical due to field size or resource constraints. Incomplete block designs use smaller blocks where not all treatments appear in each block, while still maintaining good statistical properties.

## Types of Incomplete Block Designs

### Balanced Incomplete Block Design (BIBD)

The most restrictive but statistically optimal incomplete block design.

#### Characteristics:

- Each treatment appears in exactly $r$ blocks
- Each block contains exactly $k$ treatments
- Each pair of treatments appears together in exactly $λ$ blocks
- Perfect balance but limited parameter combinations

#### Parameters:

- $v$ = number of treatments
- $b$ = number of blocks  
- $r$ = number of blocks containing each treatment
- $k$ = number of treatments per block
- $λ$ = number of blocks containing each pair of treatments
- $bk = vr$ and $λ(v-1) = r(k-1)$

What may become apparent from the characteristics and parameters listed above is that these designs are not trivial, and [there are specific and limited combinations that will work](https://en.wikipedia.org/wiki/Block_design#Pairwise_balanced_uniform_designs_(2-designs_or_BIBDs)). In the case of speed, a custom objective function is required to ensure that each pair of treatments appear the same number of times. For an example and further discussion, see the [vignette on custom objective functions](custom_objective_functions.html).


### Resolvable Incomplete Block Design (RIBD)

More flexible incomplete block designs where blocks can be grouped into complete replications.

#### Characteristics:

- Blocks can be organised into complete replications
- Each replication contains every treatment exactly once
- More flexible parameter combinations than BIBD
- Excellent for multi-location trials

### Partially Balanced Incomplete Block Design (PBIBD)

Relaxes the balance requirements of BIBD while maintaining good statistical properties.

## When to Use Incomplete Block Designs

- **Large number of treatments** (typically >15-20)
- **Limited block size** due to field homogeneity constraints
- **Multi-location variety trials** where shipping costs limit replication
- **Resource limitations** preventing complete replication
- **Preliminary screening** of large treatment sets

## Example: Resolvable Incomplete Block Design for 6 Varieties

Consider a trial with 15 treatments where complete blocks would be too large for field homogeneity. We'll use an incomplete block design with blocks of size 5.

## Setting Up a Resolvable Incomplete Block Design with speed

Firstly we need to create a data frame representing the incomplete block design. Here we will use a systematic approach to generate the blocks and treatment combinations.


``` r
# Create the data frame
ribd_df <- data.frame(
  row = rep(1:3, 6),                             # Row within each block
  col = rep(1:6, each = 3),                      # Column corresponds to block
  replicate = rep(1:3, each = 6),                # 3 replicates, 6 observations each
  block = rep(1:6, each = 3),                    # 6 blocks total, 3 treatments per block
  treatment = paste0("V", rep(1:6, times = 3))   # Treatment assignments
)

# View the design
head(ribd_df)
```

```
##   row col replicate block treatment
## 1   1   1         1     1        V1
## 2   2   1         1     1        V2
## 3   3   1         1     1        V3
## 4   1   2         1     2        V4
## 5   2   2         1     2        V5
## 6   3   2         1     2        V6
```


![Initial layout of the resolvable incomplete block design showing systematic treatment distribution.](figures/fig-ribdplot1-1.png){#fig-ribdplot1 fig-align="default"}

@fig-ribdplot1 shows the systematic resolvable incomplete block layout before optimisation. Note that replicates are made of two blocks, in each of which half the treatments will appear, and replicates are made up of pairs of blocks. The treatments can be swapped between blocks, but need to remain within their replicate.

### Performing the Optimisation


``` r
ribd_result <- speed(ribd_df, 
                     swap = "treatment", 
                     swap_within = "replicate", 
                     seed = 42)    
```

```
## row and col are used as row and column, respectively.
```

```
## Optimising level: single treatment within replicate 
## Optimal score reached at iteration 474 for level single treatment within replicate
```

### Output of the Optimisation


``` r
ribd_result
```

```
## Optimised Experimental Design
## ----------------------------
## Score: 1.8 
## Iterations Run: 474 
## Stopped Early: TRUE 
## Treatments: V1, V2, V3, V4, V5, V6 
## Seed: 42
```

``` r
str(ribd_result)
```

```
## List of 9
##  $ design_df     :Classes 'design' and 'data.frame':	18 obs. of  5 variables:
##   ..$ row      : int [1:18] 1 1 1 1 1 1 2 2 2 2 ...
##   ..$ col      : int [1:18] 1 2 3 4 5 6 1 2 3 4 ...
##   ..$ replicate: int [1:18] 1 1 2 2 3 3 1 1 2 2 ...
##   ..$ block    : int [1:18] 1 2 3 4 5 6 1 2 3 4 ...
##   ..$ treatment: chr [1:18] "V3" "V2" "V1" "V4" ...
##  $ score         : num 1.8
##  $ scores        : num [1:474] 9 7.4 5.8 6.8 5.4 4.6 4.2 4.2 4.2 4.2 ...
##  $ temperatures  : num [1:474] 100 99 98 97 96.1 ...
##  $ iterations_run: num 474
##  $ stopped_early : logi TRUE
##  $ treatments    : chr [1:6] "V1" "V2" "V3" "V4" ...
##  $ seed          : num 42
##  $ metadata      :List of 6
##   ..$ levels    : chr "single treatment within replicate"
##   ..$ row_column: chr "row"
##   ..$ col_column: chr "col"
##   ..$ grid_by   : NULL
##   ..$ per_level :List of 1
##   .. ..$ single treatment within replicate:List of 13
##   .. .. ..$ swap            : chr "treatment"
##   .. .. ..$ spatial_factors :Class 'formula'  language ~row + col
##   .. .. .. .. ..- attr(*, ".Environment")=<environment: 0x00000202dcfaf188> 
##   .. .. ..$ spatial_cols    : chr [1:2] "row" "col"
##   .. .. ..$ adj_weight      : num 1
##   .. .. ..$ bal_weight      : num 1
##   .. .. ..$ iterations      : num 10000
##   .. .. ..$ start_temp      : num 100
##   .. .. ..$ cooling_rate    : num 0.99
##   .. .. ..$ obj_function    :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, 
##     ...)  
##   .. .. .. ..- attr(*, "srcref")= 'srcref' int [1:8] 43 23 107 1 23 1 43 107
##   .. .. .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x00000202d6f188c8> 
##   .. .. ..$ final_score     : num 1.8
##   .. .. ..$ final_components: Named num [1:2] 0 1.8
##   .. .. .. ..- attr(*, "names")= chr [1:2] "adjacency" "balance"
##   .. .. ..$ optimal_score   : num 1.8
##   .. .. ..$ stop_reason     : chr "optimal"
##   ..$ call      : language speed(data = ribd_df, swap = "treatment", swap_within = "replicate", seed = 42)
##  - attr(*, "class")= chr [1:2] "design" "list"
```

### Visualise the Output


``` r
autoplot(ribd_result)
```


![](figures/ribd-plot4-1.png){fig-align="default"}

We see that each block by itself only contains half the treatments, but when combined, the pairs have a full replicate. The algorithm has also spatially optimised the treatments across rows and columns, giving a nicely optimised resolvable incomplete block design.

# P-Rep (Partially Replicated) Designs

## Overview

P-rep designs are a modern approach to plant breeding trials where a subset of entries (typically checks and selected test lines) are replicated while the majority of test entries appear only once. This provides a balance between statistical power and resource efficiency.

## Structure

- **Replicated entries**: Key checks and promising lines (typically 20-25% of entries)
- **Unreplicated entries**: Majority of test lines (75-80% of entries)
- **Strategic replication**: Based on breeding program priorities
- **Spatial distribution**: Replicates spread throughout the trial

## Key Features

### Flexible Replication

- **Variable replication levels** based on entry importance
- **Adaptive strategies** for different breeding stages
- **Resource-efficient** compared to full replication

### Modern Analysis Methods

- **Mixed models** with spatial correlation
- **BLUP prediction** for unreplicated entries
- **Genomic information** integration possible
- **Spatial adjustment** for field variation

## When to Use P-Rep Designs

- **Large-scale breeding trials** (>500 entries)
- **Early generation testing** with limited seed
- **Resource-constrained** breeding programs
- **High-throughput phenotyping** applications
- **When full replication is impractical**

## Example: P-Rep Design for Large Breeding Trial

Consider a breeding trial with 140 entries where 40 key entries (checks and promising lines) are replicated twice while others appear once. This is a single site design with two blocks.

## Setting Up P-Rep Designs with speed


``` r
prep_design <- data.frame(
  row = rep(1:14, each = 10), 
  col = rep(1:10, times = 14), 
  block = rep(rep(1:2, each = 5), 14),
  entry = c(paste0("V", rep(1:40, 2)), paste0("V", 41:100)) # 100 varieties, 40 duplicated
)

# Create an indicator for the duplicated entries
prep_design$duplicated <- duplicated(prep_design$entry) | duplicated(prep_design$entry, fromLast = TRUE)

head(prep_design)
```

```
##   row col block entry duplicated
## 1   1   1     1    V1       TRUE
## 2   1   2     1    V2       TRUE
## 3   1   3     1    V3       TRUE
## 4   1   4     1    V4       TRUE
## 5   1   5     1    V5       TRUE
## 6   1   6     2    V6       TRUE
```


![Initial layout of the p-rep design showing systematic treatment distribution.](figures/fig-prepplot1-1.png){#fig-prepplot1 fig-align="default"}


![Initial layout of the p-rep design showing replicated treatments.](figures/fig-prepplot2-1.png){#fig-prepplot2 fig-align="default"}

This shows the initial p-rep design with duplicated entries distributed systematically. Once we have set up the data frame, the `speed()` optimisation call is quite straight-forward. Note that we have added `block` into the `spatial_factors` argument, to attempt to balance the replicated treatments between blocks as well. Typically with larger designs, we may also want to increase the number of `iterations` and `early_stop_iterations` to allow more swapping to take place, however in this case it is not necessary due to the low replication.

### Performing the Optimisation


``` r
prep_result <- speed(prep_design,
                     swap = "entry",
                     spatial_factors = ~ block + row + col, 
                     seed = 42)
```

```
## row and col are used as row and column, respectively.
```

```
## Optimising level: single entry within whole design 
## Level: single entry within whole design Iteration: 1000 Score: 2.993939 Best: 2.993939 Since Improvement: 5 
## Optimal score reached at iteration 1183 for level single entry within whole design
```

### Output of the Optimisation


``` r
prep_result
```

```
## Optimised Experimental Design
## ----------------------------
## Score: 2.913131 
## Iterations Run: 1183 
## Stopped Early: TRUE 
## Treatments: V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, V40, V41, V42, V43, V44, V45, V46, V47, V48, V49, V50, V51, V52, V53, V54, V55, V56, V57, V58, V59, V60, V61, V62, V63, V64, V65, V66, V67, V68, V69, V70, V71, V72, V73, V74, V75, V76, V77, V78, V79, V80, V81, V82, V83, V84, V85, V86, V87, V88, V89, V90, V91, V92, V93, V94, V95, V96, V97, V98, V99, V100 
## Seed: 42
```

``` r
str(prep_result)
```

```
## List of 9
##  $ design_df     :Classes 'design' and 'data.frame':	140 obs. of  5 variables:
##   ..$ row       : int [1:140] 1 1 1 1 1 1 1 1 1 1 ...
##   ..$ col       : int [1:140] 1 2 3 4 5 6 7 8 9 10 ...
##   ..$ block     : int [1:140] 1 1 1 1 1 2 2 2 2 2 ...
##   ..$ entry     : chr [1:140] "V100" "V16" "V38" "V37" ...
##   ..$ duplicated: logi [1:140] TRUE TRUE TRUE TRUE TRUE TRUE ...
##  $ score         : num 2.91
##  $ scores        : num [1:1183] 4.53 4.49 4.45 4.37 4.37 ...
##  $ temperatures  : num [1:1183] 100 99 98 97 96.1 ...
##  $ iterations_run: num 1183
##  $ stopped_early : logi TRUE
##  $ treatments    : chr [1:100] "V1" "V2" "V3" "V4" ...
##  $ seed          : num 42
##  $ metadata      :List of 6
##   ..$ levels    : chr "single entry within whole design"
##   ..$ row_column: chr "row"
##   ..$ col_column: chr "col"
##   ..$ grid_by   : NULL
##   ..$ per_level :List of 1
##   .. ..$ single entry within whole design:List of 13
##   .. .. ..$ swap            : chr "entry"
##   .. .. ..$ spatial_factors :Class 'formula'  language ~block + row + col
##   .. .. .. .. ..- attr(*, ".Environment")=<environment: R_GlobalEnv> 
##   .. .. ..$ spatial_cols    : chr [1:3] "block" "row" "col"
##   .. .. ..$ adj_weight      : num 1
##   .. .. ..$ bal_weight      : num 1
##   .. .. ..$ iterations      : num 10000
##   .. .. ..$ start_temp      : num 100
##   .. .. ..$ cooling_rate    : num 0.99
##   .. .. ..$ obj_function    :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, 
##     ...)  
##   .. .. .. ..- attr(*, "srcref")= 'srcref' int [1:8] 43 23 107 1 23 1 43 107
##   .. .. .. .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x00000202d6f188c8> 
##   .. .. ..$ final_score     : num 2.91
##   .. .. ..$ final_components: Named num [1:2] 0 2.91
##   .. .. .. ..- attr(*, "names")= chr [1:2] "adjacency" "balance"
##   .. .. ..$ optimal_score   : num 2.91
##   .. .. ..$ stop_reason     : chr "optimal"
##   ..$ call      : language speed(data = prep_design, swap = "entry", spatial_factors = ~block + row +      col, seed = 42)
##  - attr(*, "class")= chr [1:2] "design" "list"
```

Ideally here we would also like to see an even distribution of the duplicated entries between each block.


``` r
prep_result$design_df$duplicated <- duplicated(prep_result$design_df$entry) | duplicated(prep_result$design_df$entry, fromLast = TRUE)

sum(prep_result$design_df$duplicated[prep_result$design_df$block==1])
```

```
## [1] 40
```

``` r
any(duplicated(prep_result$design_df$entry[prep_result$design_df$block==1]))
```

```
## [1] FALSE
```

With 40 duplicated varieties in this block, we know we also have 40 in the other block.

### Visualise the Output


``` r
autoplot(prep_result, treatments = "entry")
```


![](figures/prep-design-plot2-1.png){fig-align="default"}

An optimised p-rep design with strategic replication and spatial distribution. Note that because the treatments column is not called "treatment", we need to specify the `treatments` argument in the `autoplot()` function.

# Row-Column Designs with Blocking

## Overview

Advanced row-column designs incorporate additional blocking structures to control for multiple sources of variation simultaneously. These designs are particularly useful for large, complex experiments where variation occurs in multiple dimensions.

## Types of Row-Column Blocking

### Row-Column Designs with Superblocks

- **Superblocks** contain multiple row-column units
- **Hierarchical structure** with blocks within blocks
- **Multi-level variation control**
- **Suitable for very large experiments**

### Resolvable Row-Column Designs

- **Complete replications** within the row-column structure
- **Replications as additional blocking factor**
- **Multiple complete layouts**
- **Good for multi-location or multi-season trials**

### Nested Row-Column Designs

- **Plots nested within row-column intersections**
- **Sub-sampling within main experimental units**
- **Multiple measurements per treatment combination**
- **Increased precision for specific comparisons**

## Applications

- **Multi-location breeding trials** with spatial control
- **Large greenhouse experiments** with multiple environmental gradients
- **Field trials with complex spatial patterns**
- **High-throughput phenotyping** platforms

## Example: Row-Column Design with Blocking in Two Dimensions

Consider a large field trial with 40 varieties each replicated 10 times, requiring both row blocks and column blocks.

## Setting Up Row-Column Designs with Blocking


``` r
blocking_2d_design <- data.frame(row = rep(1:20, each = 20), 
                                 col = rep(1:20, 20), 
                                 treatment = rep(paste("V", 1:40, sep = ""), 10), 
                                 rowBlock = rep(1:10, each = 40),
                                 colBlock = rep(rep(1:10, each = 2), 20))
head(blocking_2d_design)
```

```
##   row col treatment rowBlock colBlock
## 1   1   1        V1        1        1
## 2   1   2        V2        1        1
## 3   1   3        V3        1        2
## 4   1   4        V4        1        2
## 5   1   5        V5        1        3
## 6   1   6        V6        1        3
```


![Initial layout of the 2D blocking design showing systematic treatment distribution.](figures/fig-2dblockplot1-1.png){#fig-2dblockplot1 fig-align="default"}


![2D blocking design showing rowBlock layout.](figures/fig-2dblockplot2-1.png){#fig-2dblockplot2 fig-align="default"}


![2D blocking design showing colBlock layout.](figures/fig-2dblockplot3-1.png){#fig-2dblockplot3 fig-align="default"}

This shows the initial row-column design with hierarchical blocking structure.

### Performing the Optimisation

Now we will use the `speed()` function to optimise this design. We will swap treatments within row blocks, while also considering column blocks as a spatial factor. Note that we also set some optimisation parameters to allow for more swaps, as this is a larger design with more treatments.


``` r
optimise_params <- optim_params(swap_count = 5, swap_all_blocks = TRUE, adaptive_swaps = TRUE)

blocking_2d_result <- speed(blocking_2d_design, 
                            swap = "treatment", 
                            swap_within = "rowBlock",
                            spatial_factors = ~ colBlock, 
                            iterations = 150000,
                            early_stop_iterations = 50000, 
                            optimise_params = optimise_params,
                            seed = 42, quiet = TRUE)
```

### Output of the Optimisation


``` r
blocking_2d_result
```

```
## Optimised Experimental Design
## ----------------------------
## Score: 0 
## Iterations Run: 39972 
## Stopped Early: TRUE 
## Treatments: V1, V2, V3, V4, V5, V6, V7, V8, V9, V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, V40 
## Seed: 42
```

### Visualise the Output


![Final layout of the 2D blocking design showing optimised treatment distribution.](figures/fig-2dblockplot4-1.png){#fig-2dblockplot4 fig-align="default"}

An optimised row-column design with blocking in two directions.

<!---
# Designs for Irregular Areas

## Overview

Real-world experimental sites often have irregular shapes, obstacles, or varying conditions that prevent the use of standard rectangular designs. Specialised approaches are needed to maintain statistical validity while accommodating practical constraints.

## Types of Irregular Situations

### Irregular Field Shapes

- **Non-rectangular fields** (triangular, circular, L-shaped)
- **Curved boundaries** following natural features
- **Multiple disconnected areas**
- **Terraced or sloped fields**

### Field Obstacles

- **Trees, buildings, or equipment** within the field
- **Wet areas or rocky patches**
- **Access roads or pathways**
- **Utility lines or structures**

### Varying Field Conditions

- **Distinct soil types** within the field
- **Drainage patterns** creating sones
- **Shade gradients** from adjacent features
- **Historical management differences**

## Design Strategies for Irregular Areas

### Adaptive Blocking

- **Blocks follow field contours** or natural boundaries
- **Variable block sizes** to accommodate constraints
- **Flexible shapes** rather than rectangular blocks
- **Natural groupings** of homogeneous areas

### Constraint-Based Optimisation

- **Spatial constraints** for inaccessible areas
- **Adjacency rules** modified for irregular layouts
- **Distance-based optimisation** rather than grid-based
- **Weighted optimisation** for varying quality areas

### Incomplete Coverage Designs

- **Strategic plot placement** in available areas
- **Systematic gaps** where obstacles occur
- **Interpolation methods** for spatial analysis
- **Robust analysis approaches**

## Example: Irregular Field Design with Obstacles

Consider a field trial that must work around existing trees, buildings, and drainage areas, requiring adaptive plot placement.

## Setting Up Designs for Irregular Areas


``` r
# Placeholder: Initialise irregular field design
# # Define field boundaries and obstacles
# field_constraints <- list(
#   boundaries = data.frame(x = c(0, 50, 50, 0), y = c(0, 0, 30, 30)),
#   obstacles = data.frame(x = c(15, 35), y = c(10, 20), radius = c(3, 2))
# )
# irregular_design <- initialise_design_df(entries = 48, reps = 3,
#                                        constraints = field_constraints)
# head(irregular_design)
```



This shows the initial design layout accommodating field constraints and obstacles.

### Performing the Optimisation


``` r
# Placeholder: Optimise design with spatial constraints
# irregular_result <- speed(irregular_design,
#                          swap = "entry",
#                          constraints = field_constraints,
#                          seed = 42)
# irregular_result
```

### Output of the Optimisation


``` r
# Placeholder: Show structure of results
# str(irregular_result)
```

### Visualise the Output


``` r
# Placeholder: Final visualisation with constraints
# autoplot(irregular_result) + 
#   # Add constraint visualisation
#   geom_polygon(data = field_constraints$obstacles, 
#                aes(x = x, y = y), alpha = 0.3, fill = "red")
```

An optimised design that efficiently uses available space while respecting field constraints!
--->
<!---
# Factorial Designs in Incomplete Blocks

## Overview

When factorial experiments involve many treatment combinations, complete replication may be impractical. Factorial designs can be embedded within incomplete block structures to maintain efficiency while reducing experimental size.

## Approaches

### Confounded Factorial Designs

- **Confound** high-order interactions with blocks
- **Sacrifice** information on some interactions
- **Maintain** efficiency for main effects and important interactions

### Fractional Factorial in Blocks

- Use **fractional factorial** structure
- **Block** the reduced treatment set
- **Alias** some effects but maintain key comparisons

## Applications

- **Multi-factor agricultural trials** with resource constraints
- **Industrial experiments** with expensive experimental units
- **Screening experiments** for multiple factors

## Setting Up Factorial Designs in Incomplete Blocks with speed


``` r
# Placeholder for Factorial in Incomplete Blocks example
# This will show:
# - Designing confounded factorial experiments
# - Choosing appropriate confounding schemes
# - Optimising block arrangements with speed
# - Handling fractional factorials in blocks
# - Analysis implications of confounding
# - Efficiency comparisons with complete designs
```

# Nested and Hierarchical Designs

## Overview

Nested designs involve factors that are nested within levels of other factors, creating hierarchical structures. These are common in multi-location trials and breeding programs.

## Structure

### Simple Nesting

- Factor B nested within Factor A
- Different levels of B for each level of A
- Example: Varieties within breeding programs

### Multiple Nesting

- Several factors nested within higher-level factors
- Complex hierarchical relationships
- Example: Plots within blocks within locations

## Applications

- **Multi-location variety trials**
- **Breeding program comparisons**  
- **Management system studies**
- **Genotype × environment interactions**

## Setting Up Nested Designs with speed


``` r
# Placeholder for Nested Design example
# This will show:
# - Creating hierarchical factor structures
# - Optimising arrangements within nested constraints
# - Handling multiple levels of nesting
# - Spatial optimisation across hierarchy levels
# - Analysis considerations for nested factors
# - Visualisation of hierarchical structure
```

# Design Selection Guidelines for Complex Designs

## Decision Framework

### Treatment Numbers

- **< 20 treatments**: Consider complete blocks or a Latin square
- **20-100 treatments**: Resolvable incomplete blocks within each replicate are often efficient
- **> 100 treatments**: Augmented or incomplete block designs
- **Multiple factors**: Factorial arrangements in blocks

### Resource Constraints

- **Limited field area**: Incomplete blocks or augmented designs
- **High treatment costs**: Augmented designs with fewer checks
- **Labour limitations**: Simpler designs with fewer blocks

### Precision Requirements

- **High precision needed**: Complete designs or highly replicated checks
- **Screening phase**: Augmented designs acceptable
- **Final testing**: Complete replication recommended

## Efficiency Considerations

### Statistical Efficiency

- Compare **A-efficiency**, **D-efficiency**, and **E-efficiency**
- Consider **relative efficiency** to a complete-block layout of the same size
- Balance **precision** vs **resource use**

### Practical Efficiency

- **Field layout** feasibility
- **Management** complexity
- **Analysis** requirements
- **Implementation** costs

# Advanced Spatial Optimisation with speed

## Optimisation Strategies for Complex Designs

### Multi-level Optimisation

- **Hierarchical optimisation** for nested structures
- **Constraint handling** for complex design rules
- **Multi-objective** optimisation balancing competing goals

### Custom Objective Functions

- **Weighted combinations** of different criteria
- **Penalty functions** for constraint violations
- **Domain-specific** optimisation goals

## Computational Considerations

### Large Design Challenges

- **Memory management** for large treatment sets
- **Convergence** monitoring and criteria
- **Parallel processing** options
- **Progress tracking** for long optimisations

### Quality Assessment

- **Convergence diagnostics**
- **Multiple optimisation runs**
- **Sensitivity analysis**
- **Robustness testing**

# Best Practices for Complex Designs

## Design Phase

1. **Clearly define objectives** and constraints
2. **Consider practical limitations** early
3. **Compare multiple design options** systematically  
4. **Validate design properties** before implementation
5. **Plan for analysis** requirements

## Implementation Phase

1. **Detailed field maps** and plot identification
2. **Quality control** procedures for layout
3. **Backup plans** for implementation issues
4. **Documentation** of actual vs planned layout
5. **Training** for field personnel

## Analysis Phase

1. **Appropriate statistical models** for design structure
2. **Spatial analysis** consideration
3. **Model validation** and diagnostics
4. **Effect interpretation** in context of design
5. **Reporting** design details and limitations
--->

# Conclusion

Complex experimental designs offer powerful solutions for challenging agricultural research scenarios. The `speed` package provides essential tools for optimising these designs spatially, ensuring that the statistical advantages of sophisticated designs are fully realised in practice.

Key benefits of using complex designs with spatial optimisation include:

- **Efficient resource utilisation** for large-scale studies
- **Maintained statistical rigor** despite practical constraints  
- **Enhanced precision** through appropriate blocking and spatial arrangement
- **Flexible solutions** for diverse research objectives
- **Practical feasibility** through optimised field layouts

When selecting and implementing complex designs, researchers should carefully balance statistical efficiency, practical constraints, and research objectives. The spatial optimisation capabilities of `speed` ensure that these sophisticated designs achieve their full potential in real-world applications.

<!-- For guidance on comparing the efficiency of different design options, see the **"Comparing Experimental Design Efficiency with speed"** vignette. -->

## Further Reading

### Specialised Design References

- Cochran, W.G. & Cox, G.M. (1957). *Experimental Designs*
- John, J.A. & Williams, E.R. (1995). *Cyclic and Computer Generated Designs*  
- Bailey, R.A. (2008). *Design of Comparative Experiments*
- Patterson, H.D. & Williams, E.R. (1976). "A new class of resolvable incomplete block designs"

### Agricultural Applications

- Kempton, R.A. & Fox, P.N. (1997). *Statistical Methods for Plant Variety Evaluation*
- Singh, R. & Chaudhary, B.D. (1985). *Biometrical Methods in Quantitative Genetic Analysis*

## Related Vignettes

- [Common Agricultural Experimental Designs with speed](speed.html) - Foundational designs for most agricultural applications
<!-- - **"Comparing Experimental Design Efficiency with speed"** - Tools for evaluating and comparing design efficiency -->

---

*This vignette demonstrates advanced applications of the `speed` package for complex experimental designs. For foundational designs, see the "[Common Agricultural Experimental Designs](speed.html)" vignette. For specific implementation details, consult the package documentation and function help files.*
