# R code to accompany the noteboook "Branching Processes"
# which should be at http://bactra.org/notebooks/branching-processes.html

# Draw a branching process with k generations
  # Always start from a single ancestor
  # More iteration than is probably ideal in R, but oh well   
# Inputs:
  # Number of generations (k)
    # Assumed to be at least 3
  # Function for sampling from offspring distribution (roffspring)
    # Required that the first argument be n
  # Optional additional arguments to roffspring (...)
# Output: a directed graph, in the format of the "network" object
# Side-effect: network is plotted
# Presumes without checking:
  # roffspring returns non-negative integers
rgaltonwatson <- function(k, roffspring, ...) {
  stopifnot(require(network))
  stopifnot(k>2)
  # Keep track of how big each generation is (k numbers)
  generation.sizes <- vector(length=k) 
  generation.sizes[1] <- 1
 # Track number of offspring per individual by generation (k-1 vectors)
  generation.counts <- list(length=k-1)
  for (t in 2:k) {
    # Randomly draw offspring numbers, one per member of the previous generation
    if (generation.sizes[t-1] > 0) {
      generation.counts[[t-1]] <- roffspring(n=generation.sizes[t-1], ...)
    } else {
       generation.counts[[t-1]] <- 0
    }
    # Sum up for future reference
    generation.sizes[t] <- sum(generation.counts[[t-1]])
  }
  # Label individuals by generation
  generation.labels <- rep(1:k, times=generation.sizes)
  # How many individuals in the total branching process?
  n <- length(generation.labels)
  # Create an adjacency matrix
  adj <- matrix(0, nrow=n, ncol=n)
  # Fill in the adjacency matrix
  for (t in 1:(k-1)) {
    # Who are all the members of that generation?
    senders <- which(generation.labels==t)
    # Who are all the members of the _next_ generation?
    offspring <- which(generation.labels==(t+1))
    # Skip if there aren't any offspring!
    if (length(offspring) > 0) {
       # Parents' positions within the previous generation
       child.of <- rep(1:length(senders), times=generation.counts[[t]])
       for (i in 1:length(senders)) {
          sender <- senders[i]
         receivers <- offspring[which(child.of==i)]
         adj[sender, receivers] <- 1
      }
    }
  }
  # Color nodes by generation
  node.colors <- rep(1:k, times=generation.sizes)
  # Nodes are round, unless they have no children (squares) or are the
  # last displayed generation (triangles)
  out.degrees <- rowSums(adj)
  node.sides <- ifelse(out.degrees > 0, 50, 4)
  node.sides[generation.labels==k] <- 3
  the.network <- as.network(adj)
  plot(the.network, vertex.col=topo.colors(k)[node.colors],
       vertex.sides=node.sides)
  invisible(the.network)
}



# First figure:

nr <- 4
par(mfcol=c(nr,3))
replicate(nr, rgaltonwatson(k=5, roffspring=rpois, lambda=0.9))
replicate(nr, rgaltonwatson(k=5, roffspring=rpois, lambda=1.0))
replicate(nr, rgaltonwatson(k=5, roffspring=rpois, lambda=2))


# Second figure:

par(mfrow=c(1,1))
curve(exp(0.9*(x-1)), from=0, to=1, lty=1, pty="s", ylim=c(0,1), xlim=c(0,1),
      xlab="x", ylab="f(x)")
curve(exp(1.0*(x-1)), add=TRUE, lty=2)
curve(exp(2.0*(x-1)), add=TRUE, lty=3)
abline(0,1, col="grey")
legend("topleft", legend=paste("mu", "==", c(0.9, 1.0, 2.0)),
       lty=1:3)
