Tips for the Bubble Buddies problem

This in intended to gather possibly relevant tools, ingredients, tips to save you time on the programming, etc.

L <- 10
W <- 4  # length and width of home
radius <- 0.5   # size of bubbles

An example of possible locations for the buddies:

centers <- matrix(c(3,2,4,3,6,2), nrow=3, byrow=T)
centers
     [,1] [,2]
[1,]    3    2
[2,]    4    3
[3,]    6    2
# x and y coordinates of buddy number 2:
centers[2,]
[1] 4 3
# x coordinates of all three centers:
centers[,1]
[1] 3 4 6
# Largest difference between x coordinates of centers:
max(centers[,1]) - min(centers[,1])
[1] 3

In case you might find it helpful, here is a function you can use for plotting a configuration of centers:

myplot <- function(centers){
    nb <- nrow(centers)
    plot(c(0,L),c(0,W), type="n", xlab="", axes=F, ylab="", asp=1)
    rect(0,0,L,W)
    axis(1, pos=0, at=seq(0,L,by=2)) 
    axis(2, pos=0, at=c(0,W,by=2))
    symbols(centers[,1],centers[,2],circles=rep(radius,nb),inches=F,add=T)
}

myplot(centers)

A function to calculate the 3 distances separating pairs of buddies (analogous to the lengths of the 3 red dashed segments in the picture):

distances <- function(centers){
    nb <- nrow(centers)
    distances <- numeric(choose(nb,2))
    k <- 0
    for(i in 1:(nb-1)){
        for(j in (i+1):nb){
            k <- k+1
            distances[k] <- sqrt(sum((centers[i,]-centers[j,])^2))
        }
    }
    return(distances)
}

distances(centers)
[1] 1.414214 3.000000 2.236068

You can check the last result with the Pythagorean theorem to make sure you understand what is being done.

Average distance between the buddies’ centers (this gives the “average of the lengths of the 3 red dashed segments” quantity that the joint density depends on):

mean(distances(centers))
[1] 2.216761

You will probably want to use the “distances” function in writing a function “f” that specifies the desired density up to an unknown normalization constant (what we have been doing for Metropolis).

There are certain cases where you will want your f function to return 0, because there are restrictions on where the buddies’ centers can be. So you might want to write a function that returns different values in various cases. Here is an example of how you can define a function in R that does this kind of thing. I’ll call this function “g”:

g <- function(x){
    if(x < 0 | (x>4 & x<6) | x>10) return(x)
    else if(abs(x-7)<0.5)return("about 7 or so")
    else return(x^2)
}

# Note the vertical line "|" above means "or".  Let's try out the function g:

g(7.1)
[1] "about 7 or so"
g(5)
[1] 5
g(9)
[1] 81