The Music of the Spheres

He himself could hear the harmony of the Universe, and understood the music of the spheres, and the stars which move in concert with them, and which we cannot hear because of the limitations of our weak nature (Porphyry, Life of Pythagoras)

I love legends. The life of Pythagoras is riddled with them: from the discoverie of consonant intervals in music while walking past a forge to how give death to his disciple Hippasus throwing him overboard a ship after this one proved the existence of irrational numbers. My favorite is the one that heads this post: it is said that Pythagoras could hear the sound of the spheres, the harmony of the universe. No more no less.

Nowadays is accepted that Pythagoras could not deduce the mathematical rules of consonant intervals just weighting hammers. Not even is known if Hippasus (who paradoxically demonstrated the existence of irrationals thanks to the theorem of Pythagoras) was killed. Furthermore, it’s possible that Pythagoras suffered from tinnitus: a common dolence that provoques the perception of sound when no corresponding external sound is present. That, together with some dose of marketing, could explain why he listened to the evolution of the stars.

This post is a tribute to the things and people that inspire us. There are two great sources of inspiration in it:

  • On the one hand, the work of Mark Lombardi, an american artist known for his abstract diagrammatic hand drawings, using curvy arcs and edges to capture global frauds perpetrated by politicians during 1980. The Modern Art Museum in NYC collected many of his works. Lombardi called his diagrams Narrative Structures, where this type of graph was often used to display social network analysis. I have been introduced to Lombardi’s work through a recent scientific collaboration with Alon Friedman, Professor at the School of Information in the University of South Florida.
  • On the other hand is Nina Simone, that accompanies me very often while I run, while I cook or while I work. She is a fundamental part of the soundtrack of my life. The sun around which the planets revolve is the one that appears on the cover of his album Here Comes the Sun:

If you take a look to the code you will find that all begins with a initial circular orbit where I place some of the planets (you can choose how many planets draw in total with the parameter nu_nodes). After that, I pick random planet from which will start a new orbit where I will place some other planets and so on (here is when I imitate some of the Lombardi’s arrangements for his structures). I expand each new orbit away from the sun, so that space gets a bit darker the farther we get from it. Apart from the parameter nu_nodes, you can also play with max_ratio (how big is the sun) and nu_branches (number of orbits) but you will find other places to tweak if you dive into de code. Here you have some other examples of what you can get:

Each one chooses which legends to believe and which not. I do believe that Pythagoras could listen to the music of the spheres: we must not forget that he already gave proof of having a superhuman ability discovering the most famous theorem in history.

The Mondrianomies

The Moonies are up on their mountain, the lunatics have taken over the asylum, waiting on the rapture (The Daily Mail, Radiohead)

I have not write any post lately, maybe because I have been quite busy with other unexpected project or maybe because I am going through a deep creative crisis. Whatever the reason, I have decided to resume my activity with Fronkonstin. Paraphrasing Picasso, inspiration will find me working when it comes.

Mondrianomies are the evolution of this previous project. To adapt outputs to neoplasticism assumptions I only use right angles and primary colors. This is why they remind the work of the founder of neoplasticism: Piet Mondrian. This is an example:

Mondrianomies are based on L-systems, a formalism invented in 1968 by the biologist Aristid Lindenmayer that yields a mathematical description of plant growth. Concretely, Mondrianomies have the following characeristics:

  • Use these five actions: F (draw a segment), + (turn right), - (turn left), [ (save the current position and angle for later use onto a stack of saved states) and ] (remove the last saved state from the stack and use it to restore the last saved position and angle).
  • Start with the axiom F-F-F-F (i.e. draw a segment, turn left, draw a segment, turn left, draw a segment, turn left and draw a segment).
  • Only have a rule, randomly generated from the actions. The rule is applied a number of times (3 or 4) to substitute the action F (starting from the axiom) and therefore expanding the list of actions to generate the drawing.
  • Turning angle is 90 degrees.
  • Longitude of segments depends on how many segments have been drawn previously.

