Swarm-NG  1.1
integration_plot_tutorial.py
Go to the documentation of this file.
1 ## @file integration_plot_tutorial.py Advanced tutorial
2 # on how to examine the ensemble before and after
3 # the integration to plot meaningful results
4 #
5 # refer to @ref TutorialPythonIntegrationPlot for the formatted version
6 
7 # @page TutorialPythonIntegrationPlot Advanced Python Integration Tutorial
8 #
9 # In this tutorial, we explore the different ways to
10 # examine an ensemble before and after integration.
11 # We also demonstrate how to convert the position and
12 # velocity of planets into orbital elements and finally,
13 # we plot the difference in semi-major axis of planets.
14 #
15 # Source code for this tutorial can be found at @ref py/integration_plot_tutorial.py
16 # \section setup Set-up
17 #
18 # The set-up is quite similar to approach taken in @ref TutorialPythonResume.
19 #
20 # Import the packages and parse the command-line arguments
21 
22 import swarmng
23 from os import path
24 import argparse
25 
26 parser = argparse.ArgumentParser()
27 parser.add_argument("-c", "--config" , help="Config file", required = True)
28 args = parser.parse_args()
29 
30 # Next, load the config file and the initial conditions
31 cfg = swarmng.Config.load(args.config)
32 
33 fn = cfg["input"]
34 ext = path.splitext(fn)[1]
35 if ext == "txt" : ens = swarmng.DefaultEnsemble.load_from_text(fn)
37 
38 #
39 # Integration is the same as the basic tutorial
40 ref = ens.clone()
41 swarmng.init(cfg)
42 integ = swarmng.Integrator.create( cfg )
43 integ.ensemble = ens
44 integ.destination_time = float(cfg["destination_time"])
45 integ.integrate()
46 
47 # \section ed Examining data
48 #
49 # At this point, the integration is completed. For analysis
50 # we have two ensembles: `ref`, the reference ensemble
51 # that keeps a copy of initial conditions and `ens`,
52 # the working copy that was simulated to the `destination_time`.
53 #
54 # In this example, we want to find the semi-major axis of planets and
55 # find the evolution of this variable over time.
56 #
57 # The basic access methods only give us position and velocity of planets.
58 # To calculate the orbital elements, we use the function
59 # @ref swarmng.keplerian_for_cartesian.
60 #
61 # The function `extarct_semi_major` takes an ensemble
62 # and calculate the semi-major axis for all planets in
63 # all of systems and returns a two-dimentional array of
64 # the results. For easier plotting, the first dimension
65 # is the planet number and the second dimension is the
66 # system number.
67 #
68 # For large two-dimensional arrays, we use NumPy. It is
69 # much faster than regular Python arrays.
70 #
71 # The core function to calculate the semi-major axis is
72 # @ref swarmng.keplerian_for_cartesian. It takes two 3-tuples
73 # for the information of the planet and the star and returns
74 # a tuple of all orbital elemets. For more details refer to
75 # documentation for @ref swarmng.keplerian_for_cartesian.
76 import numpy
77 
78 def extract_semi_major(en):
79  shape = (ens.nbod-1,ens.nsys)
80  value = numpy.empty(shape)
81  for sysid, sys in enumerate(en):
82  star = sys[0]
83  center = (star.pos,star.vel,star.mass)
84 
85  for bodid in range(1,en.nbod):
86  bod = sys[bodid]
87  planet = (bod.pos,bod.vel,bod.mass)
88  orbital_elements = swarmng.keplerian_for_cartesian(planet,center)
89  value[bodid-1,sysid] = orbital_elements.a
90 
91  return value
92 
93 # We calculate semi-major axis values for both ensembles: initial and
94 # final conditions (final means after the simulation).
95 initial = extract_semi_major(ref)
96 final = extract_semi_major(ens)
97 #
98 # The results are basically two-dimensional arrays of same shape.
99 # The next line normalizes the changes on the values.
100 # Note
101 # that the operations are carried out element-wise, so that
102 # the line of code here is equivalent to executing
103 # `change[i,j] = (final[i,j]-initial[i,j])/initial[i,j]` for
104 # all valid `i`,`j`.
105 change = (final-initial)/initial
106 
107 #
108 # \section plt Plotting
109 #
110 # For every planet, we plot a scatter plot of change of semi-major axis
111 # where each data point represents the change in one of the systems.
112 # The plots from different planets are overlapped but distinguished
113 # by different markers.
114 #
115 # X-axis represents the initial value of the semi-major axis calculated
116 # from the initial conditions.
117 #
118 # Y-axis represents the normalized change in the semi-major axis for
119 # individual planets in different systems.
120 #
121 markers = [ '.','x', '*', '^', 's', 'o' ]
122 import matplotlib.pyplot as P
123 for i in range(1,ens.nbod):
124  P.scatter(initial[i-1],change[i-1],marker= markers[i-1], label="Planet {0}".format(i))
125 
126 P.xlabel('Initial semi-major axis')
127 P.ylabel('Relative change of semi-major axis')
128 P.legend(title="Semi-major axis change")
129 P.savefig("semi_major_axis_comparison")
130 #
131 # The generated plot is saved as `semi_major_axis_comparison`
132 # in the currenty working directory.
133 #
134 # \section conc Conclusion
135 #
136 # In this, tutorial we explored how to extract information from an ensemble
137 # in a real application. You can change the tutorial to plot other
138 # orbital elements, or change the simulation part to more complicated one.
139 #
140 # We used NumPy and MatPlotLib packages, it is not possible to cover
141 # those packages in this tutorial. It is best to look for comprehensive
142 # tutorials of these packages on their respective websites.
143 #
144 #
145 # **Where to go from here:**
146 # * @ref swarmng.keplerian_for_cartesian documentation for using other orbital element parameters.
147 # * @ref swarmng.Body documentation for other attributes of bodies that can be extracted from the ensemble
148 # * <a href="http://wiki.scipy.org/Tentative_NumPy_Tutorial">
149 # Tentative NumPy Tutorial</a> for explanation of NumPy objects and
150 # operators defined on them. There is also examples on element-wise
151 # operations on n-dimensional arrays.
152 # * <a href="http://matplotlib.org/users/pyplot_tutorial.html">
153 # MatPlotLib tutorial</a> for customizing plots and creating other types of plots.
154 #