R/hex.R

Defines functions revert_coord_hex_xy revert_coord_fcc revert_coord_hex trans_coord_hex_xy trans_coord_hcc trans_coord_fcc trans_coord_hex

Documented in trans_coord_hex

#' Transform coordinates into hexagonal grid
#'
#' @param .tbl data.frame with (x, y, z) columns
#' @rdname hex
#' @export
trans_coord_hex = function(.tbl) {
  if (nrow(.tbl) == 0L) {
    return(.tbl)
  }
  trans_coord_fcc(.tbl)
}

# face centered cubic, cubic close packed
trans_coord_fcc = function(.tbl) {
  dplyr::mutate(
    trans_coord_hex_xy(.tbl),
    x = .data$x + .data$z / sqrt(3),
    z = .data$z * sqrt(2 / 3)
  )
}

# hexagonal close packed
trans_coord_hcc = function(.tbl) {
  dplyr::mutate(
    trans_coord_hex_xy(.tbl),
    x = .data$x + ifelse(.data$z %% 2L == 1L, sqrt(3) / 3, 0),
    z = .data$z * sqrt(2 / 3)
  )
}

# 2D transformation into hexagonal grid
trans_coord_hex_xy = function(.tbl) {
  dplyr::mutate(
    .tbl,
    y = .data$y + .data$x * 0.5,
    x = .data$x * sqrt(3 / 4)
  )
}

revert_coord_hex = function(.tbl) {
  if (nrow(.tbl) == 0L) {
    return(.tbl)
  }
  revert_coord_fcc(.tbl)
}

revert_coord_fcc = function(.tbl) {
  dplyr::mutate(
    .tbl,
    z = as.integer(round(.data$z * sqrt(3 / 2))),
    x = .data$x - .data$z / sqrt(3)
  ) |> revert_coord_hex_xy()
}

revert_coord_hex_xy = function(.tbl) {
  dplyr::mutate(
    .tbl,
    x = as.integer(round(.data$x * sqrt(4 / 3))),
    y = as.integer(round(.data$y - .data$x * 0.5))
  )
}
heavywatal/tumorr documentation built on April 2, 2024, 7:24 p.m.