forked from neozhaoliang/pywonderland
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaztec.py
191 lines (156 loc) · 6.58 KB
/
aztec.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Domino shuffling algorithm on Aztec diamond graphs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This script samples a random domino tiling of an Aztec diamond graph
with uniform probability.
Usage: python aztec.py [-s] [-o] [-f]
Optional arguments:
-s size of the image.
-o order of the Aztec diamond graph.
-f output file.
:copyright (c) 2015 by Zhao Liang.
"""
import argparse
import random
import cairocffi as cairo
# 4 colors for the 4 types of dominoes
N_COLOR = (1, 0, 0)
S_COLOR = (0.75, 0.75, 0)
W_COLOR = (0, 0.5, 0)
E_COLOR = (0, 0, 1)
class AztecDiamond(object):
"""Use a dict to represent a tiling of an Aztec diamond graph.
Items in the dict are of the form {cell: type} where a cell is a
1x1 unit square and is specified by the coordinate of its left bottom
corner. Each cell has five possible types: 'n', 's', 'w', 'e', None,
here None means it's an empty cell.
Be careful that one should always start from the boundary when
deleting or filling blocks, this is an implicit but important
part in the algorithm.
"""
def __init__(self, n):
"""Create an Aztec diamond graph of order n with an empty tiling."""
self.order = n
self.cells = []
for j in range(-n, n):
k = min(n+1+j, n-j)
for i in range(-k, k):
self.cells.append((i, j))
self.tile = {cell: None for cell in self.cells}
@staticmethod
def block(i, j):
"""Return the 2x2 block with its bottom-left cell at (i, j)."""
return [(i, j), (i+1, j), (i, j+1), (i+1, j+1)]
def is_black(self, i, j):
"""Check if cell (i, j) is colored black.
Note that the chessboard is colored in the fashion that the
leftmost cell in the top row is white.
"""
return (i + j + self.order) % 2 == 1
def check_block(self, i, j, dominoes):
"""Check whether a block is filled with dominoes of given orientations."""
return all(self.tile[cell] == fill for cell, fill in zip(self.block(i, j), dominoes))
def fill_block(self, i, j, dominoes):
"""Fill a block with two parallel dominoes of given orientations."""
for cell, fill in zip(self.block(i, j), dominoes):
self.tile[cell] = fill
def delete(self):
"""Delete all bad blocks in a tiling.
A block is called bad if it contains a pair of parallel dominoes that
have orientations toward each other.
"""
for i, j in self.cells:
try:
if (self.check_block(i, j, ['n', 'n', 's', 's'])
or self.check_block(i, j, ['e', 'w', 'e', 'w'])):
self.fill_block(i, j, [None]*4)
except KeyError:
pass
return self
def slide(self):
"""Move all dominoes one step according to their orientations."""
new_board = AztecDiamond(self.order + 1)
for (i, j) in self.cells:
if self.tile[(i, j)] == 'n':
new_board.tile[(i, j+1)] = 'n'
if self.tile[(i, j)] == 's':
new_board.tile[(i, j-1)] = 's'
if self.tile[(i, j)] == 'w':
new_board.tile[(i-1, j)] = 'w'
if self.tile[(i, j)] == 'e':
new_board.tile[(i+1, j)] = 'e'
return new_board
def create(self):
"""Fill all holes with pairs of dominoes that leaving each other.
This is a somewhat subtle step since the new Aztec graph returned
by the sliding step is placed on a different chessboard which is
colored in the opposite fashion!
"""
for i, j in self.cells:
try:
if self.check_block(i, j, [None]*4):
if random.random() > 0.5:
self.fill_block(i, j, ['s', 's', 'n', 'n'])
else:
self.fill_block(i, j, ['w', 'e', 'w', 'e'])
except KeyError:
pass
return self
def render(self, size, extent, filename, bg_color=(1, 1, 1)):
"""Draw current tiling (might have holes) to a png image with cairo.
size:
image size in pixels, e.g. size = 600 means 600x600
extent:
range of the axis: [-extent, extent] x [-extent, extent]
filename:
output filename, must be a .png image.
bg_color:
background color, default to white.
If set to None then transparent background will show through.
"""
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size)
surface.set_fallback_resolution(100, 100)
ctx = cairo.Context(surface)
ctx.scale(size/(2.0*extent), -size/(2.0*extent))
ctx.translate(extent, -extent)
if bg_color is not None:
ctx.set_source_rgb(*bg_color)
ctx.paint()
margin = 0.1
for (i, j) in self.cells:
if (self.is_black(i, j) and self.tile[(i, j)] is not None):
if self.tile[(i, j)] == 'n':
ctx.rectangle(i - 1 + margin, j + margin,
2 - 2 * margin, 1 - 2 * margin)
ctx.set_source_rgb(*N_COLOR)
if self.tile[(i, j)] == 's':
ctx.rectangle(i + margin, j + margin,
2 - 2 * margin, 1 - 2 * margin)
ctx.set_source_rgb(*S_COLOR)
if self.tile[(i, j)] == 'w':
ctx.rectangle(i + margin, j + margin,
1 - 2 * margin, 2 - 2 * margin)
ctx.set_source_rgb(*W_COLOR)
if self.tile[(i, j)] == 'e':
ctx.rectangle(i + margin, j - 1 + margin,
1 - 2 * margin, 2 - 2 * margin)
ctx.set_source_rgb(*E_COLOR)
ctx.fill()
surface.write_to_png(filename)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-size', metavar='s', type=int,
default=800, help='image size')
parser.add_argument('-order', metavar='o', type=int,
default=60, help='order of az graph')
parser.add_argument('-filename', metavar='f', type=str,
default='randomtiling.png', help='output filename')
args = parser.parse_args()
az = AztecDiamond(0)
for _ in range(args.order):
az = az.delete().slide().create()
az.render(args.size, args.order + 1, args.filename)
if __name__ == '__main__':
main()