/
lsystems_v1.py
executable file
·308 lines (213 loc) · 8.17 KB
/
lsystems_v1.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python
######################################################################
#
# lsystems_v1.py
# Matt Zucker
#
######################################################################
#
# Based on documentation in https://en.wikipedia.org/wiki/L-system and
# http://paulbourke.net/fractals/lsys/
import sys
import argparse
from datetime import datetime
from collections import namedtuple
import numpy as np
from plot_segments import plot_segments
LSystem = namedtuple('LSystem', 'start, rules, turn_angle_deg, draw_chars')
# A few L-Systems found on pages linked above
KNOWN_LSYSTEMS = {
'sierpinski_triangle': LSystem(
start = 'F-G-G',
rules = dict(F='F-G+F+G-F', G='GG'),
turn_angle_deg = 120,
draw_chars = None
),
'sierpinski_arrowhead': LSystem(
start = 'A',
rules = dict(A='B-A-B', B='A+B+A'),
turn_angle_deg = 60,
draw_chars = None
),
'dragon_curve': LSystem(
start = 'FX',
rules = dict(X='X+YF+', Y='-FX-Y'),
turn_angle_deg = 90,
draw_chars = None
),
'barnsley_fern': LSystem(
start = 'X',
rules = dict(X='F+[[X]-X]-F[-FX]+X', F='FF'),
turn_angle_deg = 25,
draw_chars = None
),
'sticks': LSystem(
start = 'X',
rules = dict(X='F[+X]F[-X]+X', F='FF'),
turn_angle_deg = 20,
draw_chars = 'F'
),
'hilbert': LSystem(
start = 'L',
rules = dict(L='+RF-LFL-FR+', R='-LF+RFR+FL-'),
turn_angle_deg = 90,
draw_chars = 'F'
),
'pentaplexity': LSystem(
start = 'F++F++F++F++F',
rules = dict(F='F++F++F+++++F-F++F'),
turn_angle_deg = 36,
draw_chars = None
)
}
######################################################################
# make a big ol' string from an L-System starting from its start state
# using repeated string replacement.
def lsys_build_string(lsys, total_iterations):
lstring = lsys.start
rules = lsys.rules
for i in range(total_iterations):
output = ''
for symbol in lstring:
if symbol in rules:
output += rules[symbol]
else:
output += symbol
lstring = output
return lstring
######################################################################
# "draw" a single symbol from an L-System string
#
# stack is read-write
# segments is for appending
# cur_state is read and returned
def _lsys_execute_symbol(lsys, symbol, cur_state, stack, segments):
cur_pos, cur_angle_deg = cur_state
if symbol.isalpha():
if lsys.draw_chars is None or symbol in lsys.draw_chars:
cur_theta = cur_angle_deg * np.pi / 180
offset = np.array([np.cos(cur_theta), np.sin(cur_theta)])
new_pos = cur_pos + offset
segments.append([cur_pos, new_pos])
cur_pos = new_pos
elif symbol == '+':
cur_angle_deg += lsys.turn_angle_deg
elif symbol == '-':
cur_angle_deg -= lsys.turn_angle_deg
elif symbol == '[':
stack.append( ( cur_pos, cur_angle_deg ) )
elif symbol == ']':
return stack.pop()
else:
raise RuntimeError('invalid symbol:' + symbol)
return cur_pos, cur_angle_deg
######################################################################
# take a string and turn it into a set of line segments, returned as
# an n-by-2-by-2 array where each segment is represented as
#
# [(x0, y0), (x1, y1)]
def lsys_segments_from_string(lsys, lstring):
cur_pos = np.array([0., 0.])
cur_angle_deg = 0
cur_state = ( cur_pos, cur_angle_deg )
# stack of pos, angle pairs
stack = []
segments = []
for symbol in lstring:
cur_state = _lsys_execute_symbol(lsys, symbol, cur_state,
stack, segments)
return np.array(segments)
######################################################################
# build up segment list recursively - don't call this function
# directly, use lsys_segments_recursive instead
def _lsys_segments_r(lsys, s,
remaining_iterations,
cur_state,
state_stack,
segments):
# for each symbol in input
for symbol in s:
# see if we can run a replacement rule for this symbol
if remaining_iterations > 0 and symbol in lsys.rules:
# get the replacement
replacement = lsys.rules[symbol]
# recursively call this function with fewer remaining steps
cur_state = _lsys_segments_r(lsys, replacement,
remaining_iterations-1,
cur_state,
state_stack, segments)
else: # execute symbol directly
cur_state = _lsys_execute_symbol(lsys, symbol, cur_state,
state_stack, segments)
return cur_state
######################################################################
# build up segment list recursively by calling helper function above
def lsys_segments_recursive(lsys, total_iterations):
cur_pos = np.array([0., 0.])
cur_angle_deg = 0
cur_state = (cur_pos, cur_angle_deg)
state_stack = []
segments = []
s = lsys.start
_lsys_segments_r(lsys, s,
total_iterations,
cur_state,
state_stack,
segments)
return np.array(segments)
######################################################################
# parse command-line options for this program
def parse_options():
parser = argparse.ArgumentParser(
description='simple Python L-system renderer')
parser.add_argument('lname', metavar='LSYSTEM', nargs=1,
help='name of desired L-system',
type=str,
choices=KNOWN_LSYSTEMS)
parser.add_argument('total_iterations', metavar='ITERATIONS', nargs=1,
help='number of iterations', type=int)
parser.add_argument('-x', dest='max_segments', metavar='MAXSEGMENTS',
type=int, default=100000,
help='maximum number of segments to plot')
parser.add_argument('-t', dest='text_only', action='store_true',
help='use text output instead of PNG')
parser.add_argument('-s', dest='use_recursion', action='store_false',
default=True,
help='use string building method (default)')
parser.add_argument('-r', dest='use_recursion', action='store_true',
default=True,
help='use recursive method')
opts = parser.parse_args()
opts.lname = opts.lname[0]
opts.total_iterations = opts.total_iterations[0]
opts.lsys = KNOWN_LSYSTEMS[opts.lname]
if opts.use_recursion:
print('using recursive method')
else:
print('using string building method')
return opts
######################################################################
# main function
def main():
opts = parse_options()
# time segment generation
start = datetime.now()
if opts.use_recursion:
segments = lsys_segments_recursive(opts.lsys, opts.total_iterations)
else:
lstring = lsys_build_string(opts.lsys, opts.total_iterations)
segments = lsys_segments_from_string(opts.lsys, lstring)
# print elapsed time
elapsed = (datetime.now() - start).total_seconds()
print('generated {} segments in {:.6f} s ({:.3f} us/segment)'.format(
len(segments), elapsed, 1e6 * elapsed/len(segments)))
if opts.max_segments >= 0 and len(segments) > opts.max_segments:
print('...maximum of {} segments exceeded, skipping output!'.format(
opts.max_segments))
return
if opts.text_only:
np.savetxt('segments.txt', segments.reshape(-1, 4))
else:
plot_segments(segments)
if __name__ == '__main__':
main()