Asymptote’s Zombie Infection Simulator — Version 2.0

NOTE: I submitted the model to the NetLogo website, and it can now be found in applet form (and downloaded) here.

After discovering that my previous Zombie Infection Simulator post had gotten a mention on SquidTalk, and found that they were expecting a release in a few weeks, I thought I ought to try not to disappoint them. However, my previous simulator was, to put it nicely, rather rough around the edges, so I spent a lazy afternoon re-writing it. Without all the extra garbage cluttering up the code, it ran a little faster, and exhibited some new behaviors I hadn’t seen before. I also built in a simulator mode that includes the walls seen in the original version of the simulator, although that mode is somewhat broken.

Flocks of humans form as they did in the previous version. Nothing new, really.

The infection has started. I don’t know if it’s visible or not, but the zombies are displaying a great deal more organization, thanks to a greatly improved directional targeting method. Thank goodness for towardsxy.

The infection is spreading rapidly, and, as seen in the previous version, social order is beginning to degenerate. I know it’s not exactly obvious in this still picture, but note the dense little group of humans just above the large group in the center, to the upper left of the cluster of zombies. This group actually broke away in a coordinated fashion when some of its members panicked and fled. I’d expect to see runaway parties like this in a real zombie infection.

Social order begins to falter. Human flocks are beginning to be broken up by panic, and there aren’t enough fighters to rally them.

The little simulated society begins to break down. A few groups are still together, but they’re beginning to collapse as the onslaught continues. The zombies are much more organized in Version 2.0, which actually puts them at a great advantage over the humans. Not only do they form flocks, but they are much more effective hunters, so they tend to infiltrate human groups and pick them off and infect them before panic can disperse them.

As I said in the introductory paragraph, I added a secondary mode to the simulator complete with walls. Since there is still a bug in my simulator, and all the flocks tend to become oriented towards the South, the flocks tend to get “stuck” to the Southern walls of the buildings, where they become immobile. Also, panic is able to spread through the walls. So, I guess I’ll leave fixing these bugs for Version 3.0.

AZIS 2.0 (sounds like the name of a guided missile or something, doesn’t it?) can be found in applet form at here.

Evolving Behavior

Well, since my previous posts about my various NetLogo models have been so popular, I thought I’d write another one about one my most unusual — and in-depth — NetLogo models thus far: one to simulate the evolution of behavior.

This particular simulation sprang from a desire I’ve harbored for a long time to create “digital organisms,” as Wikipedia calls them: organisms whose behavior is controlled by internal programming instructions, which evolve over time in a simulated environment. Of course, it’s notoriously difficult to both manipulate text and run it as program instructions within a programming language (at least for me), unless you’re willing to code a mini-compiler within your program, but nonetheless, I thought I’d give it a try.

As it turns out, NetLogo already comes with a built-in method called run. When called with a string as its argument, run interprets the string as it would any other stream of NetLogo commands. Given that, and the elegant modular simplicity of the NetLogo language, it seemed that even a merely casual programmer such as myself might have some chance of building a digital-organism simulator.

Thank goodness for one of NetLogo’s other commands, namely, carefully. Carefully has two arguments: an instruction to run, and a procedure to run if that instruction causes an error. With that in mind, and NetLogo’s modularity, I threw together a simple list containing a handful of symbols (such as “=”, “if”, and “+”), as well as the names of a few methods I’d pre-coded myself (methods that tell the organisms to do things like “eat” and “reproduce”). I had to do the latter because, the only way I could get around the errors that carefully would otherwise cause, at least for the time being, was to make any error-producing organism die immediately. After some fiddling to make the program-mutation procedure work properly, and to fix some other stupid little errors, I finally managed to get it to run. Here is a sample image from the result:

Those little labels you see hovering over each organism are the organisms’ programs. As you can see, they’re neither very varied or very complex. I had hoped to evolve the organisms into greater complexity (note: all of the methods you see here are not built-in to NetLogo, but are references to methods I coded myself. I did this for the sake of simplifying things a bit, and for “chunking” the program, so that it was less likely that a mutation would break the code, since the NetLogo language isn’t terribly mutation-tolerant, I discovered).

Over time, unfit programs died out, and the more fit ones reproduced. After a fairly short run-time, I got this:

