-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRocketSimulator.py
More file actions
204 lines (167 loc) · 6 KB
/
RocketSimulator.py
File metadata and controls
204 lines (167 loc) · 6 KB
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
import numpy as np
from scipy.integrate import odeint
from Rocket import Rocket
from Atmosphere import Atmosphere
class RocketSimulator:
def __init__(self, rocket):
"""
Initialize the simulator
Parameters:
----------
rocket : Rocket
Rocket object to simulate
"""
self.rocket = rocket
self.atm = Atmosphere()
def get_mass(self, t):
"""
Calculates the current mass of the rocket accounting for propellant burnoff
Parameters:
----------
t : float
Current time in seconds
Returns:
-----------
mass : float
Current mass in kg
"""
# If propellant has already burned out
if t > self.rocket.burn_time:
return self.rocket.dry_mass
# Propellant consumption rate (kg/s)
mass_flow_rate = self.rocket.propellant_mass / self.rocket.burn_time
# How much propellant has burned in time t
fuel_burned = mass_flow_rate * t
# Current mass = initial mass - burned propellant
return self.rocket.total_mass - fuel_burned
def get_thrust(self, t):
"""
Returns engine thrust at time t
Parameters:
----------
t : float
Current time in seconds
Returns:
-----------
thrust : float
Thrust in Newtons
"""
if t <= self.rocket.burn_time:
return self.rocket.thrust
return 0.0 # Engine off
def derivatives(self, state, t):
"""
KEY FUNCTION: computes derivatives for the ODE system
This is the heart of the simulator! Physics laws are applied here.
Parameters:
----------
state : array [x, y, vx, vy]
x, y - rocket coordinates (m)
vx, vy - velocity components (m/s)
t : float
Current time (s)
Returns:
-----------
derivatives : array [dx/dt, dy/dt, dvx/dt, dvy/dt]
dx/dt = vx
dy/dt = vy
dvx/dt = ax (acceleration along x)
dvy/dt = ay (acceleration along y)
"""
# Unpack state
x, y, vx, vy = state
# Check: if the rocket has hit the ground, stop simulation
if y < 0:
return [0, 0, 0, 0]
# === GET CURRENT PARAMETERS ===
m = self.get_mass(t) # Current mass
thrust = self.get_thrust(t) # Current thrust
g = self.atm.gravity(y) # Gravitational acceleration
rho = self.atm.density(y) # Air density at altitude y
# Total speed (magnitude of velocity vector)
v = np.sqrt(vx ** 2 + vy ** 2)
# === AERODYNAMIC DRAG CALCULATION ===
# Formula: F_drag = 0.5 * ρ * v² * Cd * A
# Directed AGAINST motion
if v > 0.1: # Avoid division by zero
# Drag force magnitude
drag_magnitude = 0.5 * rho * v ** 2 * self.rocket.cd * self.rocket.area
# Projections onto axes (directed against velocity)
drag_x = -drag_magnitude * (vx / v)
drag_y = -drag_magnitude * (vy / v)
else:
drag_x = 0
drag_y = 0
# === THRUST FORCE CALCULATION ===
# Simplification: thrust is directed along the velocity vector
# (in reality the rocket's orientation should be accounted for)
if v > 0.1 and thrust > 0:
# Thrust projections along velocity
thrust_x = thrust * (vx / v)
thrust_y = thrust * (vy / v)
elif thrust > 0:
# At the start of flight (v≈0) direct thrust vertically
thrust_x = 0
thrust_y = thrust
else:
thrust_x = 0
thrust_y = 0
# === NEWTON'S SECOND LAW: F = ma => a = F/m ===
# Sum all forces and divide by mass
ax = (thrust_x + drag_x) / m
ay = (thrust_y + drag_y) / m - g # Minus g because gravity pulls down
# Return derivatives: [dx/dt, dy/dt, dvx/dt, dvy/dt]
return [vx, vy, ax, ay]
def simulate(self, launch_angle=90, duration=60):
"""
Runs the flight simulation
Parameters:
----------
launch_angle : float
Launch angle in degrees (90 = straight up)
duration : float
Simulation duration in seconds
Returns:
-----------
results : dict
Dictionary with simulation results
"""
print(f"Starting simulation (angle: {launch_angle}°)...")
# === INITIAL CONDITIONS ===
angle_rad = np.radians(launch_angle) # Convert degrees to radians
x0 = 0.0 # Initial X coordinate
y0 = 0.1 # Initial altitude (slightly above ground)
vx0 = 0.1 * np.cos(angle_rad) # Initial velocity along X
vy0 = 0.1 * np.sin(angle_rad) # Initial velocity along Y
initial_state = [x0, y0, vx0, vy0]
# === TIME GRID ===
# Create 1000 points from 0 to duration seconds
t = np.linspace(0, duration, 1000)
# === SOLVE ODE SYSTEM ===
# odeint solves the system of differential equations
solution = odeint(self.derivatives, initial_state, t)
# Extract results
x = solution[:, 0] # X coordinate
y = solution[:, 1] # Y coordinate (altitude)
vx = solution[:, 2] # Velocity along X
vy = solution[:, 3] # Velocity along Y
# === TRIM RESULTS AFTER LANDING ===
ground_indices = np.where(y < 0)[0]
if len(ground_indices) > 0:
landing_idx = ground_indices[0]
t = t[:landing_idx]
x = x[:landing_idx]
y = y[:landing_idx]
vx = vx[:landing_idx]
vy = vy[:landing_idx]
print("Simulation complete!")
# Return results as a dictionary
return {
'time': t,
'x': x,
'y': y,
'vx': vx,
'vy': vy,
'velocity': np.sqrt(vx ** 2 + vy ** 2),
'altitude': y
}