pythoniterationiterated-function

barnsley fern implementation in python script


I am writing a script to reproduce Barnsley's fern in Python, however I get something quiet different: enter image description here

Here is my code:

def iterate_vec(f, x0, a, steps=100):
    """x0: initial vector
        a: parameter to f(x,a)"""
    n = len(x0)  # state dimension
    x = np.zeros((steps+1, n))
    x[0] = x0
    for k in range(steps):
        x[k+1] = f(x[k], a)
    return(x)
def barnsley(x, A):
    """Barnley's fern: 
        x: initial point in 2D
        a: matrices [A_0,...,A_m-1]"""
    m = A.shape  # should be (4, 2, 2), last column for bias
    fs = [0,1,2,3]
    i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07])  # choose one, in this case m[0] = 4, hence a randint btw 0 and 4
    y = A[i] @ np.append(x[0],1) #in this case either first or second matrices are multiplied by vector x
    return(y)
x = iterate_vec(barnsley, [0,0], A, 10000)
print(x.shape)
plt.plot(x[:,0], x[:,1], '.', markersize=0.5)

And this is my matrix A:

A = np.array([
    [[0, 0], 
     [0, 0.16]],  
    [[0.85, 0.04], 
     [-0.04, 0.85]],
    [[0.2, -0.26], 
     [0.23, 0.22]],
    [[-0.15, 0.28], 
     [0.26, 0.24]],
])

Solution

  • That looks like an interesting problem. Comparing your code with the description on Wikipedia it seems that you are missing the constants in the transformation. I have added those below.

    def barnsley(x, A):
    """Barnley's fern:
        x: initial point in 2D
        a: matrices [A_0,...,A_m-1]"""
        m = A.shape  # should be (4, 2, 2), last column for bias
        fs = [0,1,2,3]
        i = f = np.random.choice(fs, p=[0.01, 0.85, 0.07, 0.07])
        y = A[i] @ np.append(x[0], x[1])
        if i == 1 or i == 2:
            y[1] += 1.6
        elif i == 3:
            y[1] += 0.44
        return(y)