Notice how the organisms all have essentially the same code. This is an unintended side-effect of the fact that I spawned so few organisms at the beginning of the run, for the sake of visual clarity. Although, I have noticed that a lot of my randomly-instantiated populations tend to do the same thing, in all of my evolution simulations: most of them will prove unfit, so the world will end up being populated by a group of genetically-similar descendants of the few highly-fit originals.

I let the model run for a little while longer, knowing full well (from other runs) that it wouldn’t do what I was hoping. Apparently, I didn’t make the environment complex enough, or the selection process harsh enough, to necessitate the evolution of interesting programs. The fact that interesting variations almost always die out — since even a misplaced parenthesis or bracket will cause a syntax error, which, as I said above, automatically results in the organism’s death — sort of selected against novel programs. What I was really hoping to see were some strange loophole exploits or programming workarounds (for example, an organism that, say, re-set its own energy level so that it wouldn’t have to trouble with actually eating food) of the kind that I talked about in my previous post “Unexpected Consequences”. What, instead, I ended up with, was this:

(For the sake of readability, I’ve only printed the program of a randomly-selected ten organisms.)

As you can see, every organism has essentially the same program. Oh well, I guess that’s a problem to be tackled in Version 2.

Here are some of my goals for the next rendition:

  • Streamlining of the code: When there are more than about twenty-five organisms, the simulation slows waaay down. I don’t know if there’s a way to execute the organisms’ programs faster, but I’ m hoping that I can figure something out.
  • Make the programs less fragile: The main roadblock to interesting programming variants is the fact that any “broken” code dies immediately, rather than, perhaps, getting repaired. Figuring out how to do that is going to be complicated, but it seems that every time I think I’m not going to be able to do something in NetLogo, I still manage.
  • Make the environment more complex: as it is, the organisms are only competing for two things: energy, and, to a much lesser extent, space. I’d like to see if I can make the space-competition harsher, and perhaps introduce some new resources for them to compete over, such as mates (the current version uses asexual reproduction, since I didn’t want to bother with the nightmare of trying to prevent errors in sexually-combined programs).

More later, as events warrant.

Unexpected Consequences

One of the things that’s always fascinated me the most about simulated evolution is the way in which simulated organisms have a tendency to exploit any loophole or weakness in your code for an evolutionary advantage. Although I’ve designed and attempted to design a handful of evolutionary simulations, I’d never until today seen an example of this Darwinian cleverness.

A few days ago, I threw together a simple little evolution simulator in NetLogo. Each of the agents in the simulation had three genes: xcor (position along the x-axis), ycor (position along the y-axis), breednum (the number of daughter agents it spawns when it reproduces), and killpropensity (how likely the agent is to kill a random nearby agent). The simulation produced some interesting — although not terribly fascinating — behavior: those agents that produced the most offspring had a tendency to dominate. There was an interesting dynamic between the “killer” agents and the “peaceful” agents. The killers tended to form low-density groups (since if any of them were too close together, they’d usually kill each other), while the “pacifists” formed dense blooms. For a while, the killers would hold back the pacifists, but eventually, the pacifists would encroach and squeeze out the killers altogether. A typical run looked like this:

The agents inherit the color of their parents, so the coloration isn’t exactly by “species,” but it’s pretty close. As you can see, the green agents are fast-breeding pacifists, rapidly encroaching on the slower-breeding killers toward the center.

Then — and this is where the unexpected behavior and exploitation of loopholes I was talking about comes in — I introduced a new variable: mutationrate. It controls, obviously enough, how rapidly the agents mutate. Very quickly, every run started to look like this:

As you can see, this blue species has very rapidly come to dominate. You can’t see it, but this species has a rather high mutation rate. It took me a while to figure out why the fast-mutators were at such an enormous advantage. Then, I remembered that, in this simulation, the agents were competing for space, and in such a competition, the fittest organisms would be the ones that can maximize the space filled by their offspring. Since x-position and y-position were treated as genes, they were being mutated right along with the other variables, and since a rapidly-mutating position allowed the agents to jump farther from their parents and fill space more rapidly, fast mutation was an enormous advantage. It was such an enormous advantage that, even though the extremely large mutations the fast-mutators experienced prevented the evolution of any other behavior (because those genes tended to get so randomized that they effectively didn’t get passed on), they were still far more successful than any of the other species.

