TwoGas Mixing

TwoGas Mixing preview image

1 collaborator

Default-person Tony Matthys (Author)


(This model has yet to be categorized with any tags)
Visible to everyone | Changeable by everyone
Model was written in NetLogo 6.0.4 • Viewed 1743 times • Downloaded 25 times • Run 0 times
Download the 'TwoGas Mixing' modelDownload this modelEmbed this model

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)


This model simulates the behavior of two different types of gas particles in a box with a partitioning wall. Part or all of the wall can be removed, allowing the particles to mix together. It was one of the original CM StarLogo applications (under the name GPCEE) and is now ported to NetLogo as part of the Connected Mathematics "Making Sense of Complex Phenomena" Modeling Project.

This model is one in a series of GasLab models. They use the same basic rules for simulating the behavior of gases. Each model integrates different features in order to highlight different aspects of gas behavior.

The basic principle of the models is that gas particles are assumed to have two elementary actions: they move and they collide --- either with other particles or with any other objects such as walls.

This model is part of the Connected Mathematics "Making Sense of Complex Phenomena" Modeling Project.


The particles are modeled as hard balls with no internal energy except that which is due to their motion. Collisions between particles are elastic. Particles are colored according to speed --- blue for slow, green for medium, and red for high speeds.

Coloring of the particles is with respect to one speed (10). Particles with a speed less than 5 are blue, ones that are more than 15 are red, while all in those in-between are green.

The exact way two particles collide is as follows:

  1. A particle moves in a straight line without changing its speed, unless it collides with another particle or bounces off the wall.
  2. Two particles "collide" if they find themselves on the same patch.
  3. A random axis is chosen, as if they are two balls that hit each other and this axis is the line connecting their centers.
  4. They exchange momentum and energy along that axis, according to the conservation of momentum and energy. This calculation is done in the center of mass system.
  5. Each particle is assigned its new velocity, energy, and heading.
  6. If a particle finds itself on or very close to a wall of the container, it "bounces" --- that is, reflects its direction and keeps its same speed.


Initial settings:

  • BOX-SIZE: the percent of the width and height of the world that the box will occupy.
  • NUM-MAGENTAS and NUM-CYAN: the number of gas particles of each color.
  • MAGENTA-INIT-SPEED and CYAN-INIT-SPEED: the initial speed the the respective particle.
  • MAGENTA-MASS and CYAN-MASS: the mass of the respective particles.

The SETUP button will set these initial conditions. The GO button will begin the simulation.

Controls: The OPEN button opens the wall between the chambers of the box. The CLOSE button closes the wall between the chambers of the box.

Other settings:

  • COLLIDE?: Turns collisions between particles on and off.
  • OPENING-SIZE: the size of the opening made as a percentage of the BOX-SIZE when the OPEN button is pressed.


  • MAGENTAS IN RIGHT CHAMBER: number of magenta particles in the right chamber.
  • CYANS IN LEFT CHAMBER: number of cyan particles in the left chamber
  • AVERAGE ENERGY MAGENTA or CYAN: average energy of magenta or cyan particles.
  • AVERAGE SPEED MAGENTA or CYAN: average speed of magenta or cyan particles.


  • AVERAGE ENERGY: average energy of the different particles over time.
  • AVERAGE SPEED: average speed of the different particles over time.


What variables affect how quickly the model reaches a new equilibrium when the wall is removed?

Why does the average speed for each color decrease as the model runs with the wall in place, even though the average energy remains constant?

What happens to the relative energies and speeds of each kind of particle as they intermingle? What effect do the initial speeds and masses have on this relationship?

Does the system reach an equilibrium state?

Do heavier particles tend to have higher or lower speeds when the distribution of energy has reached equilibrium?

Is it reasonable that this box can be considered to be "insulated"?


Calculate how long the model takes to reach equilibrium with different sizes of windows (holding other parameters constant).

Calculate how long the model takes to reach equilibrium with different particle speeds.

Set the number of cyan particles to zero. This is a model of a gas expanding into a vacuum. This experiment was first done by Joule, using two insulated chambers separated by a valve. He found that the temperature of the gas remained the same when the valve was opened. Why would this be true? Is this model consistent with that observation?

Try some extreme situations, to test your intuitive understanding: -- masses the same, speeds of the two particles very different. -- speeds the same, masses very different. -- a very small number of one kind of particle -- almost, but not quite a vacuum. What happens to those few particles, and how do they affect the other kind?

Try relating quantitatively the ratio of the equilibrium speeds of both gases after the wall is opened to the ratio of the masses of both gases. How are they related?