Here you have four more outputs of this system. Do not hesitate to modify its parameters to obtain quite diverse images like these:

The code is available at github. There are many parts to play with: the axiom, the angle, the colors … you can even invent new actions to sofisticate the output. Create your own artworks and enjoy the journey.

Neighborhoods: Experimenting with Cyclic Cellular Automata

On candy stripe legs the Spiderman comes, softly through the shadow of the evening sun (Lullaby, The Cure)

Cellular automata are an inmense source of artistical images. Today, I experimented with Cyclic automata, which are ruled with these simple rules:

  • Create a grid of cells.
  • Give a state to each cell randomly; states a numbers between 0 and M-1 (you choose the value of M previously).
  • For each cell, count how many of its neighbouring cells have their state value exactly 1 unit greater than the cell’s state.
  • If the resulting number is greater than a certain thresold (that you also choose previously) increment the state of the cell by 1; if cell state reaches value of M, then you have to put 0 (in other words, you have to add 1 modulus M).
  • Repeat two previous steps a number of times.

A key concept in this algorithm is defining which is the neighborhood of a cell. There are two of them quite famous: Moore and Von Neumann neighborhoods, but you can define your own ones. Once you decide to stop iterating, you can give color to each cell according its final state, and you will obtain images like this one:

If you have a look to the code, you will see the next parameters:

  • neighborhood: the pattern of neighbouring cells
  • range: the depth of neighborhood
  • states: maximum number of states allowed (the M of the algorithm)
  • thresold
  • iter: number of iterations
  • width and height of the grid

Apart from Moore and Von Neumann, I implemented some other neighborhoods. This chart shows some of them. In columns you can find the folowing: M (Moore), N (Von Neumann), Mr (Moore remote), Nr (Von Neumann remote), Cr (Cross), S1 (S-Shape #1), Bl (Blade), C2 (Corners #2) and TM (Tick Mark). In rows, you can find different ranges for each neighborhood, from 1 to 4:

You will find more neighborhood in the code of the experiment, which is here. There are infinite combinations of the previous parameters, and each one results in a different image:

I used again COLOULovers palettes As always, I encourage you to experiment with the code, create your own neighborhoods, and see how they work. Happy New Year 2021!


Spinning on that dizzy edge (Just Like Heaven, The Cure)

This post talks about a generative system called Physarum model, which simulates the evolution of a colony of extremely simple organisms that, under certain environmental conditions, result into complex behaviors. Apart from the scientific interest of the topic, this model produce impressive images like this one, that I call The Death of a Red Dwarf:

You can find a clear explanation of how a physarum model works in this post, by Sage Jenson. A much deeper explanation can be found in this paper by Jeff Jones, from the University of the West of England. Briefly, a physarum model evolves a set of particles (agents), making them move over a surface. Agents turn towards locations with higher concentrations of a pheromone trail. Once they move, they make a deposition of pheromone as well. These are the steps of a single iteration of the model:

  • Sensor stage: Each agent looks to three positions of the trail map (left, front and right) according a certain sensor angle
  • Motor stage: then it moves to the place with the higher concentration with some rules to deal with ties
  • Deposition stage: once in the new location, the agent deposites a certain amount of pheromone.
  • Diffuse stage: the pheromones diffusing over the surface to blur the trail array.
  • Decay stage: this make to decay the concentration of pheromone on the surface.

Sage Jenson explains the process with this illustrative diagram:

My implementation is a bit different from Jones’ one. The main difference is that I do not apply the diffuse stage after deposition: I prefer a high defined picture instead blurriyng it. I also play with the initial arrangement of agents (location and heading angle) as well with the initial configuration of environment. For example, In The Death of a Red Dwarf, agents start from a circle and the environment is initialized in a dense disc. You can find the details in the code. There you will see that the system is governed by the following parameters:

  • Front and left sensor angles from forward position
  • Agent rotation angle
  • Sensor offset distance
  • Step size (how far agent moves per step)
  • Chemoattractant deposition per step
  • Trail-map chemoattractant diffusion decay factor

In adition to them (specific of the physarum model), you also can change others like colors, noise of angles (parameter amount of jitter function), number of agents and iterations as well as the initial arrangement of the environment and the location of agents. I invite you to do it. You will discover many abstractions: butterfly wings, planets, nets, explosions, supernovas … I have spent may hours playing with it. Some examples:

You can find the code here. Please, let me know if you do something interesting with it. Share your artworks with me in Twitter or drop me an email (you can find my address here).


Moça do corpo dourado
Do Sol de Ipanema
O seu balançado
É mais que um poema
(Garota de Ipanema, João Gilberto)

Sometimes I think about the reasons why I spend so many time doing experiments and writing my discoveries in a blog. Even although the main reason to start this blog was some kind of vanity, today I have pretty clear why I still keep writing it: to keep my mind tuned. I really enjoy looking for ideas, learning new algorithms, figuring out the way to translate them into code and trying to discover new territories going a step further. I cannot imagine my life without coding. Many good times in the last years have been in front of my laptop listening music and drinking a beer. In these strange times, confined at house, coding has became in something more important. It keeps me ahead from the sad news and moves my mind to places where everything is quiet, friendly and perfect. Blogging is my therapy, my mindfulness.

This post is inspired in this post from Softology, an amazing blog I recommend you to read. In it, you can find a description of the stepping stone cellular automaton as well as a appealing collection of images generated using this technique. I modified the original algorithm described in the post to create images like these, which remind me a watercolor painting:

I begin with a 400 x 400 null matrix. After that, I choose a number of random pixels that will act as centers of circles. Around them I substitute the initial zeros by numbers drawned from a normal distribution which mean depends on the distance of pixels to the center. The next step is to apply the stepping stone algorithm. For each pixel, I substitute its value by a weighted average of itself and the value of some of its neighbors, choosen randomly. I always mix values of the pixels. The original algorithm, as described in the Softology’s blog, performs these mixings randomly. Another difference is that I mix values intead interchanging them, as the original algorithm does. Once I repeat this process a number of times, I pick a nice palette from COLOURLovers and turn values of pixels into colors with ggplot:

The code is here. Let me know if you do something interesting with it. Turning numbers into bright colors: I cannot imagine a better way to spend some hours in these shadowy times.


Ooh, see the fire is sweepin’
Our very street today
Burns like a red coal carpet
Mad bull lost its way
(Gimme Shelter, The Rolling Stones)

After following this easy tutorial, you will be able to create tiled images from a photograph. You may want to use your own portrait or some other as I did. I use geom_tile: one of my preferred geometries of ggplot, which was the one I used in some other experiments like space invaders or Newton’s fractals. I used original photos from some of the most terrific monsters of the cinema: Frankenstein, Dracula and The Mummy. I love how rough squares create textures and sense of depth. This is Frankenstein after the transformation:

The process is quite simple:

  • Load the image and convert it to grayscale. I use imager, a very useful and easy to use package for image processing with R.
  • Reduce the resolution of the image as well as its dimension. Each new (big) pixel is summarized with the mean of the grayscale values of the pixels inside it.
  • Divide these average values into a number of groups using cut function.
  • Represent pixels with ggplot, using geom_tile. There are two important parameters: size and color of lines of each tile. Both of them depend on the value of the group previously calculated in which falls the tile. The graph is composed layer by layer depending on these gropus.

This is Dracula after being tiled:

And this is The Mummy:

These are the stunning original images (I love them all):

You can find the code here: let me know if you do something with it.

Reaction Diffusion

Sin patria ni banderas, ahora vivo a mi manera; y es que me siento extranjero fuera de tus agujeros (Tercer movimiento: Lo de dentro, Extremoduro)

The technique I experimented with in this post is an endless source to obtain amazing images. It is called reaction-diffusion and simulates the evolution of a system where several substances interact chemically transforming into each other (reaction) and spreading out over a surface in space (diffusion). In my case there are just two substances in a 2D space and the evolution of system is simulated using the Gray-Scott algorithm which is ruled by several parameters that, once determined, can produce images like this one:

This article by Karl Sims, is a very clear and comprehensive explanation of the Gray-Scott algorithm. Briefly, the Gray-Scott model simulates the evolution of two substances, A and B in a two dimensional grid. In each cell of the grid, the substance A is added at a given feed rate f. Then, both substances react following this rule: two particles of B convert a particle of A into a particle of B. To prevent overpopulation, B particles are killed at a given kill rate k. In the diffusion phase, both substances spread out accross the cells of the grid at a given diffusion rates Da and Db. The diffusion is performed using a 2D Lapacian operator with a 3x3 convolution matrix L.

In the article you can find the equations that rule the system, which depend on the parameters described in the previous paragraph. To obtain all the images of this post, I maintained most of them always constant and just changed the following:

  • Feed and kill rates (f and k respectively)
  • The initial proportion of both substances A and B. I always started with A=0 in each cell and B=1 in some (small) amount of them selected randomly or according to some geometrical considerations (and inner circle or square, for example). I let you to try with your own ideas.

Sometimes the system converges and remains stable after a number of iterations. For example, these images are obtained iterating 5000 times:

Before converging you can obtain also nice patterns in between:

The variety of patterns is amazing: tessellations, lattices, caleidoscopic … some more examples:

I used again Rcpp to iterate efficiently but now I tried RcppArmadillo, a C++ library for linear algebra and scientific computing because it contains a class called cube, which is a 3D matrix that fits perfectly into a 2D grid where the 3rd dimension is the amount of particles A and B.

I like to share my code because I think it may serve as a source of inspiration to someone. You can find the code here with just one of the many configurations I tried to generate the previous images. It may serve you as a good starting point to explore you own ones. Let me know if you reach interesting places.

Happy New Year 2020.

The Chaos Game: an experiment about fractals, recursivity and creative coding

Mathematics, rightly viewed, possesses not only truth, but supreme beauty (Bertrand Russell)

You have a pentagon defined by its five vertex. Now, follow these steps:

  • Step 0: take a point inside the pentagon (it can be its center if you want to do it easy). Keep this point in a safe place.
  • Step 1: choose a vertex randomly and take the midpoint between both of them (the vertex and the original point). Keep also this new point. Repeat Step 1 one more time.
  • Step 2: compare the last two vertex that you have chosen. If they are the same, choose another with this condition: if it’s not a neighbor of the last vertex you chose, keep it. If it is a neighbor, choose another vertex randomly until you choose a not-neighbor one. Then, take the midpoint between the last point you obtained and this new vertex. Keep also this new point.
  • Step 3: Repeat Step 2 a number of times and after that, do a plot with the set of points that you obtained.

If you repeat these steps 10 milion times, you will obtain this stunning image:

I love the incredible ability of maths to create beauty. More concretely, I love the fact of how repeating extremely simple operations can bring you to unexpected places. Would you expect that the image created with the initial naive algorithm would be that? I wouldn’t. Even knowing the result I cannot imagine how those simple steps can produce it.

The image generated by all the points repeat itself at different scales. This characteristic, called self-similarity, is property of fractals and make them extremely attractive. Step 2 is the key one to define the shape of the image. Apart of comparing two previous vertex as it’s defined in the algorithm above, I implemented two other versions:

  • one version where the currently chosen vertex cannot be the same as the previously chosen vertex.
  • another one where the currently chosen vertex cannot neighbor the previously chosen vertex if the three previously chosen vertices are the same (note that this implementation is the same as the original but comparing with three previous vertex instead two).

These images are the result of applying the three versions of the algorithm to a square, a pentagon, a hexagon and a heptagon (a row for each polygon and a column for each algorithm):

From a technical point of view I used Rcppto generate the set of points. Since each iteration depends on the previous one, the loop cannot easily vectorised and C++ is a perfect option to avoid the bottleneck if you use another technique to iterate. In this case, instead of writing the C++ directly inside the R file with cppFunction(), I used a stand-alone C++ file called chaos_funcs.cpp to write the C++ code that I load into R using sourceCpp().

Some days ago, I gave a tutorial at the coding club of the University Carlos III in Madrid where we worked with the integration of C++ and R to create beautiful images of strange attractors. The tutorial and the code we developed is here. You can also find the code of this experiment here. Enjoy!

Colonizing Franky

Y otra vez me arranco despacito, al sentir que nada necesito (Locura transitoria, Extremoduro)

One of my favorite sites in the Internet is algorithmic botany . It’s always a source of inspiration for me. I recently discovered there the space colonization algorithm, concretely in this paper. Originally, the algorithm was developed to simulate leaf venation patterns as well as the branching structure of trees and it works by simulating the competition for space between growing veins (or branches). Given a initial set of attractor points (3.000 points in my case), and a initial node (also a point located randomly inside the picture) the algorithm performs the next steps iteratively:

  • measure distances between attractors and nodes
  • assign the closest node to each attractor
  • keep just those pairs (node, attractor) which distance is between a minimum and maximum
  • normalize and obtain the unit average vectors for each node
  • create a new set of nodes using previous vectors and a predefined longitude

Once again, I used this image of Boris Karloff as Frankenstein’s monster to experiment with the algorithm. I have to say that I coded my own version of the algorithm which maybe is not the canonical one inspired by the previous paper as well as by this tutorial by the coding challenge. This is the resulting drawing using my preferred parametrization. As you will see in the code, I overimpose several layers of colonizations. I love the resulting images:

Play with the parameters to create your own images. If you improve my code, do not hesitate to do a pull request in Github if you want.

Clustering Frankenstein

Necesito para estar sentado, un arbolito en este descampado (Desarraigo, Extremoduro)

From time to time I come back to experiment with this stunning photograph of Boris Karloff as Frankenstein’s monster. I have done several of them previously: from decomposing it into Voronoi regions, to draw it as a single line portrait using an algorithm to solve the travelling salesman problem. I also used this last technique to do a pencil portrait of the image. Today I will use a machine learning algorithm to reinterpret the monster once again. Concretely, I will use hierarchical clustering to do drawings like this one:

The idea is simple: once loaded the photograph, the first step is to binarize it into a black and white image using thresold function of imager package. After that, a random sample of black points is taken. Here comes the clustering algorithm, which starts measuring the euclidean distance between each pair of points. Then, a hierarchical clustering is done so I can reproduce how points are gathered walking through the resulting dendrogram of the previous clustering, starting from the maximum number of clusters (each cluster is an individual point) and ending with the minimum one (just one cluster with the whole sample). The next image shows and example of this process for a sample of 25 points. The left plot shows the population of points and the right one the way that points are connected once the dendrogram is analyzed following the steps described before:

Applying this technique to a big amount of points (between 2.000 and 5.000) result in very interesting drawings. To make process faster, I used map function from purrr package. To render the graph I use ggplot function with geom_curve. This geometry draws a curve between two points, named (x, y) and (xend, yend) respectively. Among others, there are two important parameters to control its shape: curvature (negative values produce left-hand curves, positive values produce right-hand curves, and zero produces a straight line) and angle (values less than 90 skew the curve towards the start point and values greater than 90 skew the curve towards the end point). Playing with this paramaters, as well as with the sample size, you can generate a wide variety of drawings (note that here only appear the segments, since now I removed the points of their extremes):

You can find the code of this experiment here. If you do something interesting with it, please let me know. Thanks a lot for reading my post.