Hopalong or Martin Fractals Part 2

June 20, 2018 - Maths, Fractals, Emergence

As promised I’ve managed to do a bit more work on the Martin or “hopalong” fractal I mentioned in my previous post on the subject. In order to scratch my itch to get terms with the excellent Haskell Gloss package I thouhgt I’d code up the hopalong relation in Haskell and use gloss to render the output. Without further ado and with no claim to efficient or idiomatic code I include the source and a screen shot of the output for your edification and delight.

Today is my daughter Laura’s birthday so I am dedicating this code and the image below to her. Happy birthday Laura!

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE PatternGuards #-}

module Main where

import Graphics.Gloss
import Graphics.Gloss.Data.ViewPort

-- State of the world a list of iteration and computed point so far
newtype State = State [(Int, Point)] 

-- Step the world on one iteration 
-- this function required by simulate driver
stepWorld :: ViewPort -> Float -> State -> State
stepWorld _ _ (State ps)
 | (n, p) : px <- ps = State ((n+1, hopalongBCD p) : ps)

-- How to render a point generated at a given iteration
renderPoint :: (Int, Point) -> Picture
renderPoint (!n, (!x,!y))
 = Color
   (makeColorI (rem (n+32) 255) (rem (n+64) 255) (rem (n+128) 255) 255)
   (Translate (x * 1000) (y * 1000) $ circleSolid 1) 
{-# INLINE renderPoint #-}

-- A test map
diagonal :: Point -> Point
diagonal (!x,!y) = (x+1, y+1)

-- A parameter
a :: Float
a = 0.07 * pi

-- A hopalong map
hopalongA :: Point -> Point
hopalongA (!x,!y) = ((y - sin x), (a - x))

-- Some more parameters 
b, c, d :: Float
b = 0.4
c = 1.2
d = 0

-- Another hopalong map
hopalongBCD :: Point -> Point
hopalongBCD (!x,!y) = (y - (signum x * sqrt (abs (c * x - d))), b - x)
{-# INLINE hopalongBCD #-}

-- Render all points computed so far
renderState :: State -> Picture
renderState (State ps) = Pictures [renderPoint p | p <- ps] 

-- Start the simulation with an initial state.
main :: IO ()
main = simulate
 (InWindow "Hopalong B,C,D" (800, 600) (100, 100))
 white
 5000
 (State [(0, (0, 0))])
 renderState
 stepWorld 

It is perhaps worth noting that using a simulation for this simple plotting exercise is probably overkill but I wanted to learn how to do this as Gloss offers a great way of thinking about visualization as if it were an animation, a game (if we want to interact with it) or a simulation of some process.

I leave all comment on the fractal itself for another post focussing on the mathematical properties of such maps and some references to my renewed study of fractal geometry in general.

Meanwhile here is an image that was generated by the above program as provided.

Martin “hopalong” fractal (hopalongBCD 0.4 1.2 0)