Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
.Rproj.user
.Rhistory
.RData
*\.RData
*\.rds
.Ruserdata
lib/
docs
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ quarto::quarto_render("vignettes/speed.qmd") # render a vignette (Quarto, not k
Code formatting is handled by [Air](https://posit-dev.github.io/air/) - see `air.toml` (80-col, 2-space indent).
Per `CONTRIBUTING.md`, do **not** restyle code that is unrelated to your PR.

User-facing changes should add a bullet to the top of `NEWS.md`. NEWS entries should be kept concise, with just a short 1-2 sentence summary of the changes, not paragraphs of explanation. If a change is related to a GitHub issue, it can be referenced just by number in parentheses e.g. (#1), but do not reference GitHub issues unless it's certain that they are related.
User-facing changes should add a bullet to the top of `NEWS.md`. Use headings Major Changes, Minor Changes and Bug Fixes to document changes appropriately. NEWS entries should be kept concise, with just a short 1-2 sentence summary of the changes, not paragraphs of explanation. If a change is related to a GitHub issue or PR, it can be referenced just by number in parentheses e.g. (#1).

## Architecture

Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export(calculate_balance_score)
export(calculate_ed)
export(calculate_efficiency_factor)
export(calculate_nb)
export(calculate_pair_incidence)
export(calculate_position_incidence)
export(create_pair_mapping)
export(get_edges)
export(get_vertices)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
decomposed optimisation score, and design-quality diagnostics (connectedness, concurrence,
replicate spans and spread across blocks, neighbour balance, and opt-in efficiency).
([#73](https://github.com/biometryhub/speed/issues/73))
- Added `calculate_pair_incidence()` to return a symmetric treatment × treatment matrix of neighbour-pair counts.
- Added `calculate_position_incidence()` to return treatment × row/column position count matrices.

# speed 0.0.9

Expand Down
186 changes: 186 additions & 0 deletions R/incidence.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
#' Calculate Treatment Pair Incidence
#'
#' @description
#' Returns a symmetric matrix counting how many times each pair of treatments
#' appears as neighbours in the design. Two plots are neighbours if they share
#' an edge on the `row × col` grid (orthogonal / rook adjacency; diagonals
#' excluded). Horizontal and vertical adjacencies are pooled.
#'
#' The diagonal holds self-adjacency counts — the quantity that
#' [calculate_adjacency_score()] penalises. A well-optimised design will have
#' zeros (or near-zeros) on the diagonal. Off-diagonal entry \eqn{(i, j)}
#' is the total number of edges where treatment \eqn{i} and treatment \eqn{j}
#' are immediate neighbours.
#'
#' @param design A `design` object returned by [speed()], or a plain data
#' frame containing at least the columns named by `swap`, `row_column`, and
#' `col_column`.
#' @param swap Column name of the treatment variable (default `"treatment"`).
#' @param row_column Column name of the row position variable (default `"row"`).
#' @param col_column Column name of the column position variable (default `"col"`).
#' @param as_list If `TRUE`, returns a named list instead of a matrix: one
#' entry per treatment, each a named integer vector of neighbour counts with
#' every other treatment (including itself on the diagonal). This is the
#' matrix split by row — identical data, different container.
#'
#' @return When `as_list = FALSE` (default): a symmetric integer matrix of
#' dimension \eqn{t \times t} where \eqn{t} is the number of unique
#' treatments, with treatment names as row and column names.
#'
#' When `as_list = TRUE`: a named list of length \eqn{t}, where each element
#' is a named integer vector of neighbour counts for that treatment.
#'
#' @examples
#' # From a speed() result
#' df <- data.frame(
#' row = rep(1:4, times = 3),
#' col = rep(1:3, each = 4),
#' treatment = rep(c("A", "B", "C"), 4)
#' )
#' result <- speed(df, swap = "treatment", seed = 42, iterations = 200)
#' calculate_pair_incidence(result)
#'
#' # From a plain data frame; as named list
#' df2 <- initialise_design_df(
#' items = c("A", "B", "C", "B", "C", "A", "C", "A", "B"),
#' nrows = 3,
#' ncols = 3
#' )
#' calculate_pair_incidence(df2, as_list = TRUE)
#'
#' @seealso [calculate_adjacency_score()], [calculate_position_incidence()]
#'
#' @export
calculate_pair_incidence <- function(design,
swap = "treatment",
row_column = "row",
col_column = "col",
as_list = FALSE) {
df <- if (inherits(design, "design")) design$design_df else design
missing_cols <- setdiff(c(swap, row_column, col_column), names(df))
if (length(missing_cols)) {
stop(
"Column(s) not found in data: ",
paste(missing_cols, collapse = ", "),
call. = FALSE
)
}

m <- build_design_matrix(df, swap, row_column, col_column)
nr <- nrow(m)
nc <- ncol(m)

lvls <- stringi::stri_sort(
unique(as.character(df[[swap]][!is.na(df[[swap]])])),
numeric = TRUE
)

horiz <- if (nc >= 2) {
cbind(
as.vector(m[, seq_len(nc - 1L)]),
as.vector(m[, seq.int(2L, nc)])
)
} else {
matrix(character(0L), nrow = 0L, ncol = 2L)
}
vert <- if (nr >= 2) {
cbind(
as.vector(m[seq_len(nr - 1L), ]),
as.vector(m[seq.int(2L, nr), ])
)
} else {
matrix(character(0L), nrow = 0L, ncol = 2L)
}

edges <- rbind(horiz, vert)
keep <- !is.na(edges[, 1L]) & !is.na(edges[, 2L])
edges <- edges[keep, , drop = FALSE]

a_fac <- factor(edges[, 1L], levels = lvls)
b_fac <- factor(edges[, 2L], levels = lvls)
raw <- matrix(
as.integer(table(a_fac, b_fac)),
nrow = length(lvls),
dimnames = list(lvls, lvls)
)

M <- raw + t(raw)
diag(M) <- diag(raw)

if (as_list) {
return(lapply(setNames(lvls, lvls), function(trt) M[trt, ]))
}
M
}


#' Calculate Positional Incidence of Treatments
#'
#' @description
#' Returns how many times each treatment appears in each row position and each
#' column position of the design. This is the human-readable decomposition of
#' what [calculate_balance_score()] collapses to a scalar: uneven row or column
#' counts reveal where spatial imbalance lies.
#'
#' @inheritParams calculate_pair_incidence
#'
#' @return A named list with two integer matrices, both with treatments as rows
#' and positions as columns:
#' \describe{
#' \item{`row`}{Treatment × row-position count matrix.}
#' \item{`col`}{Treatment × column-position count matrix.}
#' }
#' Indexing by treatment name is natural: `result$row["A", ]` gives the row
#' distribution of treatment A.
#'
#' @examples
#' # From a speed() result
#' df <- data.frame(
#' row = rep(1:4, times = 3),
#' col = rep(1:3, each = 4),
#' treatment = rep(c("A", "B", "C"), 4)
#' )
#' result <- speed(df, swap = "treatment", seed = 42, iterations = 200)
#' res <- calculate_position_incidence(result)
#' res$row # treatment × row counts
#' res$col # treatment × column counts
#'
#' @seealso [calculate_balance_score()], [calculate_pair_incidence()]
#'
#' @export
calculate_position_incidence <- function(design,
swap = "treatment",
row_column = "row",
col_column = "col") {
df <- if (inherits(design, "design")) design$design_df else design
missing_cols <- setdiff(c(swap, row_column, col_column), names(df))
if (length(missing_cols)) {
stop(
"Column(s) not found in data: ",
paste(missing_cols, collapse = ", "),
call. = FALSE
)
}

lvls <- stringi::stri_sort(
unique(as.character(df[[swap]][!is.na(df[[swap]])])),
numeric = TRUE
)
trt_fac <- factor(df[[swap]], levels = lvls)

row_tbl <- table(trt_fac, df[[row_column]])
col_tbl <- table(trt_fac, df[[col_column]])

row_mat <- matrix(
as.integer(row_tbl),
nrow = length(lvls),
dimnames = list(lvls, colnames(row_tbl))
)
col_mat <- matrix(
as.integer(col_tbl),
nrow = length(lvls),
dimnames = list(lvls, colnames(col_tbl))
)

list(row = row_mat, col = col_mat)
}
Loading
Loading