Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/chapters/chap22.ipynb
Views: 531
Printed and electronic copies of Modeling and Simulation in Python are available from No Starch Press and Bookshop.org and Amazon.
Baseball
Modeling and Simulation in Python
Copyright 2021 Allen Downey
License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. Click here to access the notebooks: https://allendowney.github.io/ModSimPy/.
In the previous chapter we modeled an object moving in one dimension, with and without drag. Now let's move on to two dimensions, and baseball!
In this chapter we model the flight of a baseball including the effect of air resistance. In the next chapter we use this model to solve an optimization problem.
Baseball
To model the flight of a baseball, we have to make some decisions. To get started, we'll ignore any spin that might be on the ball, and the resulting Magnus force (see http://modsimpy.com/magnus). Under this assumption, the ball travels in a vertical plane, so we'll run simulations in two dimensions, rather than three.
To model air resistance, we'll need the mass, frontal area, and drag coefficient of a baseball. Mass and diameter are easy to find (see http://modsimpy.com/baseball). Drag coefficient is only a little harder; according to The Physics of Baseball (see https://books.google.com/books/about/The_Physics_of_Baseball.html?id=4xE4Ngpk_2EC), the drag coefficient of a baseball is approximately 0.33 (with no units).
However, this value does depend on velocity. At low velocities it might be as high as 0.5, and at high velocities as low as 0.28. Furthermore, the transition between these values typically happens exactly in the range of velocities we are interested in, between 20 m/s and 40 m/s.
Nevertheless, we'll start with a simple model where the drag coefficient does not depend on velocity; as an exercise at the end of the chapter, you can implement a more detailed model and see what effect it has on the results.
But first we need a new computational tool, the Vector
object.
Vectors
Now that we are working in two dimensions, it will be useful to work with vector quantities, that is, quantities that represent both a magnitude and a direction. We will use vectors to represent positions, velocities, accelerations, and forces in two and three dimensions.
ModSim provides a function called Vector
that creates a Pandas Series
that contains the components of the vector. In a Vector
that represents a position in space, the components are the and coordinates in 2-D, plus a coordinate if the Vector
is in 3-D.
You can create a Vector
by specifying its components. The following Vector
represents a point 3 units to the right (or east) and 4 units up (or north) from an implicit origin:
You can access the components of a Vector
by name using the dot operator, like this:
You can also access them by index using brackets, like this:
Vector
objects support most mathematical operations, including addition:
And subtraction:
For the definition and graphical interpretation of these operations, see http://modsimpy.com/vecops.
We can specify a Vector
with coordinates x
and y
, as in the previous examples. Equivalently, we can specify a Vector
with a magnitude and angle.
Magnitude is the length of the vector: if the Vector
represents a position, magnitude is its distance from the origin; if it represents a velocity, magnitude is its speed.
The angle of a Vector
is its direction, expressed as an angle in radians from the positive axis. In the Cartesian plane, the angle 0 rad is due east, and the angle rad is due west.
ModSim provides functions to compute the magnitude and angle of a Vector
. For example, here are the magnitude and angle of A
:
The magnitude is 5 because the length of A
is the hypotenuse of a 3-4-5 triangle.
The result from vector_angle
is in radians. Most Python functions, like sin
and cos
, work with radians, but many people find it more natural to work with degrees. Fortunately, NumPy provides a function to convert radians to degrees:
And a function to convert degrees to radians:
To avoid confusion, I'll use the variable name angle
for a value in degrees and theta
for a value in radians.
If you are given an angle and magnitude, you can make a Vector
using pol2cart
, which converts from polar to Cartesian coordinates. For example, here's a new Vector
with the same angle and magnitude of A
:
Another way to represent the direction of A
is a unit vector, which is a vector with magnitude 1 that points in the same direction as A
. You can compute a unit vector by dividing a vector by its magnitude:
ModSim provides a function that does the same thing, called vector_hat
because unit vectors are conventionally decorated with a hat, like this: .
Now let's get back to the game.
Simulating Baseball Flight
Let's simulate the flight of a baseball that is batted from home plate at an angle of 45° and initial speed 40 m/s. We'll use the center of home plate as the origin, a horizontal x-axis (parallel to the ground), and a vertical y-axis (perpendicular to the ground). The initial height is 1 m.
Here's a Params
object with the parameters we'll need.
I got the mass and diameter of the baseball from Wikipedia (see https://en.wikipedia.org/wiki/Baseball_(ball)) and the coefficient of drag from The Physics of Baseball (see https://books.google.com/books/about/The_Physics_of_Baseball.html?id=4xE4Ngpk_2EC): The density of air, rho
, is based on a temperature of 20 °C at sea level (see http://modsimpy.com/tempress). As usual, g
is acceleration due to gravity. t_end
is 10 seconds, which is long enough for the ball to land on the ground.
The following function uses these quantities to make a System
object.
make_system
uses deg2rad
to convert angle
to radians and pol2cart
to compute the and components of the initial velocity.
init
is a State
object with four state variables:
x
andy
are the components of position.vx
andvy
are the components of velocity.
When we call System
, we pass params
as the first argument, which means that the variables in params
are copied to the new System
object.
Here's how we make the System
object.
And here's the initial State
:
Drag Force
Next we need a function to compute drag force:
This function takes V
as a Vector
and returns f_drag
as a Vector
.
It uses
vector_mag
to compute the magnitude ofV
, and the drag equation to compute the magnitude of the drag force,mag
.Then it uses
vector_hat
to computedirection
, which is a unit vector in the opposite direction ofV
.Finally, it computes the drag force vector by multiplying
mag
anddirection
.
We can test it like this:
The result is a Vector
that represents the drag force on the baseball, in Newtons, under the initial conditions.
Now we can add drag to the slope function.
As usual, the parameters of the slope function are a time stamp, a State
object, and a System
object. We don't use t
in this example, but we can't leave it out because when run_solve_ivp
calls the slope function, it always provides the same arguments, whether they are needed or not.
slope_func
unpacks the State
object into variables x
, y
, vx
, and vy
. Then it packs vx
and vy
into a Vector
, which it uses to compute acceleration due to drag, a_drag
.
To represent acceleration due to gravity, it makes a Vector
with magnitude g
in the negative direction.
The total acceleration of the baseball, A
, is the sum of accelerations due to gravity and drag.
The return value is a sequence that contains:
The components of velocity,
V.x
andV.y
.The components of acceleration,
A.x
andA.y
.
These components represent the slope of the state variables, because V
is the derivative of position and A
is the derivative of velocity.
As always, we can test the slope function by running it with the initial conditions:
Using vectors to represent forces and accelerations makes the code concise, readable, and less error-prone. In particular, when we add a_grav
and a_drag
, the directions are likely to be correct, because they are encoded in the Vector
objects.
Adding an Event Function
We're almost ready to run the simulation. The last thing we need is an event function that stops when the ball hits the ground.
The event function takes the same parameters as the slope function, and returns the coordinate of position. When the coordinate passes through 0, the simulation stops.
As we did with slope_func
, we can test event_func
with the initial conditions.
Here's how we run the simulation with this event function:
The message indicates that a "termination event" occurred; that is, the simulated ball reached the ground.
results
is a TimeFrame
with one row for each time step and one column for each of the state variables. Here are the last few rows.
We can get the flight time like this:
And the final state like this:
The final value of y
is close to 0, as it should be. The final value of x
tells us how far the ball flew, in meters.
We can also get the final velocity, like this:
The magnitude of final velocity is the speed of the ball when it lands.
The final speed is about 26 m/s, which is substantially slower than the initial speed, 40 m/s.
Visualizing Trajectories
To visualize the results, we can plot the and components of position like this:
As expected, the component increases as the ball moves away from home plate. The position climbs initially and then descends, falling to 0 m near 5.0 s.
Another way to view the results is to plot the component on the -axis and the component on the -axis, so the plotted line follows the trajectory of the ball through the plane:
This way of visualizing the results is called a trajectory plot (see http://modsimpy.com/trajec). A trajectory plot can be easier to interpret than a time series plot, because it shows what the motion of the projectile would look like (at least from one point of view). Both plots can be useful, but don't get them mixed up! If you are looking at a time series plot and interpreting it as a trajectory, you will be very confused.
Notice that the trajectory is not symmetric. With a launch angle of 45°, the landing angle is closer to vertical, about 57° degrees.
Animating the Baseball
One of the best ways to visualize the results of a physical model is animation. If there are problems with the model, animation can make them apparent.
The ModSimPy library provides animate
, which takes as parameters a TimeSeries
and a draw function. The draw function should take as parameters a time stamp and a State
. It should draw a single frame of the animation.
Inside the draw function, should use decorate
to set the limits of the and axes. Otherwise matplotlib
auto-scales the axes, which is usually not what you want.
Now we can run the animation like this:
You can see the results when you run the code from this chapter.
To run the animation, uncomment the following line of code and run the cell.
Summary
This chapter introduces Vector
objects, which we use to represent position, velocity, and acceleration in two dimensions. We also represent forces using vectors, which make it easier to add up forces acting in different directions.
Our ODE solver doesn't work with Vector
objects, so it takes some work to pack and unpack their components. Nevertheless, we were able to run simulations with vectors and display the results.
In the next chapter we'll use these simulations to solve an optimization problem.
Exercises
This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. You can access the notebooks at https://allendowney.github.io/ModSimPy/.
Exercise 1
Run the simulation with and without air resistance. How wrong would we be if we ignored drag?
Exercise 2
The baseball stadium in Denver, Colorado is 1,580 meters above sea level, where the density of air is about 1.0 kg / m. Compared with the example near sea level, how much farther would a ball travel if hit with the same initial speed and launch angle?
Exercise 3
The model so far is based on the assumption that coefficient of drag does not depend on velocity, but in reality it does. The following figure, from Adair, The Physics of Baseball, shows coefficient of drag as a function of velocity (see https://books.google.com/books/about/The_Physics_of_Baseball.html?id=4xE4Ngpk_2EC).
I used an online graph digitizer (https://automeris.io/WebPlotDigitizer) to extract the data and save it in a CSV file.
The following cell downloads the data file.
We can use Pandas to read it.
Here are the first few rows.
I'll use Pint to convert miles per hour to meters per second.
I'll put the results in a Series
.
Here's what it looks like.
And, for use in the slope function, we can make a function that interpolates the data.
Modify the model to include the dependence of C_d
on velocity, and see how much it affects the results.