# # Animated MCMC for Hardcore model on a grid # Bryan Clair, June 2012 # from cs1graphics import * from HardcoreGrid import HardcoreGrid class HCAnimated: """A graphic display of the MCMC for the Hardcore model""" def __init__(self,state): """Create display and all (invisible) particles""" self._state = state self._sizex,self._sizey = state.size() self._spacing = 20 # between lines radius = self._spacing * .7 # sqrt(2)/2, basically self._c = Canvas((self._sizex-1)*self._spacing+2*radius, (self._sizey-1)*self._spacing+2*radius) # Draw the grids s = radius for x in range(self._sizex): self._c.add(Path(Point(s,radius),Point(s,self._c.getHeight()-radius))) s += self._spacing s = radius for y in range(self._sizey): self._c.add(Path(Point(radius,s),Point(self._c.getWidth()-radius,s))) s += self._spacing # Create the particles self._particles = list() for x in range(self._sizex): col = list() for y in range(self._sizey): p = Circle(radius, Point(radius+x*self._spacing,radius+y*self._spacing)) p.setFillColor('red' if (x+y)%2 else 'blue') col.append(p) if self._state.occupied(x,y): self._c.add(p) self._particles.append(col) def update(self,x,y): """Update the graphical display, given that (x,y) just changed""" if self._state.occupied(x,y): self._c.add(self._particles[x][y]) else: self._c.remove(self._particles[x][y]) if __name__ == '__main__': state = HardcoreGrid(20,20,1) pic = HCAnimated(state) steps = 0 while True: spot = state.oneStepGlauber() steps += 1 if steps % 1000 == 0: print 'density: %.2f\tpolarity: %.2f\tsteps: %d' %\ (state.density(),state.polarity(),steps) if spot: (x,y) = spot pic.update(x,y)