Ecuaciones graficas

R_GAS <- 8.314
P_ATM <- 1.0e5
CONV  <- 6.022e23 / 1e3
DT_NUM <- 1e-6

SPECIES <- c("H2", "O2", "H", "O", "HO", "H2O")
NS <- length(SPECIES)
IDX <- setNames(seq_len(NS), SPECIES)

mk_rx <- function(name, reactants, products, fwd, bwd,
                  sym_f = 1, sym_b = 1, s_f = 0.5, s_b = 0.5,
                  conv_f = TRUE, conv_b = TRUE) {
  list(name = name, reactants = reactants, products = products,
       fwd = fwd, bwd = bwd, sym_f = sym_f, sym_b = sym_b,
       s_f = s_f, s_b = s_b, conv_f = conv_f, conv_b = conv_b)
}

REACTIONS <- list(
  mk_rx("Iniciacion", c(H2 = 1, O2 = 1), c(HO = 2),
        fwd = c(2.82e-11, 0.00, -2.42e4), bwd = c(1.09e-13, 0.26, -1.47e4),
        sym_b = 0.5),
  mk_rx("Propagacion", c(HO = 1, H2 = 1), c(H = 1, H2O = 1),
        fwd = c(1.83e-15, 1.30, -1.84e3), bwd = c(1.79e-14, 1.20, -9.61e3)),
  mk_rx("1a ramificacion", c(H = 1, HO = 1), c(O = 1, H2 = 1),
        fwd = c(1.40e-14, 1.00, -3.50e3), bwd = c(3.00e-14, 1.00, -4.48e3)),
  mk_rx("2a ramificacion", c(O = 1, HO = 1), c(H = 1, O2 = 1),
        fwd = c(2.72e-12, 0.28, 8.10e1), bwd = c(3.70e-10, 0.00, -8.45e3)),
  mk_rx("Terminacion (pared)", c(H = 2), c(H2 = 1),
        fwd = c(1.80e-11, -1.00, 0.0), bwd = c(3.70e-10, 0.00, -4.83e-4),
        sym_f = 0.5, s_b = 1.0, conv_b = FALSE)
)

k_arrhenius <- function(abc, T, convert = TRUE) {
  k <- abc[1] * T^abc[2] * exp(abc[3] / T)
  if (convert) k * CONV else k
}

build_system <- function(reactions, T) {
  nr <- 2 * length(reactions)
  k <- numeric(nr); sym <- rep(1, nr)
  delta <- matrix(0, nr, NS)
  idx <- vector("list", nr); ex <- vector("list", nr)
  for (j in seq_along(reactions)) {
    rx <- reactions[[j]]
    f <- 2 * j - 1; b <- 2 * j
    k[f] <- k_arrhenius(rx$fwd, T, rx$conv_f)
    k[b] <- k_arrhenius(rx$bwd, T, rx$conv_b)
    sym[f] <- rx$sym_f; sym[b] <- rx$sym_b
    idx[[f]] <- unname(IDX[names(rx$reactants)]); ex[[f]] <- unname(rx$reactants)
    idx[[b]] <- unname(IDX[names(rx$products)]);  ex[[b]] <- unname(rx$products)
    for (s in names(rx$reactants)) {
      n <- rx$reactants[[s]]
      delta[f, IDX[s]] <- delta[f, IDX[s]] - n * rx$s_f
      delta[b, IDX[s]] <- delta[b, IDX[s]] + n * rx$s_b
    }
    for (s in names(rx$products)) {
      n <- rx$products[[s]]
      delta[f, IDX[s]] <- delta[f, IDX[s]] + n * rx$s_f
      delta[b, IDX[s]] <- delta[b, IDX[s]] - n * rx$s_b
    }
  }
  list(k = k, sym = sym, delta = delta, idx = idx, ex = ex, nr = nr)
}

