R/make-tikz-classic.R

Defines functions classic_fit_tier_lines classic_tier_lines classic_tier_layout classic_edge_lines make_tikz_classic

#' @title Generate Classic-Style TikZ Code from a Caugi Plot
#'
#' @description
#' Renders the "classic" TikZ style: plain-text variables, gray bands behind
#' each tier, a time axis with tier labels, and gently bent edges. Node order
#' and edges are taken from the `caugi::caugi_plot` object, but the tiered
#' layout is recomputed so tiers of different sizes are centered and nodes
#' within a tier zigzag, which keeps within-tier edges from running through
#' other nodes.
#'
#' Coordinates are emitted in "tier units" and "node units", with the actual
#' spacing set once in the `tikzpicture` options (`x=` and `y=`), so the figure
#' is easy to stretch or compress in LaTeX.
#'
#' @inheritParams .make_tikz
#' @param tier_label_pos `NULL` (use the default side for the orientation) or
#'   one of `"above"`, `"below"`, `"left"`, `"right"`.
#' @param node_labels,tier_labels Named character vectors of resolved labels
#'   (see `resolve_tikz_labels()`).
#' @returns A character string containing LaTeX TikZ code.
#' @keywords internal
#' @noRd
make_tikz_classic <- function(
  caugi_plot_obj,
  tier_node_map = NULL,
  scale = 10,
  full_doc = TRUE,
  bend = 10,
  pair_bend = 10,
  bend_by_edge = NULL,
  tier_label_pos = NULL,
  node_labels = NULL,
  tier_labels = NULL
) {
  stopifnot(inherits(caugi_plot_obj, "caugi::caugi_plot"))

  g <- caugi_plot_obj@grob$children$caugi.graph
  node_grob_children <- g$children$node_gtree$children
  edge_grob_children <- g$children[grep("^edge", names(g$children))]

  pos <- tikz_node_table(extract_nodes(node_grob_children, scale = 1))
  node_names <- pos$name
  edges <- tikz_edge_records(edge_grob_children, pos)

  layout <- classic_tier_layout(pos, tier_node_map)

  tier_lines <- character(0)
  needs_fit <- FALSE
  needs_calc <- FALSE
  if (!is.null(layout)) {
    coords <- layout$coords
    # Columns: tiers side by side, nodes stacked closely within a tier.
    # Rows: labels are wide, so nodes get more room and tiers less.
    units <- if (layout$orientation == "columns") {
      c(x = 0.35, y = 0.15) * scale
    } else {
      c(x = 0.25, y = 0.2) * scale
    }
    picture_opts <- sprintf(
      "x=%scm, y=%scm",
      format_coord(units[["x"]]),
      format_coord(units[["y"]])
    )
    units_cm <- units
    tier_lines <- classic_tier_lines(layout, tier_label_pos, tier_labels)
    needs_fit <- TRUE
  } else {
    # No (detectable) tiered layout: keep the plot coordinates as they are.
    coords <- pos
    coords$x <- coords$x * scale
    coords$y <- coords$y * scale
    picture_opts <- NULL
    units_cm <- c(x = 1, y = 1)
    if (!is.null(tier_node_map)) {
      needs_fit <- TRUE
      needs_calc <- TRUE
      tier_lines <- classic_fit_tier_lines(
        tier_node_map,
        intersect_names = node_names,
        tier_label_pos = tier_label_pos %||% "above",
        tier_labels = tier_labels
      )
    }
  }

  labels <- unname(node_labels[coords$name])
  node_lines <- sprintf(
    "\\node[var] (%s) at (%s,%s) {%s};",
    coords$name,
    format_coord(coords$x),
    format_coord(coords$y),
    labels
  )

  nodes_cm <- data.frame(
    name = coords$name,
    x = coords$x * units_cm[["x"]],
    y = coords$y * units_cm[["y"]],
    tikz_node_extent(labels, shape = "text")
  )
  # Default bend: always `bend right`, which puts edges in both directions on
  # opposite sides.
  bidir <- tikz_bidirected(edges$from, edges$to)
  bend_options <- tikz_bend_options(
    edges,
    nodes_cm,
    default = ifelse(bidir, -pair_bend, -bend),
    bend_by_edge = bend_by_edge
  )
  edge_lines <- classic_edge_lines(edges, bend_options)

  libraries <- c(
    "arrows.meta",
    "bending",
    "backgrounds",
    if (needs_fit) "fit",
    if (needs_calc) "calc"
  )
  generator_line <- paste0(
    "%%% Generated by causalDisco (version ",
    utils::packageVersion("causalDisco"),
    ")"
  )

  styles <- c(
    "\\tikzset{",
    "  >={Stealth[length=2.2mm, width=1.7mm]},",
    "  o/.tip={Circle[open, length=1.6mm]},",
    "  var/.style={inner sep=2pt},",
    "  link/.style={semithick},",
    "  tier/.style={fill=black!8, inner sep=4pt},",
    "  tier label/.style={font=\\small},",
    "  time axis/.style={semithick, -{Stealth[length=2mm]}}",
    "}"
  )

  lines <- c(
    generator_line,
    if (full_doc) {
      c(
        "\\documentclass[tikz,border=2mm]{standalone}",
        sprintf("\\usetikzlibrary{%s}", paste(libraries, collapse = ", ")),
        "",
        "\\begin{document}"
      )
    },
    styles,
    if (is.null(picture_opts)) {
      "\\begin{tikzpicture}"
    } else {
      sprintf("\\begin{tikzpicture}[%s]", picture_opts)
    },
    node_lines,
    if (length(edge_lines)) {
      sprintf("\\path[link] %s;", paste(edge_lines, collapse = "\n      "))
    },
    tier_lines,
    "\\end{tikzpicture}",
    if (full_doc) "\\end{document}"
  )

  paste(lines, collapse = "\n")
}


