N-Body Simulation Checklist
Goals
- Learn about a scientific computing application.
- Learn about animation using the Processing library.
- Learn about playing an audio file using the Minim library.
- Learn about opening & closing a
java.io.FileReader
. - Learn about reading & parsing data using the
java.util.Scanner
class. - Learn to use arrays.
FAQ
- What preparation do I need before beginning this assignment?
Learn the Processing library functions for displaying images, the Minim library functions for playing audio files, and familiarize yourself with the command line.
For help with reading data from an input file, review the program Students.kt. Compile and execute to make sure your system is configured properly. You can use studentsData.txt as input file.
For help with displaying images, review BouncingBall.kt. The Processing library has many functions for manipulating images, but for this assignment, you will need only those used in
BouncingBall.kt
. Here is a zipped gradle project BouncingBall.zip. Save and unzip it into your~/mcs178
directory, then docd ~/mcs178/BouncingBall
, followed bygradle run
to make sure your system is configured properly.
For help with playing music, review testMinim.kt. Here is a zipped gradle project PlayMusic.zip. Save and unzip it into your
~/mcs178
directory, then docd ~/mcs178/PlayMusic
, followed bygradle run
to make sure your system is configured properly.
- Any advice on completing this programming assignment?
This program is more involved than those you wrote in previous projects, so you should budget more time accordingly. The best advice we can give you is to carefully test, debug, and re-test your code as you write it. Do not attempt to write the whole program at once—if you do, then you will have no idea where to find the errors when the program doesn't work. Proactive testing will save you enormous amounts of time in the long run.
- Do I have to follow the assignment specifications for reading input from the file whose name is given as a command-line argument?
Yes, or you will lose points.
- Where can I find the APIs for
Scanner
?
The
java.util.Scanner
class documentation is here.
- Where can I find the APIs for Processing and Minim?
They are avaiable through these links: Processing and Minim.
- How do I draw an image to the display window?
See an example in BouncingBall.kt.
- How do I play music?
See an example in testMinim.kt.
Simulation
- Can I combine Steps A, B, and C for each body?
No, as indicated in the assignment, you must separate Step A (calculate all of the forces) from Step B(iii) (update the positions); otherwise, you will be computing the forces at time t using the velocities and positions of some of bodies at time t and others at time t + Δt.
- What is Δx?
It's the change in x-coordinate between two bodies (not between a body at time t and at time t + Δt).
Errors and Bugs
Why do I get an
InputMismatchException
or aNoSuchElementException
when I read data usingjava.util.Scanner
?InputMismatchException
means that your program is attempting to read data of one type but the next piece of data is of an incompatible type. For example, if you callscanner.nextInt()
and the next token on input is.14
.NoSuchElementException
means that your program is trying to read data from input when there is no more data available from it. For example, if you usescanner.nextInt()
twice to read two integers but the input contains only a single integer.
- I draw the bodies, but they do not appear on the screen. Why?
Did you take into consideration the fact that the numbers in the input file are in Cartesian Coordinate system, but the Processing library uses a different coordinate system?
- My bodies repel each other. Why don't they attract each other?
Make sure that you get the sign right when you apply Newton's law of gravitation:
(x[j] - x[i])
vs.(x[i] - x[j])
. Note that Δx and Δy can be positive or negative so do not usekotlin.math.abs()
. Do not consider changing the universal gravitational constant to patch your code!
Testing and Debugging
Inserting print statements is a good way to trace what your program is doing. Our input files were created with the following println()
statements.
println(n) println("%.2e".format(radius)) for (i in 0 until n) { println("%11.4e %11.4e %11.4e %11.4e %11.4e %12s" .format(px[i], py[i], vx[i], vy[i], mass[i], image[i])) }
As indicated in the collaboration policy, you may not copy or adapt code (except from the course materials). Moreover, you need to cite any code that you copy or adapt (except for code provided with the assignment). So, you are free to copy or adapt this code fragment, with or without citation.
Enrichment
- What is the music in
src/resources/2001.wav
?
It's the fanfare to Also sprach Zarathustra by Richard Strauss. It was popularized as the key musical motif in Stanley Kubrick's 1968 film 2001: A Space Odyssey.
- I'm a physicist. Why should I use the leapfrog method instead of the formula I derived in high school? In other words, why does the position update formula use the velocity at the updated time step rather than the previous one? Why not use the 1/2 a t^2 formula?
The leapfrog method is more stable for integrating Hamiltonian systems than conventional numerical methods like Euler's method or Runge–Kutta. The leapfrog method is symplectic, which means it preserves properties specific to Hamiltonian systems (conservation of linear and angular momentum, time-reversibility, and conservation of energy of the discrete Hamiltonian). In contrast, ordinary numerical methods become dissipative and exhibit qualitatively different long-term behavior. For example, the earth would slowly spiral into (or away from) the sun. For these reasons, symplectic methods are extremely popular for n-body calculations in practice.
Here's a more complete explanation of how you should interpret the variables. The classic Euler method updates the position uses the velocity at time t instead of using the updated velocity at time t + Δt. A better idea is to use the velocity at the midpoint t + Δt / 2. The leapfrog method does this in a clever way. It maintains the position and velocity one-half time step out of phase: At the beginning of an iteration, (px, py) represents the position at time t and (vx, vy) represents the velocity at time t − Δt / 2. Interpreting the position and velocity in this way, the updated position (px + Δt vx, py + Δt vy). uses the velocity at time t + Δt / 2. Almost magically, the only special care needed to deal with the half time-steps is to initialize the system's velocity at time t = −Δt / 2 (instead of t = 0.0), and you can assume that we have already done this for you. Note also that the acceleration is computed at time t so that when we update the velocity, we are using the acceleration at the midpoint of the interval under consideration.
- Are there analytic solutions known for n-body systems?
Yes, Sundman and Wang developed global analytic solutions using convergent power series. However, the series converge so slowly that they are not useful in practice. See The Solution of the N-body Problem for a brief history of the problem.
- Who uses n-body simulation?
N-body simulations play a crucial role in our understanding of the universe. Astrophysicists use it to study stellar dynamics at the galactic center, stellar dynamics in a globular cluster, colliding galaxies, and the formation of the structure of the Universe. The strongest evidence we have for the belief that there is a black hole in the center of the Milky Way comes from very accurate n-body simulations. Many of the problems that astrophysicists want to solve have millions or billions of particles. More sophisticated computational techniques are needed.
The same methods are also widely used in molecular dynamics, except that the heavenly bodies are replaced by atoms, gravity is replaced by some other force, and the leapfrog method is called Verlet's method. With van der Waals forces, the interaction energy may decay as 1/R 6 instead of an inverse square law. Occasionally, 3-way interactions must be taken into account, e.g., to account for the covalent bonds in diamond crystals.
Kepler's Orrery uses an n-body simulator to compose and play music.
- What techniques are used to do n-body simulation in practice?
Here's a wealth of information on n-body simulation.
- Any ideas for creating my own universe?
Here are some interesting two-body systems. Here is beautiful 21-body system in a figure-8 —reproducing this system (in a data file in our format) will earn you a small amount of extra credit.