Symbolic maths in Python: Attacking a castle with SymPy
While working on my Moon lander guidance software, I am making several small prototypes to test ideas. One of them involves testing several control laws (of the acceleration), which implies quite a lot of manual calculations (to integrate to obtain the velocity and position).
Doing these calculations by hand is tedious and error prone, and I thought about using a symbolic math program. Usually, a programming language can not manipulate variables without predefined values, but I found a Python library which can: SymPy.
This article will serve as a small demonstration of its capabilities, and to do so, we will jump a few centuries before rocketry was invented: let’s attack a castle!
The main point of SymPy is that it understands maths.
For example, with the standard Python library, computing
math.sqrt(8) will gives us
For engineers, this is not really false, but for mathematicians, it is not really true either.
If you ask SymPy,
2*sqrt(2), which is mathematically exact.
Before doing anything with SymPy, you need to declare the symbols you will use in your expressions.
Let’s declare a symbol
x, and compute the arbitrary expression
cos(x)**2 + sin(x)**2.
sin(x)**2 + cos(x)**2, showing that SymPy has understood the expression.
1, as expected (if you remember your math lessons).
Symbols are very powerful, and they allow SymPy to do smart things, such as integrating an acceleration to obtain the velocity. With plain Python; you would not be able to do that.
SymPy’s documentation puts it well, so I’m just going to quote it:
The real power of a symbolic computation system such as SymPy is the ability to do all sorts of computations symbolically. SymPy can simplify expressions, compute derivatives, integrals, and limits, solve equations, work with matrices, and much, much more, and do it all symbolically
Compute integrals? Let’s try this!
Note that the constant is not automatically added to the integrated expression, because it is not as easy as it looks, for example for expressions with multiple variables. You will need to do it manually, with the knowledge of the context around the problem you are solving, which SymPy can not do. Feel free to look at the Github issue(s) for more info.
Symbolic computations allows you to do all sorts of manipulation symbolically, and plug values in at the last time.
Substituting values is done with the
What is the value of the integral of
f(x) = x**2 for x=1?
Predicting a cannonball shot
Now that you understand the basics of SymPy, let’s dive deep by modeling the trajectory of a cannonball. We’re going to start with the acceleration, and integrate it to obtain the velocity and position. Later, we will plug values in for the shooting angle, initial velocity and other constants and compute the trajectory.
Variables and equations
First, we define a few symbols for our time variable (t), constant (g), and parameters (v0, angle). When defining the symbols, we pass some additional information to help SymPy when manipulating the expressions. When solving equations later, it will prevent SymPy from giving us nonsensical solutions (for example, negative time).
We then define the equations, starting with the acceleration.
There is only
g (if the castle you are attacking is on a windy hill, feel free to add it).
Additionally, the initial velocity in the x and y axis depends on the angle, and the initial position is zero.
Thanks to SymPy and its integration feature, the final equations are calculated automatically.
Calculating the trajectory
Second, we calculate, for each
t, the position.
The only thing to pay attention to, is to not mix up a SymPy variable and its value.
In my examples, the SymPy variables are lowercase (for ex.
g), while the values are uppercase (
float() is used to force SymPy to compute an actual value.
With this simple example, it is probably not needed, but in more complex cases, it can be useful to ensure that SymPy actually computes a value.
If it can not, and the expressions still has variables, it will fail loudly (raise an exception), allowing you to debug and fix the code.
The previous code is run for several angles (20°, 30°, 40°, 50°), and the trajectory is plotted.
It can be seen that the furthest impact is at around 250 m, for an angle of 40° and 50° (the maximum range of the cannon is probably with an angle of 45°, at around 230 m).
With a handful of lines of code and absolutely no manual calculations, SymPy perfectly answers our problem of modeling a cannonball.
Attacking a castle
Before we attack the fortress, my French-speaking readers will enjoy rewatching this excerpt from a masterpiece of the French’s seventh art.
While we wait for those who clicked the link to come back, let me introduce you with our target. This castle seems a bit crude, but I am sure it is a very cozy place once fully furnished and heated. Let’s attempt to conquer it!
Our soldiers just spotted the king in the second tower! There is not a lot of time to kill him, and we probably have only one attempt before he hides.
At which angle should we shoot the cannonball? We already know the motion equations, and thanks to our engineers and surveyors, we now know the target coordinates: (245, 37), and the initial velocity of the cannonball: 60 m/s (I’m a software engineer, not a fireworks operator, so I’m going to take their word for it).
So, for a given initial velocity of 60 m/s, there are two solutions to hit the enemy king: one with an angle of 31° (time of flight 4.8 sec) and one with an angle of 67° (time of flight 10.6 sec).
If we are short on powder, we can compute the parameters for a shoot to save as much as possible. To achieve this, we will solve for the point where the initial velocity is minimal, which is where the derivative of the initial velocity is 0.
On the following graph, you can see the previously mentioned v0 = 60 m/s shots, with our beautiful minimal shot with v0_min = 52.8 m/s.
In this article, I hope to have given you a good overview of SymPy’s features and how to use it.
I used a simple example to demonstrated some of SymPy features: using symbols, substituting values, applying mathematical operations such as integration, and solving equations. Through this basic example, I have highlighted in which cases SymPy can be useful: problems which have many parameters. In particular, an aerospace study (where the spacecraft have many parameters: mass, thrust, etc) can greatly benefit from this tool. Coupled with matplotlib for plotting, SymPy is 🔥!
In the future, I will keep SymPy in my toolbox, and remember to use it when appropriate. In particular, I plan to study various guidance control laws for my Moon lander guidance software (next article incoming). Once I have a good understanding of guidance, I plan to design various spacecraft in KSP and fly them. In this case, SymPy will probably be helpful to dynamically adapt to the different configurations.
I will probably not use SymPy very often, but when needed, it will save me a lot of time and avoid errors. I find it crazy that such a library exists, or is even possible. FOSS = <3.
Note: the source code is available here.