field and rule class

This commit is contained in:
Jonas Weinz 2017-05-16 22:49:28 +02:00
parent 6a03fa0cdc
commit 8382993eaf
2 changed files with 93 additions and 0 deletions

45
field.py Normal file
View File

@ -0,0 +1,45 @@
import numpy as np
import rule
class Field(object):
def __init__(self, shape = (32,32)):
self.resize(shape)
self.a_to_b = True
self.rule = rule.Rule(0)
def setRule(self, rule):
self.rule = rule
def resize(self, shape):
self.shape = shape
self.matrix_a = np.matrix(np.zeros(shape, int))
self.matrix_b = np.matrix(np.zeros(shape, int))
def update(self):
self.a_to_b = False if self.a_to_b else True
a = self.matrix_a if self.a_to_b else self.matrix_b
b = self.matrix_b if self.a_to_b else self.matrix_a
h, w = self.shape
for i in range(h):
for j in range(w):
b[i,j] = self.rule.applyRule(a, i, j)
def getField(self):
return self.matrix_b if self.a_to_b else self.matrix_a
def setValue(self, y, x, val):
self.matrix_a[y,x] = val
self.matrix_b[y,x] = val
# some testing
if __name__ == "__main__":
f = Field((160,90))
r = rule.Rule(2)
f.setRule(r)
f.setValue(2,2,1)
for i in range(10):
print(f.getField())
f.update()

48
rule.py Normal file
View File

@ -0,0 +1,48 @@
import numpy as np
class Rule(object):
def __init__(self, rule_id, r = 1, k = 2):
self.r = r
self.k = k
self.a = 2 * r + 1
self.a2 = self.a**2
self.rule_table = np.zeros(k**self.a2, int)
self.setRule(rule_id)
def setRule(self, rule_id):
if rule_id < 0:
self.rule_id = 0
elif rule_id >= self.k**self.a2:
self.rule_id = self.k**self.a2 - 1
else:
self.rule_id = rule_id
self.generateRuleTable()
def applyRule(self, matrix_field, pos_y, pos_x):
e = 0
sum = 0
h, w = matrix_field.shape
for i in range(pos_y - self.r, pos_y + self.r + 1):
for j in range(pos_x - self.r, pos_x + self.r + 1):
y = i if i < h else i - h
x = j if j < w else j - w
sum += matrix_field[y,x] * self.k**e
e += 1
return self.rule_table[sum]
def generateRuleTable(self):
id = self.rule_id
i = 0
while id > 0:
self.rule_table[i] = id % self.k
id = id // 2
i = i + 1
#print(self.rule_table)