# Evolving musical bytecode #2

Following on from the first BetaBlocker genetic algorithm bytecode experiments, in addition to the “most different notes” fitness function I added a similar calculation for the first derivative (ie. the difference between the notes in time order). This was an attempt to steer the evolution away from simple scales and into more complex patterns.

```(defn deriv [l]
(cond
(empty? l) '()
(empty? (rest l)) '()
:else (cons (- (first (rest l)) (first l))
(deriv (rest l)))))
```

The code to find the first derivative of a sequence of notes – eg. (deriv ‘(1 2 3 2 6 7)) => (1 1 -1 4 1). We then add this to the fitness function which looks like this:

```(+ (count (num-unique res)) ; unique notes are good
(count (num-unique (deriv res))) ; unique gaps between notes are good
(min (count res) 20)) ; lots of notes are good (stop at 20)
```

This resulted in the following bytecode to emerge from the primordial soup: 23 17 7 6 23 21 9 23 8 212 3 2 4 2 180 124 – which disassembles to:

The arrows show the indirection which helps as this one is a bit tricky to pull apart. It’s the first time I’ve seen self modification emerge – it decrements the “212” and uses it as a variable for the note sequence. Combining the pshi and pdp like this is a nice trick I can make use of when programming betablocker myself.

The program is self destructive – the “pop” which otherwise does nothing of use will eventually write zeros over the program itself if it’s run for a few more cycles than the 100 I’m testing the programs for.

The output looks like this:

0 212 255 211 0 210 0 209 0 208 0 207 0 206 0 205 0 204 0 203 0 202 0 201 0 200 0 199 0 198 0 197 0 196

According to our fitness function, the interleaved zeros give it a very high scoring derivative list:

212 43 -44 -211 210 -210 209 -209 208 -208 207 -207 206 -206 205 -205 204 -204 203 -203 202 -202 201 -201 200 -200 199 -199 198 -198 197 -197 196

However the actual pattern is not so interesting, so still more work needed on the fitness criteria.