Monitor pressure in the right and left chambers.

Monitor temperature in the right and left chambers.

Replace the partition wall with a moveable piston, so that the two kinds of particles can push against each other without intermingling. Do they arrive at a different equilibrium then?

Replace the partition wall with a surface that can transmit energy.

Add the histograms of energy and speed distribution (such as found in the "Free Gas" model).


Notice how collisions are detected by the turtles and how the code guarantees that the same two particles do not collide twice. What happens if we let the patches detect them?


This model was developed as part of the GasLab curriculum ( and has also been incorporated into the Connected Chemistry curriculum (


If you mention this model or the NetLogo software in a publication, we ask that you include the citations below.

For the model itself:

Please cite the NetLogo software as:


Copyright 1997 Uri Wilensky.


This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. To view a copy of this license, visit or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

Commercial licenses are also available. To inquire about commercial licenses, please contact Uri Wilensky at

This model was created as part of the project: CONNECTED MATHEMATICS: MAKING SENSE OF COMPLEX PHENOMENA THROUGH BUILDING OBJECT-BASED PARALLEL MODELS (OBPML). The project gratefully acknowledges the support of the National Science Foundation (Applications of Advanced Technologies Program) -- grant numbers RED #9552950 and REC #9632612.

This model was converted to NetLogo as part of the projects: PARTICIPATORY SIMULATIONS: NETWORK-BASED DESIGN FOR SYSTEMS LEARNING IN CLASSROOMS and/or INTEGRATED SIMULATION AND MODELING ENVIRONMENT. The project gratefully acknowledges the support of the National Science Foundation (REPP & ROLE programs) -- grant numbers REC #9814682 and REC-0126227. Converted from StarLogoT to NetLogo, 2002.

Comments and Questions

Please start the discussion about this model! (You'll first need to log in.)

Click to Run Model

  tick-delta                           ;; how much we advance the tick counter this time through
  max-tick-delta                       ;; the largest tick-delta is allowed to be
  box-edge                             ;; distance of box edge from axes
  left-particles right-particles       ;; particles in the left and right chambers
  avg-speed-cyan avg-energy-cyan       ;; left chamber averages
  avg-speed-magenta avg-energy-magenta ;; right chamber averages
  fast medium slow                     ;; current counts
  cyans magentas

breed [ particles particle ]
breed [ flashes flash ]

flashes-own [birthday]

  speed mass energy          ;; particle info

to setup
  set-default-shape particles "circle"
  set-default-shape flashes "square"
  set max-tick-delta 0.1073
  set box-edge (round (max-pxcor * box-size / 100) - 1)

to update-variables
  set avg-speed-cyan      mean [speed] of cyans
  set avg-speed-magenta    mean [speed] of magentas
  set avg-energy-cyan     mean [energy] of cyans
  set avg-energy-magenta   mean [energy] of magentas

to go
  ask particles [set step-size speed * tick-delta]
  ask particles [bounce]
  ask particles [ move ]
  ask particles
  [ if collide? [check-for-collision] ]
  tick-advance tick-delta
  if floor ticks > floor (ticks - tick-delta)

  ask flashes with [ticks - birthday > 0.4]
    [ die ]

to calculate-tick-delta
  ;; tick-delta is calculated in such way that even the fastest
  ;; particle will jump at most 1 patch length in a tick. As
  ;; particles jump (speed * tick-delta) at every tick, making
  ;; tick length the inverse of the speed of the fastest particle
  ;; (1/max speed) assures that. Having each particle advance at most
  ;; one patch-length is necessary for it not to "jump over" a wall.
  ifelse any? particles with [speed > 0]
    [ set tick-delta min list (1 / (ceiling max [speed] of particles)) max-tick-delta ]
    [ set tick-delta max-tick-delta ]

to bounce  ;; particle procedure
  ;; if we are already on a wall, no need for further checks
  if pcolor = yellow [stop]
  ;; get the coordinates of the patch we'll be on if we go forward 1
  let new-patch patch-ahead step-size
  let new-px [pxcor] of new-patch
  let new-py [pycor] of new-patch
  if [pcolor] of new-patch != yellow
    [ stop ]
  ;; if hitting left or right wall, reflect heading around x axis
  if abs new-px = box-edge [ set heading (- heading)]
  ;; if hitting top or bottom wall, reflect heading around y axis
  if abs new-py = box-edge  [ set heading (180 - heading) ]
  ;; if hitting partition, reflect heading around x axis unless near an opening
  if new-px = 0 [set heading ( - heading)
                if [pcolor] of patch-ahead step-size = yellow [set heading  (180 - heading)]]
 ;; create some flash turtles to show the bouncing particles
  ask patch new-px new-py
  [ sprout-flashes 1 [
      set color pcolor - 2
      set birthday ticks

to move  ;; particle procedure
  if patch-ahead (speed * tick-delta) != patch-here
    [ set last-collision nobody ]
  jump (speed * tick-delta)

to check-for-collision  ;; particle procedure
  ;; Here we impose a rule that collisions only take place when there
  ;; are exactly two particles per patch.  We do this because when the
  ;; student introduces new particles from the side, we want them to
  ;; form a uniform wavefront.
  ;; Why do we want a uniform wavefront?  Because it is actually more
  ;; realistic.  (And also because the curriculum uses the uniform
  ;; wavefront to help teach the relationship between particle collisions,
  ;; wall hits, and pressure.)
  ;; Why is it realistic to assume a uniform wavefront?  Because in reality,
  ;; whether a collision takes place would depend on the actual headings
  ;; of the particles, not merely on their proximity.  Since the particles
  ;; in the wavefront have identical speeds and near-identical headings,
  ;; in reality they would not collide.  So even though the two-particles
  ;; rule is not itself realistic, it produces a realistic result.  Also,
  ;; unless the number of particles is extremely large, it is very rare
  ;; for three or more particles to land on the same patch (for example,
  ;; with 400 particles it happens less than 1% of the time).  So imposing
  ;; this additional rule should have only a negligible effect on the
  ;; aggregate behavior of the system.
  ;; Why does this rule produce a uniform wavefront?  The particles all
  ;; start out on the same patch, which means that without the only-two
  ;; rule, they would all start colliding with each other immediately,
  ;; resulting in much random variation of speeds and headings.  With
  ;; the only-two rule, they are prevented from colliding with each other
  ;; until they have spread out a lot.  (And in fact, if you observe
  ;; the wavefront closely, you will see that it is not completely smooth,
  ;; because some collisions eventually do start occurring when it thins out while fanning.)

  if count other particles-here = 1
    ;; the following conditions are imposed on collision candidates:
    ;;   1. they must have a lower who number than my own, because collision
    ;;      code is asymmetrical: it must always happen from the point of view
    ;;      of just one particle.
    ;;   2. they must not be the same particle that we last collided with on
    ;;      this patch, so that we have a chance to leave the patch after we've
    ;;      collided with someone.
    let candidate one-of other particles-here with
      [who < [who] of myself and myself != last-collision]
    ;; we also only collide if one of us has non-zero speed. It's useless
    ;; (and incorrect, actually) for two particles with zero speed to collide.
    if (candidate != nobody) and (speed > 0 or [speed] of candidate > 0)
      collide-with candidate
      set last-collision candidate
      ask candidate [ set last-collision myself ]

;; implements a collision with another particle.
;; The two particles colliding are self and other-particle, and while the
;; collision is performed from the point of view of self, both particles are
;; modified to reflect its effects. This is somewhat complicated, so I'll
;; give a general outline here:
;;   1. Do initial setup, and determine the heading between particle centers
;;      (call it theta).
;;   2. Convert the representation of the velocity of each particle from
;;      speed/heading to a theta-based vector whose first component is the
;;      particle's speed along theta, and whose second component is the speed
;;      perpendicular to theta.
;;   3. Modify the velocity vectors to reflect the effects of the collision.
;;      This involves:
;;        a. computing the velocity of the center of mass of the whole system
;;           along direction theta
;;        b. updating the along-theta components of the two velocity vectors.
;;   4. Convert from the theta-based vector representation of velocity back to
;;      the usual speed/heading representation for each particle.
;;   5. Perform final cleanup and update derived quantities.

to collide-with [ other-particle ] ;; particle procedure
  ;;; PHASE 1: initial setup

  ;; for convenience, grab some quantities from other-particle
  let mass2 [mass] of other-particle
  let speed2 [speed] of other-particle
  let heading2 [heading] of other-particle

  ;; since particles are modeled as zero-size points, theta isn't meaningfully
  ;; defined. we can assign it randomly without affecting the model's outcome.
  let theta (random-float 360)

  ;;; PHASE 2: convert velocities to theta-based vector representation

  ;; now convert my velocity from speed/heading representation to components
  ;; along theta and perpendicular to theta
  let v1t (speed * cos (theta - heading))
  let v1l (speed * sin (theta - heading))

  ;; do the same for other-particle
  let v2t (speed2 * cos (theta - heading2))
  let v2l (speed2 * sin (theta - heading2))

  ;;; PHASE 3: manipulate vectors to implement collision

  ;; compute the velocity of the system's center of mass along theta
  let vcm (((mass * v1t) + (mass2 * v2t)) / (mass + mass2) )

  ;; now compute the new velocity for each particle along direction theta.
  ;; velocity perpendicular to theta is unaffected by a collision along theta,
  ;; so the next two lines actually implement the collision itself, in the
  ;; sense that the effects of the collision are exactly the following changes
  ;; in particle velocity.
  set v1t (2 * vcm - v1t)
  set v2t (2 * vcm - v2t)

  ;;; PHASE 4: convert back to normal speed/heading

  ;; now convert my velocity vector into my new speed and heading
  set speed sqrt ((v1t ^ 2) + (v1l ^ 2))
  set energy (0.5 * mass * speed * speed)
  ;; if the magnitude of the velocity vector is 0, atan is undefined. but
  ;; speed will be 0, so heading is irrelevant anyway. therefore, in that
  ;; case we'll just leave it unmodified.
  if v1l != 0 or v1t != 0
    [ set heading (theta - (atan v1l v1t)) ]

  ;; and do the same for other-particle
  ask other-particle [
    set speed sqrt ((v2t ^ 2) + (v2l ^ 2))
    set energy (0.5 * mass * (speed ^ 2))
    if v2l != 0 or v2t != 0
      [ set heading (theta - (atan v2l v2t)) ]

  ;; PHASE 5: final updates

  ;; now recolor, since color is based on quantities that may have changed
  ask other-particle
    [ recolor ]

to recolor  ;; particle procedure
  let values [ speed ] of breed
  let lower-limit mean values - 3 * standard-deviation values
  let upper-limit mean values + 3 * standard-deviation values
  set color scale-color color speed (lower-limit - 1) (upper-limit + 1)

;;; drawing procedures

;; draws the box

to make-box
  ask patches with [ ((abs pxcor = box-edge) and (abs pycor <= box-edge)) or
                     ((abs pycor = box-edge) and (abs pxcor <= box-edge)) or
                     ((abs pycor <= box-edge) and (pxcor = 0))]
    [ set pcolor yellow ]

to open-middle
  ask patches with [ pxcor = 0 and (abs pycor <= floor (box-edge * (opening-size / 100)))
                     and (abs pycor <= (box-edge - 1))] ;; in case opening reaches box edge
  [set pcolor black ask flashes-here [die]]

to close-middle
  ask patches with [ pxcor = 0 and (abs pycor <= box-edge) ]
    [ set pcolor yellow ]

;; creates initial particles

to make-particles
  create-particles num-cyans [
    set speed cyan-temperature
    set mass cyan-mass
    set color cyan
  create-particles num-magentas [
    set speed magenta-temperature
    set mass magenta-mass
    set shape "circle"
    set color magenta
  set cyans particles with [color = cyan]
  set magentas particles with [color = magenta]
  ask particles
    set energy (0.5 * mass * speed * speed)
    ;; make their graphical size equal to the cube root of their mass
    set size  mass ^ .33
    set last-collision nobody

to random-position-left ;; particle procedure
  setxy ( 1 + random-float (box-edge - 2))
        ((1 - box-edge) + random-float (2 * box-edge - 2))

to random-position-right ;; particle procedure
  setxy ((1 - box-edge) + random-float (box-edge - 2))
        ((1 - box-edge) + random-float (2 * box-edge - 2))

;;; plotting procedures

to-report max-init-speed
  report (max (list cyan-temperature magenta-temperature))

to-report max-particle-mass
  report (max (list cyan-mass magenta-mass))

; Copyright 1997 Uri Wilensky.
; See Info tab for full copyright and license.

There are 5 versions of this model.

Uploaded by When Description Download
Tony Matthys almost 5 years ago Changed initial temperature to 5 Download this version
Tony Matthys almost 5 years ago Changed variable name to include temperature Download this version
Tony Matthys about 5 years ago further reduced number of reporters Download this version
Tony Matthys about 5 years ago Reduced the number of reporters and increased graph size Download this version
Tony Matthys about 5 years ago Initial upload Download this version

Attached files

File Type Description Last updated
TwoGas Mixing.png preview Preview for 'TwoGas Mixing' about 5 years ago, by Tony Matthys Download

This model does not have any ancestors.

This model does not have any descendants.