#' @title Build Classic-Style TikZ Edge Lines
#' @param edges Data frame from `tikz_edge_records()`.
#' @param bend_options Character vector, one per edge, of bend options (e.g.
#'   `"bend left=23"`) or `NA` (straight), from `tikz_bend_options()`.
#' @returns Character vector of `(from) edge[...] (to)` fragments.
#' @keywords internal
#' @noRd
classic_edge_lines <- function(edges, bend_options) {
  vapply(
    seq_len(nrow(edges)),
    function(i) {
      opts <- c(
        tikz_edge_arrow(edges$type[i], style = "classic"),
        if (!is.na(edges$col[i])) paste0("draw=", edges$col[i]),
        if (!is.na(bend_options[i])) bend_options[i]
      )
      sprintf(
        "(%s) edge[%s] (%s)",
        edges$from[i],
        paste(opts, collapse = ", "),
        edges$to[i]
      )
    },
    character(1)
  )
}


#' @title Compute the Classic Tiered Layout
#'
#' @description
#' Detects whether the caugi plot laid tiers out as columns (tiers along x) or
#' rows (tiers along y, first tier on top), then places tier `t` at tier
#' coordinate `t` and its nodes at centered slots `0, 1, ...` along the other
#' axis. Nodes alternate a small offset along the tier axis (zigzag).
#'
#' @param pos Data frame with `name`, `x`, `y` (unscaled plot coordinates).
#' @param tier_node_map Named list mapping tier names to node names, or `NULL`.
#' @returns `NULL` if no tiered layout is detected, otherwise a list with
#'   `coords` (data frame `name`, `x`, `y` in tier/node units), `orientation`
#'   (`"columns"` or `"rows"`), `tiers` (ordered tier names), `tier_nodes`
#'   (node names per tier, in the same order), and `max_nodes`.
#' @keywords internal
#' @noRd
classic_tier_layout <- function(pos, tier_node_map) {
  if (is.null(tier_node_map) || length(tier_node_map) == 0) {
    return(NULL)
  }
  tier_node_map <- lapply(tier_node_map, function(v) intersect(v, pos$name))
  tier_node_map <- tier_node_map[lengths(tier_node_map) > 0]
  if (
    length(tier_node_map) == 0 || !setequal(unlist(tier_node_map), pos$name)
  ) {
    return(NULL)
  }

  tol <- 1e-9
  tier_coord <- function(axis) {
    vals <- vapply(
      tier_node_map,
      function(v) {
        p <- pos[[axis]][match(v, pos$name)]
        if (diff(range(p)) < tol) p[1] else NA_real_
      },
      numeric(1)
    )
    if (anyNA(vals) || anyDuplicated(round(vals, 9))) NULL else vals
  }

  tx <- tier_coord("x")
  ty <- tier_coord("y")
  if (!is.null(tx)) {
    orientation <- "columns"
    tier_order <- names(sort(tx))
    stack_axis <- "y"
  } else if (!is.null(ty)) {
    orientation <- "rows"
    tier_order <- names(sort(ty, decreasing = TRUE))
    stack_axis <- "x"
  } else {
    return(NULL)
  }

  max_nodes <- max(lengths(tier_node_map))
  jitter <- 0.15

  coords <- do.call(
    rbind,
    lapply(seq_along(tier_order), function(t) {
      v <- tier_node_map[[tier_order[t]]]
      v <- v[order(pos[[stack_axis]][match(v, pos$name)])]
      n <- length(v)
      slot <- (max_nodes - n) / 2 + seq_len(n) - 1
      offset <- if (n > 1) ifelse(seq_len(n) %% 2 == 1, -jitter, jitter) else 0
      tier_pos <- (t - 1) + offset
      if (orientation == "columns") {
        data.frame(name = v, x = tier_pos, y = slot, stringsAsFactors = FALSE)
      } else {
        data.frame(name = v, x = slot, y = -tier_pos, stringsAsFactors = FALSE)
      }
    })
  )
  coords <- coords[match(pos$name, coords$name), , drop = FALSE]
  rownames(coords) <- NULL

  list(
    coords = coords,
    orientation = orientation,
    tiers = tier_order,
    tier_nodes = unname(tier_node_map[tier_order]),
    max_nodes = max_nodes
  )
}


