How do I display code and math side-by-side?

Here is another, slightly more complex function to keep the code in one raw block (Please excuse any typos in the example):

#let annotate-code(code, annotations) = {
  // Map the annotations to a dictionary for easy access
  let dict = annotations.map(((row, a)) => (str(row), a)).to-dict()
  let numbering = numbering.with("1")
  show raw.line: it => context {
    let num-width = measure(numbering(it.count)).width // Numbering shenanigens (not really necessary)
    set block(spacing: 0em)
    grid(
      columns: (auto, 1fr, auto),
      align: (right + horizon, left + horizon, right + horizon),
      box(
        width: num-width + 1em,
        inset: (right: 1em),
        text(fill: gray, numbering(it.number)),
      ),
      it.body,
      if str(it.number) in dict {
        dict.at(str(it.number))
      } else {
        []
      },
    )
  }
  code
}

You can then use the function as follows:

#annotate-code(
  ```R
  t_multiplier = 5; min_rate = 0.1; prior = 0.2

  replicate_psms <- c(19, 28, 25) # BIRC example from
  control_psms   <- c( 0,  0,  0) # KRAS4A Pull-Down
  lambda <- max(mean(control_psms), min_rate)
  rep_scores <- c()
  for (x in replicate_psms) {
    p_t_x <- prior * dpois(x, t_multiplier * lambda)
    p_f_x <- (1 - prior) * dpois(x, lambda)
    p_x <- p_t_x + p_f_x
    if (p_x > 0 ) {
      rep_score <- p_t_x / p_x
    } else {
      stopifnot(x > t_multiplier * lambda)
      rep_score <- 1
    }
    rep_scores <- c(rep_scores, rep_score)
  }
  score <- mean(rep_scores)
  ```,
  (
    (1, $ lambda_i^tau = 5 lambda_i^F quad pi_tau = 0.2 $),
    (
      5,
      $
        hat(lambda_i^F) = max((sum_(c = 1)^(N_italic("controls")) x_c) / N_italic("controls"), 0.1)
      $,
    ),
    (8, $ pi_tau P(x; lambda_i^tau) $),
    (9, $ (1 - pi_tau) P(x; lambda_i^F) $),
    (10, $ pi_tau P(x; lambda_i^tau) + (1 - pi_tau) P(x; lambda_i^F) $),
    (
      12,
      $
        P(Z_i = 1 | X_i = x) = (pi_tau P(x; lambda_i^tau)) / (pi_tau P(x; lambda_i^tau) + (1 - pi_tau) P(x; lambda_i^F))
      $,
    ),
    (
      17,
      $
        italic("Score")_i = (sum_(r = 1)^(N_italic("replicates") P(Z_i = 1 | X_i = x_r))) / N_italic("replicates")
      $,
    ),
  ),
)
Output

8 Likes