-
Notifications
You must be signed in to change notification settings - Fork 0
/
lsystem.go
253 lines (217 loc) · 5.65 KB
/
lsystem.go
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
package lsystem
import (
"fmt"
"strconv"
"strings"
"sync"
)
type LSystem struct {
Axiom Token
Rules map[Token]ProductionRule
Variables TokenSet
Constants TokenSet
useWeightPreSampling bool
EmptyTokenId TokenStateId
TokenBytes map[Token]TokenStateId
BytesToken [255]Token
ByteRules [255]ByteProductionRule
ParamToByte [255]TokenStateId
Params [128]uint8
MemPool *MemPool
}
func NewLSystem(axiom Token, rulesMap map[Token]ProductionRule, vars TokenSet, consts TokenSet, useWeightPreSampling bool) *LSystem {
lSystem := &LSystem{
Axiom: axiom,
Rules: rulesMap,
Variables: vars,
Constants: consts,
MemPool: NewMemPool(32),
useWeightPreSampling: useWeightPreSampling,
}
lSystem.encodeTokens()
lSystem.Reset()
return lSystem
}
func (l *LSystem) Recreate(byteRules [255]ByteProductionRule) *LSystem {
clone := *l
clone.ByteRules = byteRules
return &clone
}
func (l *LSystem) RecreateWithMemPool(byteRules [255]ByteProductionRule, pool *MemPool) *LSystem {
clone := *l
clone.ByteRules = byteRules
clone.MemPool = pool
return &clone
}
func (l *LSystem) encodeTokens() {
l.TokenBytes = make(map[Token]TokenStateId)
l.BytesToken = [255]Token{}
i := uint8(0)
statefulVarParams := make(map[Token]uint8)
for t := range l.Variables {
baseVar, numberState, isStateful := tryParseStatefulVariable(t)
if isStateful {
baseVar := Token(baseVar)
if _, exists := statefulVarParams[baseVar]; !exists {
statefulVarParams[baseVar] = numberState
}
statefulVarParams[baseVar] = max(numberState, statefulVarParams[baseVar])
}
bytePair := NewTokenStateId(i, false)
l.TokenBytes[t] = bytePair
l.BytesToken[bytePair] = t
i++
}
for t := range l.Constants {
bytePair := NewTokenStateId(i, false)
l.TokenBytes[t] = bytePair
l.BytesToken[bytePair] = t
i++
}
l.EmptyTokenId = l.TokenBytes[""]
j := 0
for baseVar, maxState := range statefulVarParams {
minIndex := 1
maxIndex := int(maxState)
baseTokenId := l.TokenBytes[Token(baseVar)]
for k := minIndex; k <= maxIndex; k++ {
bytePair := NewTokenStateId(uint8(j), true)
l.TokenBytes[Token(string(baseVar)+strconv.Itoa(k))] = bytePair
l.BytesToken[bytePair] = Token(string(baseVar) + strconv.Itoa(k))
l.ParamToByte[bytePair] = baseTokenId
l.Params[j] = uint8(k)
j++
}
}
l.ByteRules = [255]ByteProductionRule{}
for t, rule := range l.Rules {
l.ByteRules[l.TokenBytes[t]] = rule.EncodeTokens(l.TokenBytes, l.useWeightPreSampling)
}
}
func (l *LSystem) EncodeTokens(tokens []Token) []TokenStateId {
result := make([]TokenStateId, 0, len(tokens))
for _, t := range tokens {
result = append(result, l.TokenBytes[t])
}
return result
}
func (l *LSystem) DecodeBytes(bp []TokenStateId) []Token {
result := make([]Token, 0, len(bp))
for _, bytePair := range bp {
//v, exists := l.BytesToken[bytePair]
v := l.BytesToken[bytePair]
exists := v != ""
if !exists {
base := bytePair.TokenId()
v = l.BytesToken[NewTokenStateId(base, false)]
}
result = append(result, v)
}
return result
}
func (l *LSystem) IsVariable(t Token) bool {
return l.Variables.Contains(t)
}
func (l *LSystem) IsConstant(t Token) bool {
return l.Constants.Contains(t)
}
func (l *LSystem) applyRules(n int) {
var wg sync.WaitGroup
for i := 0; i < threadCount; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := 0; j < n; j++ {
l.applyRulesOnce(l.MemPool.GetReadBuffer(i), l.MemPool.GetWriteBuffer(i))
l.MemPool.Swap(i)
}
}(i)
}
wg.Wait()
}
func (l *LSystem) applyRulesOnce(input, output *Buffer) {
for tokenIdx, token := range input.BytePairs[:input.Len] {
if token.HasParam() && l.Params[token.TokenId()] > 1 {
token--
}
rules := l.ByteRules[token]
if rules.Weights == nil {
output.Append(token)
continue
}
predecessor := l.EmptyTokenId
if tokenIdx > 0 {
predecessor = input.BytePairs[tokenIdx-1]
}
output.AppendSlice(rules.ChooseSuccessor(l, predecessor))
l.ByteRules[token] = rules
}
}
func (l *LSystem) IterateUntil(n int) []TokenStateId {
l.Reset()
if n >= 15 {
n -= 10
l.prime(10)
l.applyRules(n)
} else {
for i := 0; i < n; i++ {
l.applyRulesOnce(l.MemPool.GetReadBuffer(0), l.MemPool.GetWriteBuffer(0))
l.MemPool.Swap(0)
}
}
return l.MemPool.ReadAll()
}
func (l *LSystem) prime(n int) {
for i := 0; i < n; i++ {
l.applyRulesOnce(l.MemPool.GetReadBuffer(0), l.MemPool.GetWriteBuffer(0))
l.MemPool.Swap(0)
}
l.distribute()
}
func (l *LSystem) distribute() {
chunkSize := l.MemPool.GetReadBuffer(0).Len / threadCount
for i := 0; i < threadCount; i++ {
// TODO: account for catalysts
from := i * chunkSize
to := from + chunkSize
if i == threadCount-1 {
to = l.MemPool.GetReadBuffer(0).Len
}
l.MemPool.GetWriteBuffer(i).AppendSlice(l.MemPool.GetReadBuffer(0).BytePairs[from:to])
}
for i := 0; i < threadCount; i++ {
l.MemPool.Swap(i)
}
}
func (l *LSystem) Iterate(n int) []TokenStateId {
l.applyRules(n)
return l.MemPool.ReadAll()
}
func (l *LSystem) IterateOnce() []TokenStateId {
l.applyRulesOnce(l.MemPool.GetReadBuffer(0), l.MemPool.GetWriteBuffer(0))
l.MemPool.Swap(0)
buffer := l.MemPool.GetReadBuffer(0)
return buffer.BytePairs[:buffer.Len]
}
func (l *LSystem) String() string {
var sb strings.Builder
for tokenId, rule := range l.ByteRules {
if rule.Weights == nil {
continue
}
sb.WriteString("\"" + string(l.BytesToken[tokenId]) + "\": ")
sb.WriteString(rule.String(l.BytesToken))
sb.WriteString(",\n")
}
return sb.String()
}
func (l *LSystem) Reset() {
l.MemPool.Reset()
l.MemPool.GetReadBuffer(0).Append(l.TokenBytes[l.Axiom])
l.MemPool.GetReadBuffer(0).Len = 1
}
type ProductionRate struct {
Token Token
Rates []float32
Rule fmt.Stringer
}