Created
July 23, 2013 17:03
-
-
Save jmoy/6064123 to your computer and use it in GitHub Desktop.
Visualizing a 2D random walk using Python, Cairo and GTK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
""" | |
Random walk on two-dimensional grid | |
(c) Jyotirmoy Bhattacharya, [email protected] | |
LICENSE: GPL3 | |
""" | |
import random | |
import gtk,gobject,cairo | |
import math | |
N = 51 #no of lattice points along each dimension | |
S = 2 #seconds to sleep between frames | |
points = set() | |
cur = (N//2+1,N//2+1) | |
mycanvas = None | |
def add_point(): | |
global points,cur | |
inc = random.choice((-1,1)) | |
d = random.choice(('v','h')) | |
nx = cur[0] | |
ny = cur[1] | |
if d=='h': | |
nx = (nx+inc)%(N+1) | |
else: | |
ny = (ny+inc)%(N+1) | |
nxt = (nx,ny) | |
points.add(nxt) | |
cur = nxt | |
def tick(): | |
global mycanvas | |
add_point() | |
mycanvas.queue_draw() | |
return True | |
class Canvas(gtk.DrawingArea): | |
# Draw in response to an expose-event | |
__gsignals__ = { "expose-event": "override" } | |
# Handle the expose-event by drawing | |
def do_expose_event(self, event): | |
# Create the cairo context | |
cr = self.window.cairo_create() | |
# Restrict Cairo to the exposed area; avoid extra work | |
cr.rectangle(event.area.x, event.area.y, | |
event.area.width, event.area.height) | |
cr.clip() | |
self.draw(cr, *self.window.get_size()) | |
def draw(self, cr, width, height): | |
scale_x = float(width)/(N+1) | |
scale_y = float(height)/(N+1) | |
# Draw lines with gray | |
cr.set_source_rgb(0.5, 0.5, 0.5) | |
for p in points: | |
if p==cur: | |
continue | |
cr.arc(p[0]*scale_x,p[1]*scale_y,2,0,2*math.pi) | |
cr.fill() | |
cr.set_source_rgb(1,0,0) | |
cr.arc(cur[0]*scale_x,cur[1]*scale_y,2,0,2*math.pi) | |
cr.fill() | |
if __name__ == "__main__": | |
window = gtk.Window() | |
window.connect("delete-event", gtk.main_quit) | |
mycanvas = Canvas() | |
mycanvas.show() | |
window.add(mycanvas) | |
window.present() | |
gobject.timeout_add_seconds(S,tick) | |
gtk.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment