-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathflight.py
3945 lines (3587 loc) · 164 KB
/
flight.py
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 json
import math
import warnings
from copy import deepcopy
from functools import cached_property
import numpy as np
import simplekml
from scipy.integrate import BDF, DOP853, LSODA, RK23, RK45, OdeSolver, Radau
from ..mathutils.function import Function, funcify_method
from ..mathutils.vector_matrix import Matrix, Vector
from ..plots.flight_plots import _FlightPlots
from ..prints.flight_prints import _FlightPrints
from ..tools import (
calculate_cubic_hermite_coefficients,
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 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
Rocket's X velocity as a function of time.
Flight.vy : Function
Rocket's Y velocity as a function of time.
Flight.vz : Function
Rocket's Z velocity 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
Rocket's angular velocity Omega 1 as a function of time.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.w2 : Function
Rocket's angular velocity Omega 2 as a function of time.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.w3 : Function
Rocket's angular velocity Omega 3 as a function of time.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
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 - [tInit, 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.post_processed : bool
Defines if solution data has been post processed.
Flight.initial_solution : list
List defines initial condition - [tInit, 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.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. Can be called or accessed as array.
Flight.wind_velocity_y : Function
Wind velocity Y (North) experienced by the rocket as a
function of time. Can be called or accessed as array.
Flight.density : Function
Air density experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.pressure : Function
Air pressure experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.dynamic_viscosity : Function
Air dynamic viscosity experienced by the rocket as a function of
time. Can be called or accessed as array.
Flight.speed_of_sound : Function
Speed of Sound in air experienced by the rocket as a
function of time. Can be called or accessed as array.
Flight.ax : Function
Rocket's X (East) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.ay : Function
Rocket's Y (North) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.az : Function
Rocket's Z (Up) acceleration as a function of time, in m/s².
Can be called or accessed as array.
Flight.alpha1 : Function
Rocket's angular acceleration Alpha 1 as a function of time.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Units of rad/s². Can be called or accessed as array.
Flight.alpha2 : Function
Rocket's angular acceleration Alpha 2 as a function of time.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Units of rad/s². Can be called or accessed as array.
Flight.alpha3 : Function
Rocket's angular acceleration Alpha 3 as a function of time.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Units of rad/s². Can be called or accessed as array.
Flight.speed : Function
Rocket velocity magnitude in m/s relative to ground as a
function of time. Can be called or accessed as array.
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. Can be called or
accessed as array.
Flight.acceleration : Function
Rocket acceleration magnitude in m/s² relative to ground as a
function of time. Can be called or accessed as array.
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. Can be called or accessed as array.
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.
Can be called or accessed as array.
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.
Can be called or accessed as array.
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.
Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
Flight.R1 : Function
Resultant force perpendicular to rockets axis due to
aerodynamic forces as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.R2 : Function
Resultant force perpendicular to rockets axis due to
aerodynamic forces as a function of time. Units in N.
Expressed as a function of time. Can be called or accessed
as array.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.R3 : Function
Resultant force in rockets axis due to aerodynamic forces
as a function of time. Units in N. Usually just drag.
Expressed as a function of time. Can be called or accessed
as array.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
Flight.M1 : Function
Resultant moment (torque) perpendicular to rockets axis due to
aerodynamic forces and eccentricity as a function of time.
Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 1 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry.
Flight.M2 : Function
Resultant moment (torque) perpendicular to rockets axis due to
aerodynamic forces and eccentricity as a function of time.
Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 2 is in the rocket's body axis and points perpendicular
to the rocket's axis of cylindrical symmetry and direction 1.
Flight.M3 : Function
Resultant moment (torque) in rockets axis due to aerodynamic
forces and eccentricity as a function of time. Units in N*m.
Expressed as a function of time. Can be called or accessed
as array.
Direction 3 is in the rocket's body axis and points in the
direction of cylindrical symmetry.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
Flight.drag_power : Function
Aerodynamic drag power output as a function
of time in Watts. Can be called or accessed as array.
Flight.attitude_frequency_response : Function
Fourier Frequency Analysis of the rocket's attitude angle.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega1_frequency_response : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 1.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega2_frequency_response : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 2.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
Flight.omega3_frequency_response : Function
Fourier Frequency Analysis of the rocket's angular velocity omega 3.
Expressed as the absolute vale of the magnitude as a function
of frequency in Hz. Can be called or accessed as array.
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. Can be called or accessed as array.
Flight.stream_velocity_y : Function
Freestream velocity y (North) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.stream_velocity_z : Function
Freestream velocity z (up) component, in m/s, as a function of
time. Can be called or accessed as array.
Flight.free_stream_speed : Function
Freestream velocity magnitude, in m/s, as a function of time.
Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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. Can be called or accessed as array.
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.
"""
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",
):
"""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-3.
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 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]_.
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.ode_solver = ode_solver
# 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 # TODO: allow different integrators
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
phase.time_nodes = self.TimeNodes()
# Add first time node to the time_nodes list
phase.time_nodes.add_node(phase.t, [], [], [])
# Add non-overshootable parachute time nodes
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 to the time_nodes list
phase.time_nodes.add_node(phase.time_bound, [], [], [])
# Organize time nodes with sort() and merge()
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 = []
# 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)
if self.sensors:
# u_dot for all sensors
u_dot = phase.derivative(self.t, self.y_sol)
for sensor, position in node._component_sensors:
relative_position = position - self.rocket._csys * Vector(
[0, 0, self.rocket.center_of_dry_mass_position]
)
sensor.measure(
self.t,
u=self.y_sol,
u_dot=u_dot,
relative_position=relative_position,
environment=self.env,
gravity=self.env.gravity.get_value_opt(
self.solution[-1][3]
),
pressure=self.env.pressure,
earth_radius=self.env.earth_radius,
initial_coordinates=(self.env.latitude, self.env.longitude),
)
for controller in node._controllers:
controller(
self.t,
self.y_sol,
self.solution,
self.sensors,
)
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
)
]
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])
# 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")
# Check for first out of rail event
if len(self.out_of_rail_state) == 1 and (
self.y_sol[0] ** 2
+ self.y_sol[1] ** 2
+ (self.y_sol[2] - self.env.elevation) ** 2
>= self.effective_1rl**2
):
# Check exactly when it went out using root finding
# Disconsider elevation
self.solution[-2][3] -= self.env.elevation
self.solution[-1][3] -= self.env.elevation
# Get points
y0 = (
sum(self.solution[-2][i] ** 2 for i in [1, 2, 3])
- self.effective_1rl**2
)
yp0 = 2 * sum(
self.solution[-2][i] * self.solution[-2][i + 3]
for i in [1, 2, 3]
)
t1 = self.solution[-1][0] - self.solution[-2][0]
y1 = (
sum(self.solution[-1][i] ** 2 for i in [1, 2, 3])
- self.effective_1rl**2
)
yp1 = 2 * sum(
self.solution[-1][i] * self.solution[-1][i + 3]
for i in [1, 2, 3]
)
# Put elevation back
self.solution[-2][3] += self.env.elevation
self.solution[-1][3] += self.env.elevation
# Cubic Hermite interpolation (ax**3 + bx**2 + cx + d)
a, b, c, d = calculate_cubic_hermite_coefficients(
0,
float(phase.solver.step_size),
y0,
yp0,
y1,
yp1,
)
a += 1e-5 # TODO: why??
# Find roots
t_roots = find_roots_cubic_function(a, b, c, d)
# Find correct root
valid_t_root = [
t_root.real
for t_root in t_roots
if 0 < t_root.real < t1 and abs(t_root.imag) < 0.001
]
if len(valid_t_root) > 1: # pragma: no cover
raise ValueError(
"Multiple roots found when solving for rail exit time."
)
if len(valid_t_root) == 0: # pragma: no cover
raise ValueError(
"No valid roots found when solving for rail exit time."
)
# Determine final state when upper button is going out of rail
self.t = valid_t_root[0] + self.solution[-2][0]
interpolator = phase.solver.dense_output()
self.y_sol = interpolator(self.t)
self.solution[-1] = [self.t, *self.y_sol]
self.out_of_rail_time = self.t
self.out_of_rail_time_index = len(self.solution) - 1
self.out_of_rail_state = self.y_sol
# Create new flight phase
self.flight_phases.add_phase(
self.t,
self.u_dot_generalized,
index=phase_index + 1,
)
# 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"
# Check for apogee event
# TODO: negative vz doesn't really mean apogee. Improve this.
if len(self.apogee_state) == 1 and self.y_sol[5] < 0:
# Assume linear vz(t) to detect when vz = 0
t0, vz0 = self.solution[-2][0], self.solution[-2][6]
t1, vz1 = self.solution[-1][0], self.solution[-1][6]
t_root = find_root_linear_interpolation(t0, t1, vz0, vz1, 0)
# Fetch state at t_root
interpolator = phase.solver.dense_output()
self.apogee_state = interpolator(t_root)
# Store apogee data
self.apogee_time = t_root
self.apogee_x = self.apogee_state[0]
self.apogee_y = self.apogee_state[1]
self.apogee = self.apogee_state[2]
if self.terminate_on_apogee:
self.t = self.t_final = t_root
# Roll back solution
self.solution[-1] = [self.t, *self.apogee_state]
# Set last flight phase
self.flight_phases.flush_after(phase_index)
self.flight_phases.add_phase(self.t)
# 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"
elif len(self.solution) > 2:
# adding the apogee state to solution increases accuracy
# we can only do this if the apogee is not the first state
self.solution.insert(-1, [t_root, *self.apogee_state])
# Check for impact event
if self.y_sol[2] < self.env.elevation:
# Check exactly when it happened using root finding
# Cubic Hermite interpolation (ax**3 + bx**2 + cx + d)
a, b, c, d = calculate_cubic_hermite_coefficients(
x0=0, # t0
x1=float(phase.solver.step_size), # t1 - t0
y0=float(self.solution[-2][3] - self.env.elevation), # z0
yp0=float(self.solution[-2][6]), # vz0
y1=float(self.solution[-1][3] - self.env.elevation), # z1
yp1=float(self.solution[-1][6]), # vz1
)
# Find roots
t_roots = find_roots_cubic_function(a, b, c, d)
# Find correct root
t1 = self.solution[-1][0] - self.solution[-2][0]
valid_t_root = [
t_root.real
for t_root in t_roots
if abs(t_root.imag) < 0.001 and 0 < t_root.real < t1
]
if len(valid_t_root) > 1: # pragma: no cover
raise ValueError(
"Multiple roots found when solving for impact time."
)
# Determine impact state at t_root
self.t = self.t_final = valid_t_root[0] + self.solution[-2][0]
interpolator = phase.solver.dense_output()
self.y_sol = self.impact_state = interpolator(self.t)
# Roll back solution
self.solution[-1] = [self.t, *self.y_sol]
# Save impact state
self.x_impact = self.impact_state[0]
self.y_impact = self.impact_state[1]
self.z_impact = self.impact_state[2]
self.impact_velocity = self.impact_state[5]
# Set last flight phase
self.flight_phases.flush_after(phase_index)
self.flight_phases.add_phase(self.t)
# 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"
# List and feed overshootable time nodes
if self.time_overshoot:
# Initialize phase overshootable time nodes
overshootable_nodes = self.TimeNodes()
# Add overshootable parachute time nodes
overshootable_nodes.add_parachutes(
self.parachutes, self.solution[-2][0], self.t
)
# Add last time node (always skipped)
overshootable_nodes.add_node(self.t, [], [], [])
if len(overshootable_nodes) > 1:
# Sort and merge equal overshootable time nodes
overshootable_nodes.sort()
overshootable_nodes.merge()
# Clear if necessary
if overshootable_nodes[0].t == phase.t and phase.clear:
overshootable_nodes[0].parachutes = []
overshootable_nodes[0].callbacks = []
# Feed overshootable time nodes trigger