After I corrected for this ludicrous advantage (by setting it so that mutation rate couldn’t work on the position genes), this is what I got:

For a moment, I thought I’d solved the problem, until I inspected some of the agents and discovered that they had stopped mutating altogether. The sneaky intelligence of the genetic algorithm strikes again! I suppose that mutating would become something of a maladaptive behavior once the organism had optimized all of its other behaviors, since, after optimization was reached, any organism that mutated could only be at a disadvantage.

I realized that the only fix for this would be to force the mutation rate to stay above 2 (it’s a peculiarity of the random-number-generation code I cobbled together for this simulation that, at a mutation rate less than 2, no mutations occur). I thought that all I’d get would be the simulation I started with, but I was pleasantly surprised to discover that there was actually quite a diversity of mutation rates, and that none of these rates was at a particularly huge advantage over any of the others. This is what a run of the fixed simulator produced:

Those numbers you see hovering over every agent are the mutation rate. It appears that there’s not really an advantage to having a mutation rate above the usual 2, but it does seem that there’s not a disadvantage, either. So I can finally call this simulation fixed.

This experience reminded me that there’s a reason genetic algorithms are so popular in AI research, and that brings us to the moral of this little story: Darwinian evolution is a lot smarter than us. When writing evolutionary simulations, if there’s a loophole or a workaround or an exploit to be found in your code, then evolution will find it. Plan accordingly.

NOTE: Someone requested an image with the organisms color-coded by “kill propensity.” Since you asked nicely, and since I agree that that would be a good image to have up here, here you go. The organisms that are the darkest have the lowest probability of killing their neighbors, and the ones that are closer to white are very likely to kill:

As you can see, the situation is as I described in the body of the post: the killers have too great a tendency to limit their own growth, and are easily out-competed by their more peaceful counterparts.

SimHeart Update

The folks at the NetLogo website have been gracious enough to include SimHeart in their “community models” page, and the result is that there is now a place where you can run the program in your web browser (assuming you have a recent enough version of Java installed). Now, you don’t have to download or install anything in order to run it.

You can find the SimHeart applet here.

Once again, many, many thanks to the creators of NetLogo.

Zombie Infection Simulator

Yesterday evening, as I was wiling away some hours at the computer, a thought struck me. I realized that my knowledge of NetLogo has finally reached the point at which I could build something I’ve wanted to build for a long time: a simulation of a zombie outbreak. Ever since I saw the cool simulator on this page, I’ve wanted to build my own version in NetLogo, but I’ve never been competent enough to program it. Now that I’ve got some experience under my belt, I was finally able to pull it off.

Here are the basics:

  • Humans show up as blue dots. They walk at a leisurely pace, and flock together with other humans.
  • Panicked humans result whenever a human sees a zombie or another panicked human. Panicked humans run faster than normal ones, change directions more often, and don’t flock. If there’s nothing threatening about, and the general panic level has died down, they turn back into normal humans.
  • Zombies are green. They lack any sort of intelligence and wander around randomly. If a human gets too close to them, they may attack, resulting in infection.
  • Fighting humans are humanity’s only hope to resist the zombie hordes. They show up as yellow. Fighters flock together with other fighters, and also seek out any zombies nearby. They also have a rallying effect. That is, they have a tendency to make panicking humans calm and urge calm humans to fight. Sometimes, fighters break under the strain and panic, or, if there are no immediate threats, they go back to normal.

These rules are fairly simple, but I’ve been working with StarLogo and NetLogo for long enough now to know that emergence can perform feats of magic with simple rules. And I did indeed get some fascinating behavior.

As I toyed around with the simulator, I discovered the importance of scaling. With a small map and a large population, the behavior seemed to resemble that one might find in an urban setting, and as the map size increased, the behavior seemed to be more like that of a county or a small country, with the groups of humans representing cities, or something to that effect.

The first run I did for this post was an urban one with an initial human population of 300 (THIS IS SPARTAAA!!! Sorry…couldn’t help myself.)

The humans have organized into “flocks”. For some reason, there seems to be a bias that causes them to favor moving down the map, rather than in some other direction. I’m still trying to fix that particular bug.

