-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsys.py
executable file
·360 lines (278 loc) · 9.64 KB
/
lsys.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python
"""
Classes and examples based on the Wikipedia article on L-systems:
https://en.wikipedia.org/wiki/L-system
"""
class ContextFreeGrammar(object):
"""
A grammar where each production rule refers only to an individual symbol
and not to its neighbours.
"""
def __init__(self, alphabet, axiom, rules):
"""
Initialize the grammar, validate the axiom and rules against the
alphabet.
:param Alphabet alphabet: The alphabet (variables and constants)
:param Axiom axiom: The initial state of the system
:param list rules: A list of `Rule` objects
:raises: `ValueError` if any of the `axiom` or `rules` can not be
validated against the supplied `alphabet`.
"""
# make sure the axiom contains only valid symbols.
alphabet.validate(axiom.symbols)
# a dict of rules key'd off their predecessor symbols.
# TODO: won't work with stochastic L-system
self._rule_lookup = {}
# validate each rule's predecessor and successor symbols against the
# alphabet
for rule in rules:
alphabet.validate(rule.predecessor)
alphabet.validate(rule.successor)
if rule.predecessor in self._rule_lookup:
raise ValueError(
"Multiple rules with predecessor '{p}'".format(
p=rule.predecessor)
)
else:
self._rule_lookup[rule.predecessor] = rule
self._alphabet = alphabet
self._axiom = axiom
self._rules = rules
def generate(self, iterations):
"""
Generate a string with the grammar.
:param int iterations: The number of iterations
:returns: The str generated by the grammar
"""
# The axiom provides the initial state of the system
state = self.axiom.symbols
# TODO: use logging instead. Too lazy to do now.
print "n=0 : {s}".format(s=state)
# Iterate and update the state of the system
for i in range(0, iterations):
# holds the modified state
new_state = []
# the context free part (one symbol at a time)
for symbol in state:
# don't operate on constants or symbols without rules.
# TODO: should this fail if not a constant and no matching rule?
if self.alphabet.is_constant(symbol) or \
symbol not in self._rule_lookup:
# nothing to do, just append the symbol
new_state.append(symbol)
else:
# easy operation, just replace the current symbol with the
# rule's predecessor in the new state
rule = self._rule_lookup[symbol]
new_state.append(rule.successor)
# the new state after this iteration
state = "".join(new_state)
# TODO: use logging instead. Too lazy to do now.
print "n={i} : {s}".format(i=i+1, s=state)
return state
@property
def alphabet(self):
"""(Alphabet) the alphabet object for this grammar"""
return self._alphabet
@property
def axiom(self):
"""(Axiom) the axiom object for this grammar"""
return self._axiom
@property
def rules(self):
"""(list) the list of rule objects for this grammar"""
return self._rules
class Alphabet(object):
"""
A set of symbols containing both elements that can be replaced (variables)
and those which cannot be replaced ("constants").
"""
def __init__(self, variables, constants=""):
"""
Initialize the Alphabet.
Also ensures the variables and constants don't have duplicate symbols.
:param str variables: A `str` containing variables
:param str constants: A `str` containing constants
:return:
"""
# eliminate duplicates
self._variables = "".join(set(list(variables)))
self._constants = "".join(set(list(constants)))
def validate(self, symbols):
"""
Validate the supplied symbols against this alphabet.
:param str symbols: A `str` containing symbols
:return: True if all symbols are either a variable or constant in this
alphabet.
:rtype: bool
:raises: `ValueError` if the symbols don't validate
"""
for symbol in symbols:
if not self.contains(symbol):
# oops, neither a constant or variable
raise ValueError(
"Invalid symbol '{s}' not found in alphabet '{a}'.".format(
s=symbol, a=alphabet)
)
def contains(self, symbol):
"""
Checks to see if a supplied symbol is either a variable or constant
in this alphabet.
:param str symbol: A single character symbol
:return: True if the symbol is a variable or constant, False otherwise
:rtype: bool
"""
return self.is_variable(symbol) or self.is_constant(symbol)
def is_variable(self, symbol):
"""
Checks to see if a supplied symbol is a variable in this alphabet.
:param str symbol: A single character symbol
:return: True if the symbol is a variable, False otherwise
:rtype: bool
"""
return symbol in self.variables
def is_constant(self, symbol):
"""
Checks to see if a supplied symbol is a constant in this alphabet.
:param str symbol: A single character symbol
:return: True if the symbol is a constant, False otherwise
:rtype: bool
"""
return symbol in self.constants
@property
def variables(self):
"""(str) The variables for this alphabet"""
return self._variables
@property
def constants(self):
"""(str) The constants for this alphabet"""
return self._constants
class Axiom(object):
"""
A string of symbols from an Alphabet defining the initial state of the
system.
"""
def __init__(self, symbols):
"""
Initialize the axiom.
:param str symbols: A `str` representing a starting state
"""
self._symbols = symbols
@property
def symbols(self):
"""(str) The symbols for this axiom."""
return self._symbols
class Rule(object):
"""
A production rule defining the way variables can be replaced with
combinations of constants and other variables.
"""
def __init__(self, predecessor, successor):
"""
Initialize the Rule.
:param str predecessor: A str representing the match criteria for this
rule
:param str successor: A str representing the rule's replacement symbols
"""
self._predecessor = predecessor
self._successor = successor
@property
def predecessor(self):
"""(str) The match criteria for this rule."""
return self._predecessor
@property
def successor(self):
"""(str) The replacement symbols for this rule."""
return self._successor
if __name__ == "__main__":
# ---------------------
# Run the examples...
# ---------------------
# Example 1: Algae
alphabet = Alphabet("AB")
axiom = Axiom("A")
rules = [
Rule("A", "AB"),
Rule("B", "A")
]
print "\nAlgae"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(7)
# ---------------------
# Example 2: Pythagoras tree
alphabet = Alphabet("01", "[]")
axiom = Axiom("0")
rules = [
Rule("1", "11"),
Rule("0", "1[0]0")
]
print "\nPythagoras tree"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# ---------------------
# Example 3: Cantor dust
alphabet = Alphabet("AB")
axiom = Axiom("A")
rules = [
Rule("A", "ABA"),
Rule("B", "BBB")
]
print "\nCantor dust"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# ---------------------
# Example 4: Koch curve
alphabet = Alphabet("F", "+-")
axiom = Axiom("F")
rules = [
Rule("F", "F+F-F-F+F"),
]
print "\nKoch curve"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# ---------------------
# Example 5: Sierpinski triangle
alphabet = Alphabet("AB", "+-")
axiom = Axiom("A")
rules = [
Rule("A", "+B-A-B+"),
Rule("B", "-A+B+A-"),
]
print "\nSierpinski triangle"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# Sierpinski triangle (alt)
alphabet = Alphabet("FG", "+-")
axiom = Axiom("F-G-G")
rules = [
Rule("F", "F-G+F+G-F"),
Rule("G", "GG"),
]
print "\nSierpinski triangle (alt)"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# ---------------------
# Example 6: Dragon curve
alphabet = Alphabet("XY", "F+-")
axiom = Axiom("FX")
rules = [
Rule("X", "X+YF+"),
Rule("Y", "-FX-Y"),
]
print "\nDragon curve"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# ---------------------
# Example 7: Fractal plant
alphabet = Alphabet("XF", "+-[]")
axiom = Axiom("X")
rules = [
Rule("X", "F-[[X]+X]+F[+FX]-X"),
Rule("F", "FF"),
]
print "\nFractal plant"
grammar = ContextFreeGrammar(alphabet, axiom, rules)
grammar.generate(3)
# TODO
# * stochastic grammar
# * context sensitive grammar