integrate_kin <- function(reactions, c0, T, t_end = Inf, max_steps = 300000,
                          eq_tol = 0, stall = Inf) {
  sy <- build_system(reactions, T)
  nr <- sy$nr
  c <- as.numeric(c0)
  rec_t  <- numeric(max_steps)
  rec_dt <- numeric(max_steps)
  rec_c  <- matrix(0, max_steps, NS)
  rec_c[1, ] <- c
  rates <- numeric(nr)
  t <- 0; n <- 1L
  while (n < max_steps && t < t_end) {
    for (r in seq_len(nr))
      rates[r] <- sy$k[r] * sy$sym[r] * prod(c[sy$idx[[r]]]^sy$ex[[r]])
    maxr <- max(rates)
    if (maxr <= 0) break
    if (eq_tol > 0 && n > 6) {
      a <- rates[seq(1, nr, 2)]; b <- rates[seq(2, nr, 2)]
      if (all(abs(a - b) <= eq_tol * pmax(a, b))) break
    }
    dt <- DT_NUM / maxr
    if (n > 20 && dt > stall * t) break
    t <- t + dt
    c <- c + as.vector(crossprod(sy$delta, rates * dt))
    c[c < 0] <- 0
    n <- n + 1L
    rec_t[n] <- t; rec_dt[n] <- dt; rec_c[n, ] <- c
  }
  if (n >= max_steps) message("  [aviso] se alcanzo max_steps = ", max_steps)
  list(t = rec_t[1:n], dt = rec_dt[1:n], c = rec_c[1:n, , drop = FALSE])
}

initial_concentrations <- function(moles, T, P_pa = P_ATM) {
  n_tot <- sum(unlist(moles))
  V_L <- n_tot * R_GAS * T / P_pa * 1e3
  c0 <- numeric(NS)
  for (s in names(moles)) if (s %in% SPECIES) c0[IDX[s]] <- moles[[s]] / V_L
  list(c0 = c0, V = V_L)
}
c_ref_pairwise <- function(T, P_pa = P_ATM) 0.5 * P_pa / (R_GAS * T) / 1e3

time_unit <- function(tmax) {
  if (tmax >= 3600) list(u = 3600, lab = "h")
  else if (tmax >= 1) list(u = 1, lab = "s")
  else if (tmax >= 1e-3) list(u = 1e-3, lab = "ms")
  else if (tmax >= 1e-6) list(u = 1e-6, lab = "us")
  else list(u = 1e-9, lab = "ns")
}
thin_idx <- function(n, nmax = 6000) {
  if (n <= nmax) return(seq_len(n))
  sort(unique(c(seq_len(min(400, n)), round(seq(1, n, length.out = nmax)))))
}
COLS <- c(H2 = "#1f77b4", O2 = "#ff7f0e", H = "#d62728", O = "#2ca02c",
          HO = "#9467bd", H2O = "#8c564b")

figure2 <- function(T, outdir, max_steps = 200000) {
  cat("Fig. 2: reacciones individuales ...\n")
  cref <- c_ref_pairwise(T)
  png(file.path(outdir, "fig2_reacciones_individuales.png"),
      width = 1650, height = 2000, res = 150)
  par(mfrow = c(length(REACTIONS), 2), mar = c(4, 4.5, 3, 1), oma = c(0, 0, 2, 0))
  for (rx in REACTIONS) {
    for (sentido in c("directa", "inversa")) {
      side <- if (sentido == "directa") rx$reactants else rx$products
      c0 <- numeric(NS)
      for (s in names(side)) c0[IDX[s]] <- side[[s]] * cref
      res <- integrate_kin(list(rx), c0, T, max_steps = max_steps,
                           eq_tol = 1e-2, stall = 1.5)
      t <- res$t; cm <- res$c
      dev <- rowSums(abs(sweep(cm, 2, cm[nrow(cm), ])))
      hit <- which(dev < 0.01 * dev[1])
      t_win <- if (dev[1] > 0 && length(hit) > 0) min(6 * t[hit[1]], t[length(t)])
               else min(t[length(t)], 3600)
      keep <- t <= t_win
      if (sum(keep) < 3) keep[1:3] <- TRUE
      t <- t[keep]; cm <- cm[keep, , drop = FALSE]
      tu <- time_unit(t[length(t)])
      ii <- thin_idx(length(t))
      sp <- unique(c(names(rx$reactants), names(rx$products)))
      ylim <- range(cm[, IDX[sp]] * 1e3, cref * 1e3)
      plot(NA, xlim = range(t[ii] / tu$u), ylim = ylim,
           xlab = paste0("t [", tu$lab, "]"), ylab = "c [1e-3 mol/L]",
           main = paste0(rx$name, " - arranque ", sentido), cex.main = 0.95)
      grid()
      for (s in sp) lines(t[ii] / tu$u, cm[ii, IDX[s]] * 1e3, col = COLS[[s]], lwd = 1.6)
      abline(h = cref * 1e3, lty = 2, col = "gray50")
      legend("right", legend = sp, col = unlist(COLS[sp]), lwd = 1.6, cex = 0.7, bty = "n")
    }
  }
  mtext(sprintf("Historias temporales de reacciones individuales (T = %.0f K, P = 1 atm)", T),
        outer = TRUE, cex = 1.1)
  dev.off()
}

