Kerbal Space Program simulator
I was playing Kerbal Space Program and I had a limited collection of components available to me to make a rocket out of. After hours of trial and error of trying to reach orbit I finally did, but I decided it would be more efficient to have the computer play the trial and error game for me. The presence of non-constant mass (from fuel and oxidizer usage), non-uniform gravity, and velocity-dependent drag, led me to use a numerical simulation as opposed to analytical solutions.
Usng Python I made a classes for components, stages, and a rocket, so that you could create a rocket by creating a stage, adding components, and then adding the stage to the rocket.
Stage1 = Stage.Stage() Stage1.addComp(Component(.84, .2, 600)) #Command Pod Mk1 Stage1.addComp(Component(4.5, .2, 1600, m_fuel = 1.8, m_ox = 2.2)) #FL-T800 Fuel Tank Stage1.addComp(Component(1.5,.2, 950, thrust = 200, I_sp_sea = 320, I_sp_vac = 370)) #LV-T45 Liquid Fuel Engine Rocket = Rocket.Rocket() Rocket.addStage(Stage1)
Above the arguments .84, .2, 600 refer to mass, drag, and cost.
I used Scipy's odeint function to integrate the rocket's displacement (vertical altitude), velocity (vertical only), and mass through time. Acceleration is calculated as the sum of acceleration due to gravity, acceleration due to thrust, and acceleration due to drag. KSP uses a drag model which is dependent on the atmospheric density (exponential model), ship's velocity, and cross-sectional area of the components. Because the thrust is constant but the specifc impulse is not, the mass flow rate is calculated by dividing the thrust by the current specfic impulse (linearly interpolated between sea and vacuum levels) and the gravitational constant (9.82 m/s).
Verification was done by actually running the configurations in KSP and then looking at the maximum altitude and velocity in the stats. As my code only accounted for vertical-only flight, I tried my best to make sure the rocket went straight up.
Command Pod Mk1 FL-T800 Fuel Tank LV-T45 Liquid Fuel Engine Predicted: Max altitude: 101666.716018m @ 211.6s Max velocity: 1129.50143115m/s @ 69.0s Actual: Max altitude: 102928m @ ~212s Max velocity: ~1134.2m/s @ ~68.0s Percent Difference: Max altitude: 1.233% Max velocity: 0.4151%
Further improvements to this could be to use a non-constant (100%) throttle, account for non-vertical movement, finish the staging code (for more than single-stage rockets), etc. Also the intended purpose of this code was to couple it with a database of all the components in game, as well as an optimization algorithm, to find better rocket configurations to get to orbit with cost constraints.
My code can be found at https://github.com/colonoh/kerbalcat.Home