-
-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathflight.py
More file actions
4655 lines (4182 loc) · 185 KB
/
flight.py
File metadata and controls
4655 lines (4182 loc) · 185 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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# pylint: disable=too-many-lines
import math
import warnings
from copy import deepcopy
from functools import cached_property
import numpy as np
from scipy.integrate import BDF, DOP853, LSODA, RK23, RK45, OdeSolver, Radau
from rocketpy.simulation.flight_data_exporter import FlightDataExporter
from ..mathutils.function import Function, funcify_method
from ..mathutils.vector_matrix import Matrix, Vector
from ..motors.point_mass_motor import PointMassMotor
from ..plots.flight_plots import _FlightPlots
from ..prints.flight_prints import _FlightPrints
from ..rocket import PointMassRocket
from ..tools import (
calculate_cubic_hermite_coefficients,
deprecated,
euler313_to_quaternions,
find_closest,
find_root_linear_interpolation,
find_roots_cubic_function,
quaternions_to_nutation,
quaternions_to_precession,
quaternions_to_spin,
)
ODE_SOLVER_MAP = {
"RK23": RK23,
"RK45": RK45,
"DOP853": DOP853,
"Radau": Radau,
"BDF": BDF,
"LSODA": LSODA,
}
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-instance-attributes
class Flight:
"""Keeps all flight information and has a method to simulate flight.
Attributes
----------
Flight.env : Environment
Environment object describing rail length, elevation, gravity and
weather condition. See Environment class for more details.
Flight.rocket : Rocket
Rocket class describing rocket. See Rocket class for more
details.
Flight.parachutes : Parachute
Direct link to parachutes of the Rocket. See Rocket class
for more details.
Flight.frontal_surface_wind : float
Surface wind speed in m/s aligned with the launch rail.
Flight.lateral_surface_wind : float
Surface wind speed in m/s perpendicular to launch rail.
Flight.FlightPhases : class
Helper class to organize and manage different flight phases.
Flight.TimeNodes : class
Helper class to manage time discretization during simulation.
Flight.time_iterator : function
Helper iterator function to generate time discretization points.
Flight.rail_length : float, int
Launch rail length in meters.
Flight.effective_1rl : float
Original rail length minus the distance measured from nozzle exit
to the upper rail button. It assumes the nozzle to be aligned with
the beginning of the rail.
Flight.effective_2rl : float
Original rail length minus the distance measured from nozzle exit
to the lower rail button. It assumes the nozzle to be aligned with
the beginning of the rail.
Flight.name: str
Name of the flight.
Flight._controllers : list
List of controllers to be used during simulation.
Flight.max_time : int, float
Maximum simulation time allowed. Refers to physical time
being simulated, not time taken to run simulation.
Flight.max_time_step : int, float
Maximum time step to use during numerical integration in seconds.
Flight.min_time_step : int, float
Minimum time step to use during numerical integration in seconds.
Flight.rtol : int, float
Maximum relative error tolerance to be tolerated in the
numerical integration scheme.
Flight.atol : int, float
Maximum absolute error tolerance to be tolerated in the
integration scheme.
Flight.time_overshoot : bool, optional
If True, decouples ODE time step from parachute and controller trigger
functions sampling rate. The time steps can overshoot the necessary
trigger function evaluation points and then interpolation is used to
calculate them and feed the triggers. Can greatly improve run
time in some cases.
Flight.terminate_on_apogee : bool
Whether to terminate simulation when rocket reaches apogee.
Flight.solver : scipy.integrate.LSODA
Scipy LSODA integration scheme.
Flight.x : Function
Rocket's X coordinate (positive east) as a function of time.
Flight.y : Function
Rocket's Y coordinate (positive north) as a function of time.
Flight.z : Function
Rocket's z coordinate (positive up) as a function of time.
Flight.vx : Function
Velocity of the rocket's center of dry mass in the X (East) direction of
the inertial frame as a function of time.
Flight.vy : Function
Velocity of the rocket's center of dry mass in the Y (North) direction of
the inertial frame as a function of time.
Flight.vz : Function
Velocity of the rocket's center of dry mass in the Z (Up) direction of
the inertial frame as a function of time.
Flight.e0 : Function
Rocket's Euler parameter 0 as a function of time.
Flight.e1 : Function
Rocket's Euler parameter 1 as a function of time.
Flight.e2 : Function
Rocket's Euler parameter 2 as a function of time.
Flight.e3 : Function
Rocket's Euler parameter 3 as a function of time.
Flight.w1 : Function
Angular velocity of the rocket in the x direction of the rocket's
body frame as a function of time, in rad/s. Sometimes referred to as
pitch rate (q).
Flight.w2 : Function
Angular velocity of the rocket in the y direction of the rocket's
body frame as a function of time, in rad/s. Sometimes referred to as
yaw rate (r).
Flight.w3 : Function
Angular velocity of the rocket in the z direction of the rocket's
body frame as a function of time, in rad/s. Sometimes referred to as
roll rate (p).
Flight.latitude: Function
Rocket's latitude coordinates (positive North) as a function of time.
The Equator has a latitude equal to 0, by convention.
Flight.longitude: Function
Rocket's longitude coordinates (positive East) as a function of time.
Greenwich meridian has a longitude equal to 0, by convention.
Flight.inclination : int, float
Launch rail inclination angle relative to ground, given in degrees.
Flight.heading : int, float
Launch heading angle relative to north given in degrees.
Flight.initial_solution : list
List defines initial condition - [t_initial, x_init,
y_init, z_init, vx_init, vy_init, vz_init, e0_init, e1_init,
e2_init, e3_init, w1_init, w2_init, w3_init]
Flight.t_initial : int, float
Initial simulation time in seconds. Usually 0.
Flight.solution : list
Solution array which keeps results from each numerical
integration.
Flight.t : float
Current integration time.
Flight.y : list
Current integration state vector u.
Flight.out_of_rail_time : int, float
Time, in seconds, in which the rocket completely leaves the
rail.
Flight.out_of_rail_state : list
State vector u corresponding to state when the rocket
completely leaves the rail.
Flight.out_of_rail_velocity : int, float
Velocity, in m/s, with which the rocket completely leaves the
rail.
Flight.apogee_state : array
State vector u corresponding to state when the rocket's
vertical velocity is zero in the apogee.
Flight.apogee_time : int, float
Time, in seconds, in which the rocket's vertical velocity
reaches zero in the apogee.
Flight.apogee_x : int, float
X coordinate (positive east) of the center of mass of the
rocket when it reaches apogee.
Flight.apogee_y : int, float
Y coordinate (positive north) of the center of mass of the
rocket when it reaches apogee.
Flight.apogee : int, float
Z coordinate, or altitude, of the center of mass of the
rocket when it reaches apogee.
Flight.x_impact : int, float
X coordinate (positive east) of the center of mass of the
rocket when it impacts ground.
Flight.y_impact : int, float
Y coordinate (positive east) of the center of mass of the
rocket when it impacts ground.
Flight.impact_velocity : int, float
Velocity magnitude of the center of mass of the rocket when
it impacts ground.
Flight.impact_state : array
State vector u corresponding to state when the rocket
impacts the ground.
Flight.parachute_events : array
List that stores parachute events triggered during flight.
Flight.function_evaluations : array
List that stores number of derivative function evaluations
during numerical integration in cumulative manner.
Flight.function_evaluations_per_time_step : list
List that stores number of derivative function evaluations
per time step during numerical integration.
Flight.time_steps : array
List of time steps taking during numerical integration in
seconds.
Flight.flight_phases : Flight.FlightPhases
Stores and manages flight phases.
Flight.wind_velocity_x : Function
Wind velocity X (East) experienced by the rocket as a
function of time.
Flight.wind_velocity_y : Function
Wind velocity Y (North) experienced by the rocket as a
function of time.
Flight.density : Function
Air density experienced by the rocket as a function of
time.
Flight.pressure : Function
Air pressure experienced by the rocket as a function of
time.
Flight.dynamic_viscosity : Function
Air dynamic viscosity experienced by the rocket as a function of
time.
Flight.speed_of_sound : Function
Speed of Sound in air experienced by the rocket as a
function of time.
Flight.ax : Function
Acceleration of the rocket's center of dry mass along the X (East)
axis in the inertial frame as a function of time.
Flight.ay : Function
Acceleration of the rocket's center of dry mass along the Y (North)
axis in the inertial frame as a function of time.
Flight.az : Function
Acceleration of the rocket's center of dry mass along the Z (Up)
axis in the inertial frame as a function of time.
Flight.alpha1 : Function
Angular acceleration of the rocket in the x direction of the rocket's
body frame as a function of time, in rad/s. Sometimes referred to as
yaw acceleration.
Flight.alpha2 : Function
Angular acceleration of the rocket in the y direction of the rocket's
body frame as a function of time, in rad/s. Sometimes referred to as
yaw acceleration.
Flight.alpha3 : Function
Angular acceleration of the rocket in the z direction of the rocket's
body frame as a function of time, in rad/s. Sometimes referred to as
roll acceleration.
Flight.speed : Function
Rocket velocity magnitude in m/s relative to ground as a
function of time.
Flight.max_speed : float
Maximum velocity magnitude in m/s reached by the rocket
relative to ground during flight.
Flight.max_speed_time : float
Time in seconds at which rocket reaches maximum velocity
magnitude relative to ground.
Flight.horizontal_speed : Function
Rocket's velocity magnitude in the horizontal (North-East)
plane in m/s as a function of time.
Flight.acceleration : Function
Rocket acceleration magnitude in m/s² relative to ground as a
function of time.
Flight.max_acceleration : float
Maximum acceleration magnitude in m/s² reached by the rocket
relative to ground during flight.
Flight.max_acceleration_time : float
Time in seconds at which rocket reaches maximum acceleration
magnitude relative to ground.
Flight.path_angle : Function
Rocket's flight path angle, or the angle that the
rocket's velocity makes with the horizontal (North-East)
plane. Measured in degrees and expressed as a function
of time.
Flight.attitude_vector_x : Function
Rocket's attitude vector, or the vector that points
in the rocket's axis of symmetry, component in the X
direction (East) as a function of time.
Flight.attitude_vector_y : Function
Rocket's attitude vector, or the vector that points
in the rocket's axis of symmetry, component in the Y
direction (East) as a function of time.
Flight.attitude_vector_z : Function
Rocket's attitude vector, or the vector that points
in the rocket's axis of symmetry, component in the Z
direction (East) as a function of time.
Flight.attitude_angle : Function
Rocket's attitude angle, or the angle that the
rocket's axis of symmetry makes with the horizontal (North-East)
plane. Measured in degrees and expressed as a function
of time.
Flight.lateral_attitude_angle : Function
Rocket's lateral attitude angle, or the angle that the
rocket's axis of symmetry makes with plane defined by
the launch rail direction and the Z (up) axis.
Measured in degrees and expressed as a function
of time.
Flight.phi : Function
Rocket's Spin Euler Angle, φ, according to the 3-2-3 rotation
system nomenclature (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time.
Flight.theta : Function
Rocket's Nutation Euler Angle, θ, according to the 3-2-3 rotation
system nomenclature (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time.
Flight.psi : Function
Rocket's Precession Euler Angle, ψ, according to the 3-2-3 rotation
system nomenclature (NASA Standard Aerospace). Measured in degrees and
expressed as a function of time.
Flight.R1 : Function
Aerodynamic force acting along the x-axis of the rocket's body frame
as a function of time. Expressed in Newtons (N).
Flight.R2 : Function
Aerodynamic force acting along the y-axis of the rocket's body frame
as a function of time. Expressed in Newtons (N).
Flight.R3 : Function
Aerodynamic force acting along the z-axis of the rocket's body frame
as a function of time. Expressed in Newtons (N).
Flight.M1 : Function
Aerodynamic moment acting along the x-axis of the rocket's body
frame as a function of time. Expressed in Newtons (N).
Flight.M2 : Function
Aerodynamic moment acting along the y-axis of the rocket's body
frame as a function of time. Expressed in Newtons (N).
Flight.M3 : Function
Aerodynamic moment acting along the z-axis of the rocket's body
frame as a function of time. Expressed in Newtons (N).
Flight.net_thrust : Function
Rocket's engine net thrust as a function of time in Newton.
This is the actual thrust force experienced by the rocket.
It may be corrected with the atmospheric pressure if a reference
pressure is defined.
Flight.aerodynamic_lift : Function
Resultant force perpendicular to rockets axis due to
aerodynamic effects as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamic_drag : Function
Resultant force aligned with the rockets axis due to
aerodynamic effects as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamic_bending_moment : Function
Resultant moment perpendicular to rocket's axis due to
aerodynamic effects as a function of time. Units in N m.
Expressed as a function of time. Can be called or accessed
as array.
Flight.aerodynamic_spin_moment : Function
Resultant moment aligned with the rockets axis due to
aerodynamic effects as a function of time. Units in N m.
Expressed as a function of time. Can be called or accessed
as array.
Flight.rail_button1_normal_force : Function
Upper rail button normal force in N as a function
of time.
Flight.max_rail_button1_normal_force : float
Maximum upper rail button normal force experienced
during rail flight phase in N.
Flight.rail_button1_shear_force : Function
Upper rail button shear force in N as a function
of time.
Flight.max_rail_button1_shear_force : float
Maximum upper rail button shear force experienced
during rail flight phase in N.
Flight.rail_button2_normal_force : Function
Lower rail button normal force in N as a function
of time.
Flight.max_rail_button2_normal_force : float
Maximum lower rail button normal force experienced
during rail flight phase in N.
Flight.rail_button2_shear_force : Function
Lower rail button shear force in N as a function
of time.
Flight.max_rail_button2_shear_force : float
Maximum lower rail button shear force experienced
during rail flight phase in N.
Flight.rotational_energy : Function
Rocket's rotational kinetic energy as a function of time.
Units in J.
Flight.translational_energy : Function
Rocket's translational kinetic energy as a function of time.
Units in J.
Flight.kinetic_energy : Function
Rocket's total kinetic energy as a function of time.
Units in J.
Flight.potential_energy : Function
Rocket's gravitational potential energy as a function of
time. Units in J.
Flight.total_energy : Function
Rocket's total mechanical energy as a function of time.
Units in J.
Flight.thrust_power : Function
Rocket's engine thrust power output as a function
of time in Watts.
Flight.drag_power : Function
Aerodynamic drag power output as a function
of time in Watts.
Flight.attitude_frequency_response : Function
Fourier Frequency Analysis of the rocket's attitude angle.
Expressed as the absolute value of the magnitude as a function
of frequency in Hz.
Flight.omega1_frequency_response : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 1.
Expressed as the absolute value of the magnitude as a function
of frequency in Hz.
Flight.omega2_frequency_response : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 2.
Expressed as the absolute value of the magnitude as a function
of frequency in Hz.
Flight.omega3_frequency_response : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 3.
Expressed as the absolute value of the magnitude as a function
of frequency in Hz.
Flight.static_margin : Function
Rocket's static margin during flight in calibers.
Flight.stability_margin : Function
Rocket's stability margin during flight, in calibers.
Flight.initial_stability_margin : float
Rocket's initial stability margin in calibers.
Flight.out_of_rail_stability_margin : float
Rocket's stability margin in calibers when it leaves the rail.
Flight.stream_velocity_x : Function
Freestream velocity x (East) component, in m/s, as a function of
time.
Flight.stream_velocity_y : Function
Freestream velocity y (North) component, in m/s, as a function of
time.
Flight.stream_velocity_z : Function
Freestream velocity z (up) component, in m/s, as a function of
time.
Flight.free_stream_speed : Function
Freestream velocity magnitude, in m/s, as a function of time.
Flight.apogee_freestream_speed : float
Freestream speed of the rocket at apogee in m/s.
Flight.mach_number : Function
Rocket's Mach number defined as its freestream speed
divided by the speed of sound at its altitude. Expressed
as a function of time.
Flight.max_mach_number : float
Rocket's maximum Mach number experienced during flight.
Flight.max_mach_number_time : float
Time at which the rocket experiences the maximum Mach number.
Flight.reynolds_number : Function
Rocket's Reynolds number, using its diameter as reference
length and free_stream_speed as reference velocity. Expressed
as a function of time.
Flight.max_reynolds_number : float
Rocket's maximum Reynolds number experienced during flight.
Flight.max_reynolds_number_time : float
Time at which the rocket experiences the maximum Reynolds number.
Flight.dynamic_pressure : Function
Dynamic pressure experienced by the rocket in Pa as a function
of time, defined by 0.5*rho*V^2, where rho is air density and V
is the freestream speed.
Flight.max_dynamic_pressure : float
Maximum dynamic pressure, in Pa, experienced by the rocket.
Flight.max_dynamic_pressure_time : float
Time at which the rocket experiences maximum dynamic pressure.
Flight.total_pressure : Function
Total pressure experienced by the rocket in Pa as a function
of time.
Flight.max_total_pressure : float
Maximum total pressure, in Pa, experienced by the rocket.
Flight.max_total_pressure_time : float
Time at which the rocket experiences maximum total pressure.
Flight.angle_of_attack : Function
Rocket's angle of attack in degrees as a function of time.
Defined as the minimum angle between the attitude vector and
the freestream velocity vector. Can be called or accessed as
array.
Flight.simulation_mode : str
Simulation mode for the flight. Can be "6 DOF" or "3 DOF".
Flight.rail_button1_bending_moment : Function
Internal bending moment at upper rail button attachment point in N·m
as a function of time. Calculated using beam theory during rail phase.
Flight.max_rail_button1_bending_moment : float
Maximum internal bending moment experienced at upper rail button
attachment point during rail flight phase in N·m.
Flight.rail_button2_bending_moment : Function
Internal bending moment at lower rail button attachment point in N·m
as a function of time. Calculated using beam theory during rail phase.
Flight.max_rail_button2_bending_moment : float
Maximum internal bending moment experienced at lower rail button
attachment point during rail flight phase in N·m.
"""
def __init__( # pylint: disable=too-many-arguments,too-many-statements
self,
rocket,
environment,
rail_length,
inclination=80.0,
heading=90.0,
initial_solution=None,
terminate_on_apogee=False,
max_time=600,
max_time_step=np.inf,
min_time_step=0,
rtol=1e-6,
atol=None,
time_overshoot=True,
verbose=False,
name="Flight",
equations_of_motion="standard",
ode_solver="LSODA",
simulation_mode="6 DOF",
weathercock_coeff=0.0,
):
"""Run a trajectory simulation.
Parameters
----------
rocket : Rocket
Rocket to simulate.
environment : Environment
Environment to run simulation on.
rail_length : int, float
Length in which the rocket will be attached to the rail, only
moving along a fixed direction, that is, the line parallel to the
rail. Currently, if the an initial_solution is passed, the rail
length is not used.
inclination : int, float, optional
Rail inclination angle relative to ground, given in degrees.
Default is 80.
heading : int, float, optional
Heading angle relative to north given in degrees.
Default is 90, which points in the x (east) direction.
initial_solution : array, Flight, optional
Initial solution array to be used. Format is:
.. code-block:: python
initial_solution = [
self.t_initial,
x_init, y_init, z_init,
vx_init, vy_init, vz_init,
e0_init, e1_init, e2_init, e3_init,
w1_init, w2_init, w3_init
]
If a Flight object is used, the last state vector will be
used as initial solution. If None, the initial solution will start
with all null values, except for the euler parameters which will be
calculated based on given values of inclination and heading.
Default is None.
terminate_on_apogee : boolean, optional
Whether to terminate simulation when rocket reaches apogee.
Default is False.
max_time : int, float, optional
Maximum time in which to simulate trajectory in seconds.
Using this without setting a max_time_step may cause unexpected
errors. Default is 600.
max_time_step : int, float, optional
Maximum time step to use during integration in seconds.
Default is 0.01.
min_time_step : int, float, optional
Minimum time step to use during integration in seconds.
Default is 0.01.
rtol : float, array, optional
Maximum relative error tolerance to be tolerated in the
integration scheme. Can be given as array for each
state space variable. Default is 1e-6.
atol : float, optional
Maximum absolute error tolerance to be tolerated in the
integration scheme. Can be given as array for each
state space variable. Default is 6*[1e-3] + 4*[1e-6] + 3*[1e-3].
time_overshoot : bool, optional
If True, decouples ODE time step from parachute and controller
trigger functions sampling rate. The time steps can overshoot the
necessary trigger function evaluation points and then interpolation
is used to calculate them and feed the triggers. Can greatly improve
run time in some cases. Default is True.
verbose : bool, optional
If true, verbose mode is activated. Default is False.
name : str, optional
Name of the flight. Default is "Flight".
equations_of_motion : str, optional
Type of equations of motion to use. Can be "standard" or
"solid_propulsion". Default is "standard". Solid propulsion is a
more restricted set of equations of motion that only works for
solid propulsion rockets. Such equations were used in RocketPy v0
and are kept here for backwards compatibility.
ode_solver : str, ``scipy.integrate.OdeSolver``, optional
Integration method to use to solve the equations of motion ODE.
Available options are: 'RK23', 'RK45', 'DOP853', 'Radau', 'BDF',
'LSODA' from ``scipy.integrate.solve_ivp``.
Default is 'LSODA', which is recommended for most flights.
A custom ``scipy.integrate.OdeSolver`` can be passed as well.
For more information on the integration methods, see the scipy
documentation [1]_.
weathercock_coeff : float, optional
Proportionality coefficient (rate coefficient) for the alignment rate of the rocket's body axis
with the relative wind direction in 3-DOF simulations, in rad/s. The actual angular velocity
applied to align the rocket is calculated as ``weathercock_coeff * sin(angle)``, where ``angle``
is the angle between the rocket's axis and the wind direction. A higher value means faster alignment
(quasi-static weathercocking). This parameter is only used when simulation_mode is '3 DOF'.
Default is 0.0 to mimic a pure 3-DOF simulation without any weathercocking (fixed attitude).
Set to a positive value to enable quasi-static weathercocking behaviour.
Returns
-------
None
References
----------
.. [1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html
"""
# Save arguments
self.env = environment
self.rocket = rocket
self.rail_length = rail_length
if self.rail_length <= 0: # pragma: no cover
raise ValueError("Rail length must be a positive value.")
self.parachutes = self.rocket.parachutes[:]
self.inclination = inclination
self.heading = heading
self.max_time = max_time
self.max_time_step = max_time_step
self.min_time_step = min_time_step
self.rtol = rtol
self.atol = atol or 6 * [1e-3] + 4 * [1e-6] + 3 * [1e-3]
self.initial_solution = initial_solution
self.time_overshoot = time_overshoot
self.terminate_on_apogee = terminate_on_apogee
self.name = name
self.equations_of_motion = equations_of_motion
self.simulation_mode = simulation_mode
self.ode_solver = ode_solver
self.weathercock_coeff = weathercock_coeff
# Controller initialization
self.__init_controllers()
# Flight initialization
self.__init_solution_monitors()
self.__init_equations_of_motion()
self.__init_solver_monitors()
# Create known flight phases
self.flight_phases = self.FlightPhases()
self.flight_phases.add_phase(
self.t_initial, self.initial_derivative, clear=False
)
self.flight_phases.add_phase(self.max_time)
# Simulate flight
self.__simulate(verbose)
# Initialize prints and plots objects
self.prints = _FlightPrints(self)
self.plots = _FlightPlots(self)
def __repr__(self):
return (
f"<Flight(rocket= {self.rocket}, "
f"environment= {self.env}, "
f"rail_length= {self.rail_length}, "
f"inclination= {self.inclination}, "
f"heading = {self.heading},"
f"name= {self.name})>"
)
# pylint: disable=too-many-nested-blocks, too-many-branches, too-many-locals,too-many-statements
def __simulate(self, verbose):
"""Simulate the flight trajectory."""
for phase_index, phase in self.time_iterator(self.flight_phases):
# Determine maximum time for this flight phase
phase.time_bound = self.flight_phases[phase_index + 1].t
# Evaluate callbacks
for callback in phase.callbacks:
callback(self)
# Create solver for this flight phase
self.function_evaluations.append(0)
phase.solver = self._solver(
phase.derivative,
t0=phase.t,
y0=self.y_sol,
t_bound=phase.time_bound,
rtol=self.rtol,
atol=self.atol,
max_step=self.max_time_step,
min_step=self.min_time_step,
)
# Initialize phase time nodes
self.__setup_phase_time_nodes(phase)
# Iterate through time nodes
for node_index, node in self.time_iterator(phase.time_nodes):
# Determine time bound for this time node
node.time_bound = phase.time_nodes[node_index + 1].t
phase.solver.t_bound = node.time_bound
if self.__is_lsoda:
phase.solver._lsoda_solver._integrator.rwork[0] = (
phase.solver.t_bound
)
phase.solver._lsoda_solver._integrator.call_args[4] = (
phase.solver._lsoda_solver._integrator.rwork
)
phase.solver.status = "running"
# Feed required parachute and discrete controller triggers
# TODO: parachutes should be moved to controllers
for callback in node.callbacks:
callback(self)
self.__process_sensors_and_controllers_at_current_node(node, phase)
for controller in node._controllers:
controller(
self.t,
self.y_sol,
self.solution,
self.sensors,
self.env,
)
for parachute in node.parachutes:
# Calculate and save pressure signal
(
noisy_pressure,
height_above_ground_level,
) = self.__calculate_and_save_pressure_signals(
parachute, node.t, self.y_sol[2]
)
if parachute.triggerfunc(
noisy_pressure,
height_above_ground_level,
self.y_sol,
self.sensors,
):
# Remove parachute from flight parachutes
self.parachutes.remove(parachute)
# Create phase for time after detection and before inflation
# Must only be created if parachute has any lag
i = 1
if parachute.lag != 0:
self.flight_phases.add_phase(
node.t,
phase.derivative,
clear=True,
index=phase_index + i,
)
i += 1
# Create flight phase for time after inflation
callbacks = [
lambda self, parachute_cd_s=parachute.cd_s: setattr(
self, "parachute_cd_s", parachute_cd_s
),
lambda self, parachute_radius=parachute.radius: setattr(
self, "parachute_radius", parachute_radius
),
lambda self, parachute_height=parachute.height: setattr(
self, "parachute_height", parachute_height
),
lambda self, parachute_porosity=parachute.porosity: setattr(
self, "parachute_porosity", parachute_porosity
),
lambda self,
added_mass_coefficient=parachute.added_mass_coefficient: setattr(
self,
"parachute_added_mass_coefficient",
added_mass_coefficient,
),
]
self.flight_phases.add_phase(
node.t + parachute.lag,
self.u_dot_parachute,
callbacks,
clear=False,
index=phase_index + i,
)
# Prepare to leave loops and start new flight phase
phase.time_nodes.flush_after(node_index)
phase.time_nodes.add_node(self.t, [], [], [])
phase.solver.status = "finished"
# Save parachute event
self.parachute_events.append([self.t, parachute])
if self.__check_and_handle_parachute_triggers(
node, phase, phase_index, node_index
):
break # Stop simulation if parachute is deployed
# Step through simulation
while phase.solver.status == "running":
# Execute solver step, log solution and function evaluations
phase.solver.step()
self.solution += [[phase.solver.t, *phase.solver.y]]
self.function_evaluations.append(phase.solver.nfev)
# Update time and state
self.t = phase.solver.t
self.y_sol = phase.solver.y
if verbose:
print(f"Current Simulation Time: {self.t:3.4f} s", end="\r")
if self.__check_simulation_events(phase, phase_index, node_index):
break # Stop if simulation termination event occurred
# Process overshootable time nodes if enabled
if self.time_overshoot and self.__process_overshootable_nodes(
phase, phase_index, node_index
):
break
# If controlled flight, post process must be done on sim time
# Post-process controllers if needed
if self._controllers:
phase.derivative(self.t, self.y_sol, post_processing=True)
self.t_final = self.t
self.__transform_pressure_signals_lists_to_functions()
if self._controllers:
# cache post process variables
self.__evaluate_post_process = np.array(self.__post_processed_variables)
if self.sensors:
self.__cache_sensor_data()
if verbose:
print(f"\n>>> Simulation Completed at Time: {self.t:3.4f} s")
def __setup_phase_time_nodes(self, phase):
"""Set up time nodes for the current phase.
Parameters
----------
phase : FlightPhase
The current flight phase.
"""
phase.time_nodes = self.TimeNodes()
# Add first time node
phase.time_nodes.add_node(phase.t, [], [], [])
if self.time_overshoot is False:
phase.time_nodes.add_parachutes(self.parachutes, phase.t, phase.time_bound)
phase.time_nodes.add_sensors(self.rocket.sensors, phase.t, phase.time_bound)
phase.time_nodes.add_controllers(
self._controllers, phase.t, phase.time_bound
)
# Add last time node
phase.time_nodes.add_node(phase.time_bound, [], [], [])
# Organize time nodes
phase.time_nodes.sort()
phase.time_nodes.merge()
# Clear triggers from first time node if necessary
if phase.clear:
phase.time_nodes[0].parachutes = []
phase.time_nodes[0].callbacks = []
def __process_sensors_and_controllers_at_current_node(self, node, phase):
"""Process sensors and controllers at the current node.
Parameters
----------
node : TimeNode
The current time node.
phase : FlightPhase
The current flight phase.
"""
if self.sensors:
u_dot = phase.derivative(self.t, self.y_sol)
self.__measure_sensors(node._component_sensors, u_dot)
for controller in node._controllers:
controller(
self.t,
self.y_sol,
self.solution,
self.sensors,
)
def __measure_sensors(self, component_sensors, u_dot, t=None, y_sol=None):
"""Measure sensors with the given state and derivative.
Parameters
----------
component_sensors : list
List of (sensor, position) tuples.
u_dot : array_like
State derivative vector.
t : float, optional
Time for measurement. If None, uses self.t.
y_sol : array_like, optional
State vector. If None, uses self.y_sol.
"""
if t is None:
t = self.t
if y_sol is None:
y_sol = self.y_sol
for sensor, position in component_sensors:
relative_position = position - self.rocket._csys * Vector(
[0, 0, self.rocket.center_of_dry_mass_position]
)
sensor.measure(
t,
u=y_sol,
u_dot=u_dot,
relative_position=relative_position,
environment=self.env,
gravity=self.env.gravity.get_value_opt(
y_sol[2] if len(y_sol) > 2 else self.solution[-1][3]
),
pressure=self.env.pressure,
earth_radius=self.env.earth_radius,
initial_coordinates=(self.env.latitude, self.env.longitude),
)
def __check_and_handle_parachute_triggers(
self, node, phase, phase_index, node_index
):
"""Check for parachute triggers and handle deployment.
Parameters
----------
node : TimeNode
The current time node.
phase : FlightPhase
The current flight phase.
phase_index : int
The index of the current phase.
node_index : int
The index of the current node.
Returns
-------
bool
True if a parachute was triggered and the phase should break.
"""
for parachute in node.parachutes:
# Calculate and save pressure signal
(
noisy_pressure,
height_above_ground_level,
) = self.__calculate_and_save_pressure_signals(
parachute, node.t, self.y_sol[2]
)
if not parachute.triggerfunc(
noisy_pressure,
height_above_ground_level,
self.y_sol,
self.sensors,
):
continue # Check next parachute
# Remove parachute from flight parachutes (if not already removed)
if parachute in self.parachutes:
self.parachutes.remove(parachute)
else:
continue # Parachute already triggered, skip to next
# Create phase for time after detection and before inflation
# Must only be created if parachute has any lag
i = 1
if parachute.lag != 0:
self.flight_phases.add_phase(
node.t,
phase.derivative,
clear=True,
index=phase_index + i,
)
i += 1
# Create flight phase for time after inflation
callbacks = [
lambda self, parachute_cd_s=parachute.cd_s: setattr(
self, "parachute_cd_s", parachute_cd_s
),
lambda self, parachute_radius=parachute.radius: setattr(
self, "parachute_radius", parachute_radius
),
lambda self, parachute_height=parachute.height: setattr(
self, "parachute_height", parachute_height
),
lambda self, parachute_porosity=parachute.porosity: setattr(
self, "parachute_porosity", parachute_porosity
),
lambda self,
added_mass_coefficient=parachute.added_mass_coefficient: setattr(
self,
"parachute_added_mass_coefficient",
added_mass_coefficient,
),
]
self.flight_phases.add_phase(
node.t + parachute.lag,
self.u_dot_parachute,
callbacks,
clear=False,
index=phase_index + i,
)
# Prepare to leave loops and start new flight phase