figure4_5 <- function(T, t_end, outdir, max_steps = 300000) {
  cat("Fig. 4 y 5: mecanismo global ...\n")
  ic <- initial_concentrations(list(H2 = 2.0, O2 = 1.0, N2 = 3.76), T)
  cat(sprintf("  V = %.1f L, [H2]0 = %.4e, [O2]0 = %.4e mol/L\n",
              ic$V, ic$c0[IDX["H2"]], ic$c0[IDX["O2"]]))
  tic <- proc.time()
  res <- integrate_kin(REACTIONS, ic$c0, T, t_end = t_end, max_steps = max_steps)
  cat(sprintf("  %d pasos en %.1f s\n", length(res$t) - 1, (proc.time() - tic)[["elapsed"]]))
  t <- res$t; dt <- res$dt; cm <- res$c

  t_ign <- dt[2]
  tau <- t - t_ign
  in_expl <- which(tau > 0 & tau < 100e-6 & seq_along(t) >= 3)
  dt_max <- max(dt[in_expl])
  S <- rowSums(cm)
  cat(sprintf("  Retardo de ignicion Dt1       = %.4f s   (articulo: 0.3009 s)\n", t_ign))
  cat(sprintf("  Max. Dt en explosion (post-1) = %.2f us  (articulo: 11.90 us)\n", dt_max * 1e6))
  cat(sprintf("  Dt1 / Dtmax                   = %s      (articulo: 25,286)\n",
              format(round(t_ign / dt_max), big.mark = ",")))
  cat(sprintf("  Sum c inicial = %.4e, final = %.4e, 2/3*Sum c0 = %.4e mol/L\n",
              S[1], S[length(S)], 2 / 3 * S[1]))

  png(file.path(outdir, "fig4_mecanismo_global.png"), width = 1350, height = 1800, res = 150)
  par(mfrow = c(3, 1), mar = c(4, 4.5, 3, 1))
  ii <- thin_idx(length(t))
  plot(NA, xlim = range(t), ylim = range(cm * 1e3), xlab = "t [s]",
       ylab = "c [1e-3 mol/L]",
       main = sprintf("(a) Vista macroscopica - retardo de ignicion Dt1 = %.4f s", t_ign))
  grid()
  for (s in SPECIES) lines(t[ii], cm[ii, IDX[s]] * 1e3, col = COLS[[s]], lwd = 1.6)
  abline(v = t_ign, lty = 3)
  legend("right", legend = SPECIES, col = unlist(COLS), lwd = 1.6, cex = 0.8, bty = "n")

  m <- which(tau >= 0 & tau <= 0.7e-3)
  jj <- m[thin_idx(length(m))]
  plot(NA, xlim = c(0, 0.7), ylim = range(cm[m, ] * 1e3), xlab = "t - Dt1 [ms]",
       ylab = "c [1e-3 mol/L]",
       main = "(b) Vista microscopica (region de explosion y equilibrio)")
  grid()
  for (s in SPECIES) lines(tau[jj] * 1e3, cm[jj, IDX[s]] * 1e3, col = COLS[[s]], lwd = 1.6)
  legend("right", legend = SPECIES, col = unlist(COLS), lwd = 1.6, cex = 0.8, bty = "n")

  m <- which(tau > 0 & tau <= 70e-6)
  plot(tau[m] * 1e6, dt[m] * 1e6, type = "l", lwd = 1, xlab = "t - Dt1 [us]",
       ylab = "Dt [us]", main = "(c) Longitud del paso Dt en los primeros 70 us de la explosion")
  grid()
  dev.off()

  png(file.path(outdir, "fig5_concentracion_total.png"), width = 1200, height = 700, res = 150)
  par(mar = c(4, 4.5, 3, 1))
  m <- which(tau >= 0 & tau <= 5e-3)
  jj <- m[thin_idx(length(m))]
  plot(tau[jj] * 1e3, S[jj] * 1e3, type = "l", lwd = 1.8, col = "#1f77b4",
       ylim = c(0, max(S[jj] * 1e3)), xlab = "t - Dt1 [ms]", ylab = "Sum c [1e-3 mol/L]",
       main = "Concentracion total -> 2/3  (2 H2 + O2 -> 2 H2O)")
  grid()
  abline(h = 2 / 3 * S[1] * 1e3, lty = 2, col = "gray40")
  legend("topright", legend = c("Sum c_i", "2/3 del valor inicial"),
         col = c("#1f77b4", "gray40"), lty = c(1, 2), lwd = c(1.8, 1), bty = "n")
  dev.off()

  out <- data.frame(t_s = t, dt_s = dt, cm)
  names(out)[3:(2 + NS)] <- SPECIES
  write.csv(out, file.path(outdir, "serie_global.csv"), row.names = FALSE)
}