#' @title Build Tier Bands, Time Axis, and Tier Labels (Classic Style)
#' @param layout Output of `classic_tier_layout()`.
#' @param tier_label_pos `NULL` or one of `"above"`, `"below"`, `"left"`,
#'   `"right"`. Must be compatible with the layout orientation.
#' @param tier_labels Named character vector of tier labels (see
#'   `resolve_tikz_labels()`).
#' @returns Character vector of TikZ lines.
#' @keywords internal
#' @noRd
classic_tier_lines <- function(layout, tier_label_pos, tier_labels) {
  columns <- layout$orientation == "columns"
  allowed <- if (columns) c("below", "above") else c("left", "right")
  tier_label_pos <- tier_label_pos %||% allowed[1]
  if (!tier_label_pos %in% allowed) {
    stop(
      sprintf(
        "With `style = \"classic\"` and tiers laid out as %s, `tier_label_pos` must be %s.",
        layout$orientation,
        paste0("\"", allowed, "\"", collapse = " or ")
      ),
      call. = FALSE
    )
  }

  n_tiers <- length(layout$tiers)
  idx <- seq_len(n_tiers) - 1
  labels <- tier_labels[layout$tiers]
  band_names <- paste0("tier-", seq_len(n_tiers))
  fc <- format_coord

  # Points are written as (tier coordinate, slot coordinate) and swapped for rows.
  pt <- function(t, s) {
    if (columns) {
      sprintf("(%s,%s)", fc(t), fc(s))
    } else {
      sprintf("(%s,%s)", fc(s), fc(-t))
    }
  }

  # Each band fits its own nodes (so long labels stay inside) plus two fixed
  # points at the ends of the slot range (so all bands have the same length).
  slot_lo <- -0.5
  slot_hi <- layout$max_nodes - 1 + 0.5
  bands <- vapply(
    seq_len(n_tiers),
    function(t) {
      v <- layout$coords$name[layout$coords$name %in% layout$tier_nodes[[t]]]
      sprintf(
        "\\node[tier, fit={%s%s%s}] (%s) {};",
        paste0("(", v, ")", collapse = ""),
        pt(idx[t], slot_lo),
        pt(idx[t], slot_hi),
        band_names[t]
      )
    },
    character(1)
  )

  # Time axis runs along the labelled side of the bands, past the last tier.
  side <- switch(
    tier_label_pos,
    below = "south",
    above = "north",
    left = "west",
    right = "east"
  )
  first <- band_names[1]
  last <- band_names[n_tiers]
  axis_line <- if (columns) {
    sprintf(
      "\\draw[time axis] ([xshift=-3mm]%s.%s west) -- ([xshift=5mm]%s.%s east);",
      first,
      side,
      last,
      side
    )
  } else {
    sprintf(
      "\\draw[time axis] ([yshift=3mm]%s.north %s) -- ([yshift=-5mm]%s.south %s);",
      first,
      side,
      last,
      side
    )
  }
  label_lines <- sprintf(
    "\\node[tier label, %s=3pt] at (%s.%s) {%s};",
    tier_label_pos,
    band_names,
    side,
    labels
  )

  c(
    "\\begin{scope}[on background layer]",
    bands,
    "\\end{scope}",
    axis_line,
    label_lines
  )
}


#' @title Build Fitted Tier Bands (Classic Style, Custom Layouts)
#' @param tier_node_map Named list mapping tier names to node names.
#' @param intersect_names Node names present in the plot.
#' @param tier_label_pos One of `"above"`, `"below"`, `"left"`, `"right"`.
#' @param tier_labels Named character vector of tier labels (see
#'   `resolve_tikz_labels()`).
#' @returns Character vector of TikZ lines.
#' @keywords internal
#' @noRd
classic_fit_tier_lines <- function(
  tier_node_map,
  intersect_names,
  tier_label_pos,
  tier_labels
) {
  tier_node_map <- lapply(tier_node_map, function(v) {
    intersect(v, intersect_names)
  })
  tier_node_map <- tier_node_map[lengths(tier_node_map) > 0]
  tier_names <- names(tier_node_map)
  labels <- tier_labels[tier_names]
  pos_info <- get_anchor_and_offset(tier_label_pos, offset = 0.1)

  bands <- sprintf(
    "\\node[tier, inner sep=6pt, fit=(%s)] (%s) {};",
    vapply(tier_node_map, paste, character(1), collapse = ")("),
    tier_names
  )
  label_lines <- sprintf(
    "\\node[tier label, anchor=%s] at ($(%s.%s)+(%scm,%scm)$) {%s};",
    pos_info$anchor,
    tier_names,
    pos_info$anchor_point,
    pos_info$dx,
    pos_info$dy,
    labels
  )
  c(
    "\\begin{scope}[on background layer]",
    bands,
    "\\end{scope}",
    label_lines
  )
}

Try the causalDisco package in your browser

Any scripts or data that you put into this service are public.

causalDisco documentation built on Nov. 17, 2026, 5:08 p.m.