Chapter 6: Simulating Chemical Reactions with Parallel Programming

Chemistry happens when molecules wander and collide. A molecule drifts through its surroundings (diffusion), and when it bumps into the right partner, the two react. Repeat this for millions of molecules, and remarkable patterns emerge: predators and prey chasing each other in waves, epidemics sweeping through a population, and spirals of rock, paper, and scissors that chase each other forever. Systems that combine these two ingredients are called reaction-diffusion systems, and building a reaction-diffusion simulator is the goal of this chapter.

There is a catch. Simulating thousands of particles that move and react at every time step is slow, and our computers stopped getting much faster at running a single task long ago. Instead, a modern laptop has many cores that can work at the same time. In this chapter, we will learn parallel programming, splitting one big task among many workers, and we will use it to make our reaction-diffusion simulator fast enough to watch these patterns unfold.

We start small, summing a list across several processes and timing the speedup, then revisit our craps simulator from Chapter 2 in parallel. Next, we build a diffusion simulator of particles taking random walks and parallelize it. Finally, we add chemical reactions, deal with the subtle problem of particles that react across the boundary between two workers, and take a tour of the reaction systems that our simulator can explore.

Core text (coming soon)

The core text for this chapter, which presents the key ideas of parallel programming and reaction-diffusion independently of any language, is coming soon. In the meantime, the Python code alongs below are complete, and each one contains the video in which we build the code together.

Python code alongs

Find all of the code alongs on the Chapter 6 Python Code Alongs page, or jump straight to a lesson:

  1. Parallelism vs. Concurrency
  2. Summing a List Across Processes in Python
  3. Any Number of Processes and Timing the Speedup in Python
  4. Parallel Craps in Python
  5. A Serial Diffusion Simulator in Python
  6. Parallel Diffusion with Pool and starmap in Python
  7. Reaction-Diffusion: Designing the Serial Engine in Python
  8. Reaction-Diffusion: Applying Reactions in Python
  9. Parallel Reaction-Diffusion: Strips and Halos in Python
  10. Parallel Reaction-Diffusion: Processing Strips in Python
  11. A Tour of Reaction Systems
Scroll to Top
Programming for Lovers banner no background
programming for lovers logo cropped

Join our community!