Now the fun part begins. I cause one human to suddenly become a zombie, and the infection starts. All the people nearby start to panic, except for a small group of renegades who become fighters and start hunting down the zombies.

As the epidemic begins to grow out of control, panic spreads throughout the “city”. Groups of fighters attempt to rally the panicking citizenry, but their efforts are for naught, as the growing zombie horde continues to inspire panic.

Groups of fighters still try valiantly to keep the infection under control, but it’s already too far gone. By this point, social organization is beginning to decay.

As the situation continues to spiral out of control, social order breaks down, and humans stop forming flocks. Groups of fighters are overwhelmed on every front.

It is the end of days (well, at least the end of the “city”). There are few humans left, and those survivors are panicked and running for their lives. Note the single fighter still trying to kill zombies. Unfortunately, this is not an actual zombie movie, and so there’s pretty much no chance that a ruggedly good-looking male protagonist is going to rally a ragtag group of comic-relief-spouting survivors and save the day.

This program is incredibly fun to play with, and I’ll put it up for download as soon as I get around to it. In the meantime, I’ll do a larger run, one that represents more of a “nationwide” zombie epidemic. But since, for some reason, this simulation is pretty CPU-intensive, it’s going to take me a while to get around to running that one.

Many thanks to Kevan Davis for the inspiration for this simulation!

And, once again, many thanks to the makers of NetLogo. I know it sounds like I’m on their payroll or something, but NetLogo really does make programming multi-agent simulations pathetically simple.

SimHeart — Now Available for Download

All right, as promised, I’ve finally figured out a way that people can download SimHeart to play with it themselves. Many thanks to the folks at NetLogo for automating so much of the process, and thanks to MediaFire.com for the free file hosting.

The file is kind of large because, in order for it to work, I had to put a bunch of Java modules into the folder with it, but it shouldn’t take too long to download, even over a slow-ish Internet connection. When you’ve downloaded it, you’ll need to extract the file to your desktop. I recommend an unzipping program like WinZip or WinAce. The program should (major, major emphasis on should) work on Macs and PCs, but I make no guarantees.

To run the simulation, go into the folder into which you’ve extracted SimHeart, and double click on the HTML file there. It should open up in a new window, and you should see the simulation screen. If you don’t, either you don’t have an up-to-date version of Java, or something went wrong in the download process, or I made a mistake zipping the files. If you checked the previous two things, please leave a comment and describe the problem, and I’ll try to help, although I make no claims to be very good at this kind of thing.

Also, I must provide the obligatory legal disclaimer: I take no responsibility if this file somehow damages your system. To my knowledge, there is absolutely nothing in the file that should do so, but you never know, something might have gotten corrupted or damaged along the way. Also, this software is for entertainment purposes only, and should not be taken as any form of medical advice. I’m not sure why anybody would, but you never know.

Download SimHeart 2.0 here.

If you already have the latest version of NetLogo installed on your computer, you can download the much smaller .nlogo file here. If you’re interested in this kind of thing, you should go ahead and download NetLogo (you can do that here). Not only will it allow you to download a much smaller file, but NetLogo comes with a whole cornucopia of fascinating little simulations, and there are more you can download from the Internet.

If you have trouble with either of these files, please let me know by commenting on this post. If you don’t want to do that for some reason, send an e-mail to asymptote [døt] inverse [át] gmail [døt] com (Sorry about all the weird characters in there, but that account gets enough spam as it is, without ever having broadcast the address on the Internet, so I figured I’d better obfuscate as much as possible).

I’ll try to update the files as I revise SimHeart, but I seem to be at a point where there’s not much more I can do with it, at least not without rewriting most of the code. I’ll be sure to post updates as they come.

SimHeart 2.0

It seems that every time I sit down to work on my heart-simulation project, I get a lot more done than I was expecting. In my last post on the subject, I talked about how I wanted to integrate a more realistic model of the atrioventricular (AV) node, the little bundle of nerve fibers that carries the contraction impulse from the atria at the top of the heart to the ventricles on the bottom. Apparently, I’d entirely misjudged the difficulty of this effort, since, once the solution occurred to me, I was able to implement it in about five minutes.

