Step 3: Your first N-body program
In this step, we will write our first N-body program. We have set up the initial conditions in step 1 and the acceleration function in step 2. Now, we will need to solve the equations of motion for the particles. For Newtonian mechanics, we have the following coupled equations:
They are ordinary differential equations (ODEs). To solve them, we will need a ODE solver.
Euler method
The simplest ODE solver is the Euler method, where the update is approximated as
where \(\Delta t\) is the time step. By Taylor expansion, we can see that this is a first-order approximation,
where \(\mathcal{O}(\Delta t^2)\) is the local truncation error if \(\Delta t \to 0\). Because the total number of steps scales with \(1/\Delta t\), the global error is
If you are not familiar with the big-O notation, you can think of it as the error is being bounded by a polynomial in the order of \(\Delta t\).
Implementing the Euler integrator is very easy. With
we have the following code:
def euler(a: np.ndarray, system: System, dt: float) -> None:
"""
Advance one step with the Euler's method.
Parameters
----------
a : np.ndarray
Gravitational accelerations array with shape (N, 3).
system : System
System object.
dt : float
Time step.
"""
acceleration(a, system)
system.x += system.v * dt
system.v += a * dt
Now, we will build all the components we need for our N-body program.
Solution output
We will need a way to store the solution. A naive way is to store the system at every time step or every few time steps. However, this is a terrible idea because the output size will depends on your choice of time step. A better way is to store the solution at regular intervals. In our simulation, we will use a output interval of 0.1 years. For a simulation of 200 years, we will have 2000 time steps.
Tip
For the Solar system, we only have 9 particles and it takes very little memory to store. So, you don't need to worry too much about the solution size. Just be careful and don't set the output interval too small.
Before the simulation, we will need to set up the output array and store the initial conditions.
OUTPUT_INTERVAL = 0.1 * 365.24 # years to days
def main() -> None:
...
# Solution array
sol_size = int(TF // OUTPUT_INTERVAL + 2) # +2 for initial and final time
sol_x = np.zeros((sol_size, system.num_particles, 3))
sol_v = np.zeros((sol_size, system.num_particles, 3))
sol_t = np.zeros(sol_size)
sol_x[0] = system.x
sol_v[0] = system.v
sol_t[0] = 0.0
output_count = 1
Also, we need to calculate the output time.
def main() -> None:
...
for i in range(NUM_STEPS):
...
if current_time >= next_output_time:
sol_x[output_count] = system.x
sol_v[output_count] = system.v
sol_t[output_count] = current_time
output_count += 1
next_output_time = output_count * OUTPUT_INTERVAL
Finally, we resize the arrays to the actual size.
def main() -> None:
...
sol_x = sol_x[:output_count]
sol_v = sol_v[:output_count]
sol_t = sol_t[:output_count]
Putting it all together
Let's put everything together. We first need to setup the simulation parameters.
# Default units is AU, days, and M_sun
TF = 200.0 * 365.24 # years to days
DT = 1.0
OUTPUT_INTERVAL = 0.1 * 365.24 # years to days
NUM_STEPS = int(TF / DT)
Before running the simulation, it is a good idea to print the simulation information.
def print_simulation_info_fixed_step_size(
system: System,
tf: float,
dt: float,
num_steps: int,
output_interval: float,
sol_size: int,
) -> None:
print("----------------------------------------------------------")
print("Simulation Info:")
print(f"num_particles: {system.num_particles}")
print(f"G: {system.G}")
print(f"tf: {tf} days (Actual tf = dt * num_steps = {dt * num_steps} days)")
print(f"dt: {dt} days")
print(f"Num_steps: {num_steps}")
print()
print(f"Output interval: {output_interval} days")
print(f"Estimated solution size: {sol_size}")
print("----------------------------------------------------------")
Finally, we have the main function that runs the main simulation loop.
I have added a timer to measure the runtime, and a print statement
to show the simulation progress every time we save a solution. The \r
at the end
of the print statement should overwrite the previous line, but you can remove
the print statement if it is spamming your terminal.
def main() -> None:
# Get initial conditions
system, labels, colors, legend = common.get_initial_conditions(INITIAL_CONDITION)
# Initialize memory
a = np.zeros((system.num_particles, 3))
# Solution array
sol_size = int(TF // OUTPUT_INTERVAL + 2) # +2 for initial and final time
sol_x = np.zeros((sol_size, system.num_particles, 3))
sol_v = np.zeros((sol_size, system.num_particles, 3))
sol_t = np.zeros(sol_size)
sol_x[0] = system.x
sol_v[0] = system.v
sol_t[0] = 0.0
output_count = 1
# Launch simulation
common.print_simulation_info_fixed_step_size(
system, TF, DT, NUM_STEPS, OUTPUT_INTERVAL, sol_size
)
next_output_time = output_count * OUTPUT_INTERVAL
start = timeit.default_timer()
for i in range(NUM_STEPS):
common.euler(a, system, DT)
current_time = i * DT
if current_time >= next_output_time:
sol_x[output_count] = system.x
sol_v[output_count] = system.v
sol_t[output_count] = current_time
output_count += 1
next_output_time = output_count * OUTPUT_INTERVAL
print(f"Current time: {current_time:.2f} days", end="\r")
sol_x = sol_x[:output_count]
sol_v = sol_v[:output_count]
sol_t = sol_t[:output_count]
end = timeit.default_timer()
print()
print(f"Done! Runtime: {end - start:.3g} seconds, Solution size: {output_count}")
You should see the following output:
----------------------------------------------------------
Simulation Info:
num_particles: 9
G: 0.00029591220828411956
tf: 73048.0 days (Actual tf = dt * num_steps = 73048.0 days)
dt: 1.0 days
Num_steps: 73048
Output interval: 36.524 days
Estimated solution size: 2001
----------------------------------------------------------
Current time: 73012.00 days
Done! Runtime: 1.1 seconds, Solution size: 2000
Plotting the trajectory
To visualize the trajectory, we have the following function. Notice that we
have one ax.plot
and one ax.scatter
calls. The first one is to plot the
trajectory, and the second one is to plot the final position with a circle marker.
def plot_trajectory(
sol_x: np.ndarray,
labels: list,
colors: list,
legend: bool,
) -> None:
"""
Plot the 2D trajectory.
Parameters
----------
sol_x : np.ndarray
Solution position array with shape (N_steps, num_particles, 3).
labels : list
List of labels for the particles.
colors : list
List of colors for the particles.
legend : bool
Whether to show the legend.
"""
fig = plt.figure()
ax = fig.add_subplot(111, aspect="equal")
ax.set_xlabel("$x$ (AU)")
ax.set_ylabel("$y$ (AU)")
for i in range(sol_x.shape[1]):
traj = ax.plot(
sol_x[:, i, 0],
sol_x[:, i, 1],
color=colors[i],
)
# Plot the last position with marker
ax.scatter(
sol_x[-1, i, 0],
sol_x[-1, i, 1],
marker="o",
color=traj[0].get_color(),
label=labels[i],
)
if legend:
fig.legend(loc="center right", borderaxespad=0.2)
fig.tight_layout()
plt.show()
Then, we add the function call to the end of the main function.
You should see the following plot:
Congrats! You have just written your first N-body simulation program!
However, we can see that the results are not very accurate, especially for those inner planets.
(Mercury has drifted to a orbit beyond Saturn within 200 years!)
In the next step, we will implement some higher-order integrators to improve the accuracy.
Full scripts
The full scripts are available at 5_steps_to_n_body_simulation/python/
,
or https://github.com/alvinng4/grav_sim/blob/main/5_steps_to_n_body_simulation/python/
step3.py (Click to expand)
common.py (Click to expand)
5_steps_to_n_body_simulation/python/common.py | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 |
|