figure7 <- function(outdir) {
  cat("Fig. 7: limite de explosion ...\n")
  T <- seq(600, 1000, length.out = 200)
  k_if <- sapply(T, function(Ti) k_arrhenius(REACTIONS[[1]]$fwd, Ti))
  dts <- c(0.1, 1, 10, 100, 1000)
  png(file.path(outdir, "fig7_limite_explosion.png"), width = 1100, height = 1000, res = 150)
  par(mar = c(4.5, 4.5, 4, 1))
  plot(NA, xlim = c(600, 1000), ylim = c(0, 2), xlab = "T [K]", ylab = "P [atm]",
       main = "Curvas de igual retardo de ignicion (H2:O2 = 2:1)\nExplosion: Dt1 < 10 s")
  grid()
  pal <- c("#1f77b4", "#ff7f0e", "#d62728", "#2ca02c", "#9467bd")
  for (i in seq_along(dts)) {
    c_tot <- sqrt(9 * DT_NUM / (2 * k_if * dts[i]))
    P_atm <- c_tot * 1e3 * R_GAS * T / P_ATM
    lines(T, P_atm, col = pal[i], lty = if (dts[i] == 10) 1 else 2,
          lwd = if (dts[i] == 10) 2.5 else 1.2)
  }
  legend("topright", col = pal, lwd = c(1.2, 1.2, 2.5, 1.2, 1.2), lty = c(2, 2, 1, 2, 2),
         legend = sprintf("Dt1 = %g s%s", dts, ifelse(dts == 10, " (limite)", "")), bty = "n")
  dev.off()

  Tt <- 900
  n_L <- P_ATM / (R_GAS * Tt) / 1e3
  c0 <- numeric(NS); c0[IDX["H2"]] <- 2 / 3 * n_L; c0[IDX["O2"]] <- 1 / 3 * n_L
  r <- integrate_kin(REACTIONS, c0, Tt, max_steps = 5)
  k900 <- k_arrhenius(REACTIONS[[1]]$fwd, Tt)
  cat(sprintf("  Chequeo T=900 K, P=1 atm: Dt1 integrador = %.4f s, formula = %.4f s\n",
              r$dt[2], DT_NUM / (k900 * c0[IDX["H2"]] * c0[IDX["O2"]])))
}

main <- function() {
  args <- commandArgs(trailingOnly = TRUE)
  want <- if (length(args)) args else c("fig2", "fig4", "fig5", "fig7")
  outdir <- "figuras_cinetica_R"
  dir.create(outdir, showWarnings = FALSE)
  T <- 1000
  if ("fig2" %in% want) figure2(T, outdir)
  if (any(c("fig4", "fig5") %in% want)) figure4_5(T, t_end = 1.2, outdir = outdir)
  if ("fig7" %in% want) figure7(outdir)
}
if (sys.nframe() == 0) main()