Here’s what I did. As I said before, each cell in the simulation has two variables assigned to it: ARefrac, which determines whether or not an atrial impulse can pass through the cell; and VRefrac, which determines whether a ventricular impulse can pass through. I solved the AV-realism problem by simply introducing a global variable called AVRefrac that determines whether or not the AV node can accept an impulse. Basically, every time a simulated electrical “spark” strikes the simulated node, as long as AVRefrac is equal to or less than zero, it sets AVRefrac’s value to a user-specified constant I call AV-delay. So, basically, now the ventricles can only respond as fast as the AV node will allow, just like a real heart! When I saw how beautifully my little fix had worked, I was thrilled!

So, my simulated heart is now more realistic than ever. For example, I did a few runs with the refract-length value (the value that determines how quickly cells recover their ability to fire after each firing) set very short so that arrhythmias would occur frequently, so that I could study their effects. Before long, my simulated heart went into atrial flutter/fibrillation (a condition where the small pumping chambers at the top of the heart expand and contract quickly and chaotically, often leading to a dangerously fast ventricular rate. I was amazed to see something very similar to the many atrial-fibrillation EKG’s I’ve looked at:

(Note: in the simulated EKG, I’ve separated the atrial and ventricular signals, since whenever the ventricular rate got very fast, it obscured all the atrial activity, and I wanted to be able to study the atrial activity as well)

Given my tendency towards oversimplified simulations that produce peculiar behavior, the resemblance this bears to real supraventricular tachycardia (fast heart rate caused by the atria, which is often seen in atrial flutter or fibrillation) was frankly, surprising. After about half a second of atrial flutter, the atria begin to fibrillate, producing that classic irregular ventricular response.

Note the extremely high ventricular rate that shows up towards the end of the ECG. That’s a rather unrealistic product of my simulation, since whenever one of the waves of excitation collided with the back of a previous wave, it had a tendency to collapse into a tachycardic or fibrillatory spiral.

There are some forms of supraventricular tachycardia that terminate on their own. They’re called “paroxysmal” supraventricular tachycardia, and my simple little simulation actually managed to produce a run of it!

Some forms of atrial fibrillation occur in the presence of heat block (which, in its most common form, is basically a very slow AV node that doesn’t conduct every impulse that passes to it). In those cases, the fibrillation is frequently asymptomatic or minimally symptomatic, since the heart doesn’t end up racing. When I set the AV-delay parameter higher than usual, I observed this very same phenomenon.

Eventually, the aforementioned wave-collision problem had become annoying enough that I decided to re-write part of the simulation so that there was a small probability that an electrical spark could actually cross a cell that had not entirely recovered. That solved a lot of my problems.

In the re-written simulation, atrial fibrillation still produces that classic irregular ventricular heartbeat, and this time, since the waves are more collision-tolerant, the behavior doesn’t immediately degenerate into ventricular fibrillation, which gives me a chance to actually study it properly.

More updates as they’re warranted. And for those reader(s?) who are wondering what the hell has been wrong with me lately, don’t worry, I’ll be turning the blog over to my old cynical, sarcastic self very shortly.

UPDATE:

I was sitting around without much to do, so I opened up SimHeart and let it run in the background. When I checked in on it again a few minutes later, I’d discovered some very interesting behavior:

Apparently, some of the standard sort of atrial fibrillation had started, then, spontaneously self-organized into a coordinated wave spiraling cyclically through the atria. You can see the wave in the screenshot.

This really grabbed my attention, so I watched it for a while, and discovered that, strangely enough, the wave was quite stable.

Not even the normal sinus beats, which occasionally inserted themselves in the path of the wave, were very good at disrupting it. Not long after this screenshot, it degenerated rather suddenly into normal atrial fibrillation.

Then, while having a look at the pictures a few minutes later, I realized something: my simulation had produced true atrial flutter. What I saw before and called atrial flutter was really just organized fibrillation. This, though, exhibits all the classic features of atrial flutter: rapid atrial waves with a sawtooth shape. In this case, since I had the ventricular response set to be fairly quick, it turned into quite realistic atrial tachycardia.

I tried to save the state of the simulation so that I could study it later, but as there are some features of NetLogo with which I’m not entirely familiar, I wasn’t able to do it. So, for now, I guess I’ll just keep running HeartSim in the background until I see that rhythm again.