### Programming Assignment Checklist: N-Body Simulation

 Goals

• Learn about a scientific computing application.
• Learn about plotting using the StdDraw graphics library.

The submission system says my program exceeds the 80 character limit, but I don't see which line it's on. Can you help? Program WidthChecker.java prints out all lines from standard input longer than a command line input N. Please note that all tabs are converted to 4 spaces during assignment submission.

My computer it too slow to display the animation smoothly. Is there anything I can do? Here are a few suggestions. First, be sure that you are only calling StdDraw.pause once at the end of each time step, instead of after each StdDraw.spot command. You might also try increasing the delay parameter in StdDraw.pause to prevent hoarding system resources.

Can I combine Steps 1, 2, and 3 into one massive loop? No! This will simultaneously screw up the physics and make your code harder to understand and debug.

I draw the planets, but nothing appears on the screen. Why? Use StdDraw.setScale to change the coordinate system to use the physics coordinates instead of the screen ones. Also, be sure that you call StdDraw.pause at the end of each time step.

I'm confused about all of the Δt / 2 terms. Do I need to worry about them to get the physics right? No! The update formulas for velocity and position already take this into account.

What should I use for the initial velocity in the leapfrog method? Use the value from the input file. As a technicality, the leapfrog method should be initialized with the velocity at time t = -Δt / 2, so we'll assume this is the value in the input file. In real codes, special care must be made to deal with this.

I'm a physicist. Why should I use the leapfrog method instead of the formula I derived in high school? 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. You asked!

My planets 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. Note that Δx and Δy can be positive or negative. Do not consider changing the universal gravitational constant G to patch your code!

How should I compute x2? The simplest way is x*x. In Java, the ^ operator means XOR (instead of exponentiation).

When I compile NBody.java, it says "cannot resolve symbol StdDraw." Any thoughts? Be sure you have StdIn.class, StdDraw.class, and Draw.class in the current directory. Also make sure you are running Java 1.4.x and not some older version.

 Input, Output, and Testing

Input. Copy the nbody directory from the COS 126 ftp site to your computer. This includes the image files and many sample data files with interesting universes.

• Windows NT using IE. Click the ftp link above, then right click the nbody folder, and select Copy To Folder.

• OS X using Safari. Click the ftp link above to mount the ftp site, then drag-and-drop the nbody folder from the ftp mount.

• Arizona Unix cluster. Type the following command:
```cp -pr /u/cos126/files/nbody .
```

Compilation.  Your program must be named NBody.java. The capitalization is important. Compile your program with:

`javac NBody.java`
Note that even if you had the .java files of StdDraw and StdIn instead of the .class files, it's not actually necessary to javac StdDraw.java or StdIn.java since this happens automatically when you compile NBody.java.

Execution.  To redirect standard input from a file, execute your program with:

`java NBody < planets.txt`

 Submission

Submission.  Submit NBody.java. Don't forget to hit the "Run Script" button on the submission system to test that it compiles cleanly.

 Possible Progress Steps

These are purely suggestions for how you might make progress. You do not have to follow these steps. Warning: this program is more involved than the previous ones, and you should budget more time accordingly. The best advice we can give you is to carefully test, debug, and re-rest 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 error if the program doesn't work. We promise that proactive testing will save you enormous amounts of time in the long run. Trust us! Also, if you get stumped or frustrated on some portion of the assignment, you should not hesitate to consult a preceptor.

• Review the Bouncing Ball program from lecture for help with graphics, and the Student Precept List program from Section 2.5 for help with standard input. Compile and execute them to make sure your system is configured properly.

• Copy the nbody directory from the COS 126 ftp site to your computer as described above. In particular, be sure you have Draw.class, StdDraw.class, StdIn.class, the image files, and some sample input files in your working directory.

• Read in the data file planets.txt using StdIn.class. To test that you read it in correctly, print the information back out using System.out.println. Do not even think of continuing until you have checked that you read in the data correctly.

• Now, read in the data file and store the information in several arrays. Let rx[i], ry[i], vx[i], vy[i], and mass[i] be real numbers which store the current position (x and y coordinates), velocity (x and y components), and mass of planet i. Let image[i] be a string which represents the filename of the GIF image used to display planet i. Print the information back out. Again, test that you read it in correctly by printing some of it back out.

• Step 3. Plot the background starfield.jpg image. Recall that StdDraw.spot centers the image at the current location, so use StdDraw.go to pre-position at the origin. Test that it works. Now, write a loop to plot the N bodies. Don't forget to call StdDraw.pause(20) after the loop to allow some time rest and display the picture on the screen. Test it. If all goes correctly, you should see the four stationary planets and the sun. Test it on another data file.

• Step 2. Write a loop to calculate the new velocity and position for each body. (This code goes before the stuff you wrote in Step 3.) Since we haven't yet incorporated gravity, assume the acceleration acting on each planet is 0. Add an outer loop to repeat Steps 1 and 2 forever. Test it. You should now see the four planets moving off the screen in a straight line, with constant velocity. Test it on another data file.

• Step 1. Now, calculate the net force acting on each body. (This code goes before the stuff you wrote in Step 2.) You will need two additional arrays fx[i] and fy[i] to store the net force acting planet i. First, write a loop to initialize all the net forces to 0.0. Then write two nested for loops to calculate the net force exerted by planet j on planet i. Add these values to fx[i] and fy[i], but skip the case when i = j. Once you have these values computed, go back to Step 2 and use them to compute the acceleration (instead of assuming it is zero). Test your program on several data files.

• At the beginning of the simulation (outside of any loop), use StdDraw.play to play the 2001 theme. Test it.

 Enrichment

• Here's some information about our solar system.

• Here's a wealth of information on N-body simulation [pdf].

• Here's some of the N-body physics.

• 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. We will revisit one such approach in the final project.

• 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.

COS 126 Assignments
Kevin Wayne