Generating a Markov Chain vs. Computing the Transition Matrix
Join the DZone community and get the full member experience.
Join For Free
a couple of days ago, we had a quick chat on karl broman ‘s blog, about snakes and ladders (see http://kbroman.wordpress.com/… ) with karl and corey (see http://bayesianbiologist.com/…. ), and the use of markov chain. i do believe that this application is truly awesome: the example is understandable by anyone, and computations (almost any kind, from what we’ve tried) are easy to perform. at the same time, some french students asked me specific details regarding some old lectures notes on markov chains, and on some introductory example i used as a possible motivation: the stepping stone algorithm. in the notes, i just mentioned the idea of this popular generic algorithm (introduced in sawyer (1976) ) and i use simulations to show  visually  how it works. again, it was just to motivate the course which actually did focus on the theory of markov chains. but those student wanted more, like how did i get the transition matrix, for instance. and that is actually not a simple question, from a computational perspective. i mean, i can easily generate this markov chain, but writing explicitly the transition, that was another story. which took me a bit longer. in a very specific case…
but let us get back to the roots, and to the stepping stone algorithm. at least, one of them (the one i used in my notes) because it looks like there are several algorithm. we do consider a grid, say , with some colors inside, say possible colors. each cell of the grid has a given color. then, at some stage, we select randomly one cell in the grid, and it will take the color of one of its neighbor (some kind of absorption, or mutation). this is, more or less, what is also detailed in some lecture notes by james propp (see also e sato (1983) or zähle et al. (2005) for more theoretical details about that markov chain). this is extremely simple to generate (that’s what i did in my notes, with very big grids, and a lot of colors). but what if we want to write the transition matrix ?
first of all, we need to define the state space. basically, we do have cells, each of them has one color, chosen among . which gives us possible states…. and that can be large. i mean, if we consider the smallest possible grid (that might be interesting), say , and only colors, then we talk about possible states. that is large, not huge. but we should keep in mind that we have to compute a transition matrix, that would be a matrix with elements. more generally, we talk about writing down matrices with elements. if we want black and white grids, that would mean a matrix with which mean 4 billion elements ! and if we consider an redgreenblue grid, we have to explicit a matrix with i.e almost 400 million elements. so, let’s face it: we can only work with bicolor grids.
so let’s try… the good thing is that it can be related to work i’ve been doing recently on binomial recombining trees (binomial being related to bicolor). first of all, our grid will be describes as follows
> h=3 > m=matrix(1:(h^2),h,h) > m [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9
with two colors
> color=c("red","blue")
then, we should look for neighbors, or derive an neighborhood matrix,
> d=function(i,j) dist(rbind(c((i1)%/%h,(i1)%%h), + c((j1)%/%h,(j1)%%h))) > neighb=matrix(vectorize(d)(rep(1:(h^2),each=h^2), + rep(1:(h^2),h^2)),h^2,h^2) > trunc(neighb*100)/100 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 0.00 1.00 2.00 1.00 1.41 2.23 2.00 2.23 2.82 [2,] 1.00 0.00 1.00 1.41 1.00 1.41 2.23 2.00 2.23 [3,] 2.00 1.00 0.00 2.23 1.41 1.00 2.82 2.23 2.00 [4,] 1.00 1.41 2.23 0.00 1.00 2.00 1.00 1.41 2.23 [5,] 1.41 1.00 1.41 1.00 0.00 1.00 1.41 1.00 1.41 [6,] 2.23 1.41 1.00 2.00 1.00 0.00 2.23 1.41 1.00 [7,] 2.00 2.23 2.82 1.00 1.41 2.23 0.00 1.00 2.00 [8,] 2.23 2.00 2.23 1.41 1.00 1.41 1.00 0.00 1.00 [9,] 2.82 2.23 2.00 2.23 1.41 1.00 2.00 1.00 0.00 > neighb=(neighb<2)&(neighb>0) > neighb [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] false true false true true false false false false [2,] true false true true true true false false false [3,] false true false false true true false false false [4,] true true false false true false true true false [5,] true true true true false true true true true [6,] false true true false true false false true true [7,] false false false true true false false true false [8,] false false false true true true true false true [9,] false false false false true true false true false
now, let us explicit our 512 possible states.
> n=h^2 > states=function(x){ + base.b=rep(0,n) + ndigits=(floor(logb(x,base=length(color)))+1) + for(i in 1:ndigits){ + base.b[ni+1]=(x%%length(color)) + x=(x %/% length(color))} + return(base.b)} > m=vectorize(states)(1:(length(color)^n1)) > liststates=data.frame(rbind(rep(0,h^2),t(m))) > head(liststates) x1 x2 x3 x4 x5 x6 x7 x8 x9 1 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 1 3 0 0 0 0 0 0 0 1 0 4 0 0 0 0 0 0 0 1 1 5 0 0 0 0 0 0 1 0 0 6 0 0 0 0 0 0 1 0 1
(for the first six, with 0/1 digits instead of colors). for instance, if we look at a specific one, it is possible to plot the grid, using
> plotsteps=function(u){ + plot(0:h,0:h,col="white",xlab="",ylab="",axes=false) + for(i in 0:(h^21)){ + x=i%/%h + y=i%%h + polygon(x+c(1,.1,.1,1),y+c(1,1,.1,.1), + col=color[as.numeric(u)[i+1] + 1]) + text(x+.45,y+.45,i) + }}
here,
> plotsteps(liststates[100,])
then, given one state, let us see what could happen next,
 let us compute all connected states: all states where we can end up in if we change one cell
 we have to check, for each connect state which cell did change
 we should compute probabilities to reach those 9 states, based on the fact that each of the cell is chosen with the same probability, and the fact that probability to change the color is based on the colors around.
 if some states cannot be reached (if a cell is surrounded by elements of the same color, so it cannot change its color), then, we should remove then from the list of reachable (possible) states.
the code will be something like the following
> listneighbour=function(i){ + start=liststates[i,] + difference2only=function(j) { + w=which(liststates[j,]!=liststates[i,]) + return((length(w)==1))} + possible=which( vectorize(difference2only)(1:nrow(liststates))==true ) + p=function(j){ + l=liststates[i,which(neighb[which(liststates[j,]!=liststates[i,]),]==true)] + t=table(as.numeric(l)) + t=t[as.character(0:(length(color)1))] + t[is.na(t)]=0 + return(as.numeric(t)/sum(t)) + } + probability=vectorize(p)(possible) + w=null + for(j in possible) w=c(w,which(liststates[j,]!=liststates[i,])) + i=1liststates[i,w]+1 + vp=diag(probability[as.numeric(i),]) + vproba=0*vp + if(sum(vp)!=0) vproba=vp/sum(vp) + return(list( + color=liststates[i,w], + absorb=w, + possible=possible, + probability=probability, + prob=vproba)) + }
for instance, if we start from state 100 (here, on the right)
> listneighbour(100) $color x3 x4 x8 x9 x7 x6 x5 x2 x1 100 1 1 1 1 0 0 0 0 0 $absorb [1] 3 4 8 9 7 6 5 2 1 $possible [1] 36 68 98 99 104 108 116 228 356 $probability [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 1 0.8 0.6 0.6667 0.3333 0.4 0.5 0.6 0.6667 [2,] 0 0.2 0.4 0.3333 0.6667 0.6 0.5 0.4 0.3333 $prob [1] 0.17964072 0.14371257 0.10778443 0.11976048 0.11976048 [6] 0.10778443 0.08982036 0.07185629 0.05988024
let us look more specificaly at the 99th state (which appears above as a state that could be reached from the 100th),
> liststates[99,] x1 x2 x3 x4 x5 x6 x7 x8 x9 99 0 0 1 1 0 0 0 1 0
if we plot it (here on the right, again), we get
> plotsteps(liststates[99,])
clearly, here, the cell in the upper corner (number 9) changed from blue to red. now, about the probability… the probability to select cell 9 is 1/9, and given that cell 9 is chosen, the probability to go from blue to red is 2/3 (the cell is surrounded by 2 red cells, and 1 blue cell). the probability to remain blue is then 1/3. those are the probabilities computed by our function (the table with two rows, one per color). in order to get a better understanding on the meaning of the last line, with some sort of probabilities), let us look at the following (simpler) example.
> liststates[2,] x1 x2 x3 x4 x5 x6 x7 x8 x9 2 0 0 0 0 0 0 0 0 1
that can be visualized on the right (on the right). here,
> listneighbour(2) $color x9 x8 x7 x6 x5 x4 x3 x2 x1 2 1 0 0 0 0 0 0 0 0 $absorb [1] 9 8 7 6 5 4 3 2 1 $possible [1] 1 4 6 10 18 34 66 130 258 $probability [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 1 0.8 1 0.8 0.875 1 1 1 1 [2,] 0 0.2 0 0.2 0.125 0 0 0 0 $prob [1] 0.65573770 0.13114754 0.00000000 0.13114754 0.08196721 [6] 0.00000000 0.00000000 0.00000000 0.00000000
things are pretty simple here
 if we chose cells , then nothing change, since all the neighbors have the same color. so if we want to focus on changes (or say run the algorithm until the first color change, then choosing those cells is a waste of time)
 if we chose cells , then it could be possible to change the color. and actually, is different from (since it does have much more neighbors)
 if we chose cell , then definitively, the color will change, since all neighbors have the other color here,
now, the probability to select cell given that there was a color change would be, if is in
while if is in , then there are 4 out 5 neighbors that are red, so
and if is , then, only one neighbor has a different color, out of 8, so
and for the other, . so, it comes – since we assume that cells are drawn independently, and with the same probability , if is in
while if is in , then there are 4 out 5 neighbors that are red, so
and if is , then, only one neighbor has a different color, out of 8, so
which are exactly the probability computed above. the point is that we compute probabilities given that a color change will actually occur . the good point is that it should faster convergence to some limiting distribution. if any.
what about our transition matrix ? well, using a simply loop, we should get it easily
> m=matrix(0,nrow(liststates),nrow(liststates)) + for(i in 1:nrow(liststates)){ + l=listneighbour(i) + if(sum(l$prob)!=0){ + j=l$possible + m[i,j]=l$prob + } + if(sum(l$prob)==0){ + j=i + m[i,j]=1 + } + }
one can check that this matrix satisfies some properties of transition matrices. for instance, the sum per row is one,
> sum(apply(m,1,sum)!=1) [1] 0
remember that this matrix is big, so i will not print if here. but trust me, it works (it might take a while on an old laptop, but anyone can do it). now, if we want to visualize some paths of that chain, we can use the following algorithm. first, we need a starting point, that can be chosen randomly,
> j=sample(1:nrow(liststates),size=1)
or using a given colored grid, say
> j=100
then we plot it,
> plotsteps(liststates[j,])
now, the code within the loop is here
> d=rep(0,nrow(liststates)) > d[j]=1 > d=d%*%m > j=sample(1:nrow(m),size=1,prob=d) > plotsteps(liststates[j,])
here are some examples. and indeed, we end up either with all cells in blue, or all cells in red.




now, do we have to compute that transition matrix to produce those graph (and to generate that markov chain) ? no. of course not… at each step, i use a dirac measure, and use the transition matrix just to get the probability to generate then the next state. actually, one can write a faster and more intuitive code to generate the same chain… but i should probably keep that for another post…
Published at DZone with permission of Arthur Charpentier, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending

MLOps: Definition, Importance, and Implementation

Fun Is the Glue That Makes Everything Stick, Also the OCP

Hibernate Get vs. Load

Measuring Service Performance: The Whys and Hows
Comments