-
-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathenvironment.py
More file actions
2865 lines (2553 loc) · 116 KB
/
environment.py
File metadata and controls
2865 lines (2553 loc) · 116 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-public-methods, too-many-instance-attributes
import bisect
import json
import re
import warnings
from collections import namedtuple
from datetime import datetime
import netCDF4
import numpy as np
import pytz
from rocketpy.environment.fetchers import (
fetch_aigfs_file_return_dataset,
fetch_atmospheric_data_from_windy,
fetch_gefs_ensemble,
fetch_gfs_file_return_dataset,
fetch_hiresw_file_return_dataset,
fetch_hrrr_file_return_dataset,
fetch_nam_file_return_dataset,
fetch_open_elevation,
fetch_rap_file_return_dataset,
fetch_wyoming_sounding,
)
from rocketpy.environment.tools import (
calculate_wind_heading,
calculate_wind_speed,
convert_wind_heading_to_direction,
find_latitude_index,
find_longitude_index,
find_time_index,
geodesic_to_lambert_conformal,
geodesic_to_utm,
get_elevation_data_from_dataset,
get_final_date_from_time_array,
get_initial_date_from_time_array,
get_interval_date_from_time_array,
get_pressure_levels_from_file,
mask_and_clean_dataset,
)
from rocketpy.environment.weather_model_mapping import WeatherModelMapping
from rocketpy.mathutils.function import NUMERICAL_TYPES, Function, funcify_method
from rocketpy.plots.environment_plots import _EnvironmentPlots
from rocketpy.prints.environment_prints import _EnvironmentPrints
from rocketpy.tools import (
bilinear_interpolation,
geopotential_height_to_geometric_height,
)
class Environment:
"""Keeps all environment information stored, such as wind and temperature
conditions, as well as gravity.
Attributes
----------
Environment.earth_radius : float
Value of Earth's Radius as 6.3781e6 m.
Environment.air_gas_constant : float
Value of Air's Gas Constant as 287.05287 J/K/Kg
Environment.gravity : Function
Gravitational acceleration. Positive values point the
acceleration down. See :meth:`Environment.set_gravity_model` for more
information.
Environment.latitude : float
Launch site latitude.
Environment.longitude : float
Launch site longitude.
Environment.datum : string
The desired reference ellipsoid model, the following options are
available: ``SAD69``, ``WGS84``, ``NAD83``, and ``SIRGAS2000``.
Environment.initial_east : float
Launch site East UTM coordinate
Environment.initial_north : float
Launch site North UTM coordinate
Environment.initial_utm_zone : int
Launch site UTM zone number
Environment.initial_utm_letter : string
Launch site UTM letter, to keep the latitude band and describe the
UTM Zone
Environment.initial_hemisphere : string
Launch site South/North hemisphere
Environment.initial_ew : string
Launch site East/West hemisphere
Environment.elevation : float
Launch site elevation.
Environment.datetime_date : datetime
Date time of launch in UTC time zone using the ``datetime`` object.
Environment.local_date : datetime
Date time of launch in the local time zone, defined by the
``Environment.timezone`` parameter.
Environment.timezone : string
Local time zone specification. See `pytz`_. for time zone information.
.. _pytz: https://pytz.sourceforge.net/
Environment.elev_lon_array : array
Unidimensional array containing the longitude coordinates.
Environment.elev_lat_array : array
Unidimensional array containing the latitude coordinates.
Environment.elev_array : array
Two-dimensional Array containing the elevation information.
Environment.topographic_profile_activated : bool
True if the user already set a topographic profile. False otherwise.
Environment.max_expected_height : float
Maximum altitude in meters to keep weather data. The altitude must be
Above Sea Level (ASL). Especially useful for controlling plots.
Can be altered as desired by running ``max_expected_height = number``.
Environment.pressure_ISA : Function
Air pressure in Pa as a function of altitude as defined by the
International Standard Atmosphere ISO 2533.
Environment.temperature_ISA : Function
Air temperature in K as a function of altitude as defined by the
International Standard Atmosphere ISO 2533
Environment.pressure : Function
Air pressure in Pa as a function of altitude.
Environment.barometric_height : Function
Geometric height above sea level in m as a function of pressure.
Environment.temperature : Function
Air temperature in K as a function of altitude.
Environment.speed_of_sound : Function
Speed of sound in air in m/s as a function of altitude.
Environment.density : Function
Air density in kg/m³ as a function of altitude.
Environment.dynamic_viscosity : Function
Air dynamic viscosity in Pa*s as a function of altitude.
Environment.wind_speed : Function
Wind speed in m/s as a function of altitude.
Environment.wind_direction : Function
Wind direction (from which the wind blows) in degrees relative to north
(positive clockwise) as a function of altitude.
Environment.wind_heading : Function
Wind heading (direction towards which the wind blows) in degrees
relative to north (positive clockwise) as a function of altitude.
Environment.wind_velocity_x : Function
Wind U, or X (east) component of wind velocity in m/s as a function of
altitude.
Environment.wind_velocity_y : Function
Wind V, or Y (north) component of wind velocity in m/s as a function of
altitude.
Environment.atmospheric_model_type : string
Describes the atmospheric model which is being used. Can only assume the
following values: ``standard_atmosphere``, ``custom_atmosphere``,
``wyoming_sounding``, ``windy``, ``forecast``, ``reanalysis``,
``ensemble``.
Environment.atmospheric_model_file : string
Address of the file used for the atmospheric model being used. Only
defined for ``wyoming_sounding``, ``windy``, ``forecast``,
``reanalysis``, ``ensemble``
Environment.atmospheric_model_dict : dictionary
Dictionary used to properly interpret ``netCDF`` and ``OPeNDAP`` files.
Only defined for ``forecast``, ``reanalysis``, ``ensemble``.
Environment.atmospheric_model_init_date : datetime
Datetime object instance of first available date in ``netCDF``
and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.atmospheric_model_end_date : datetime
Datetime object instance of last available date in ``netCDF`` and
``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.atmospheric_model_interval : int
Hour step between weather condition used in ``netCDF`` and
``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.atmospheric_model_init_lat : float
Latitude of vertex just before the launch site in ``netCDF``
and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.atmospheric_model_end_lat : float
Latitude of vertex just after the launch site in ``netCDF``
and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.atmospheric_model_init_lon : float
Longitude of vertex just before the launch site in ``netCDF``
and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.atmospheric_model_end_lon : float
Longitude of vertex just after the launch site in ``netCDF``
and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or
``Ensemble``.
Environment.lat_array : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. Two-element list ``[x1, x2]`` containing
the latitude coordinates of the grid-cell vertices that bracket the
launch site and are used in bilinear interpolation.
Environment.lon_array : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. Two-element list ``[y1, y2]`` containing
the longitude coordinates of the grid-cell vertices that bracket the
launch site and are used in bilinear interpolation.
Environment.lon_index : int
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. Index to a grid longitude which
is just over the launch site longitude, while ``lon_index`` - 1
points to a grid longitude which is just under the launch
site longitude.
Environment.lat_index : int
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. Index to a grid latitude which
is just over the launch site latitude, while ``lat_index`` - 1
points to a grid latitude which is just under the launch
site latitude.
Environment.geopotentials : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. 2x2 matrix for each pressure level of
geopotential heights corresponding to the vertices of the grid cell
which surrounds the launch site.
Environment.wind_us : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. 2x2 matrix for each pressure level of
wind U (east) component corresponding to the vertices of the grid
cell which surrounds the launch site.
Environment.wind_vs : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. 2x2 matrix for each pressure level of
wind V (north) component corresponding to the vertices of the grid
cell which surrounds the launch site.
Environment.levels : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. List of pressure levels available in the file.
Environment.temperatures : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. 2x2 matrix for each pressure level of
temperatures corresponding to the vertices of the grid cell which
surrounds the launch site.
Environment.time_array : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. Two-element list with the first and last
values from the dataset time variable in the dataset native units.
Environment.height : array
Defined if ``netCDF`` or ``OPeNDAP`` file is used, for Forecasts,
Reanalysis and Ensembles. List of geometric height corresponding to
launch site location.
Environment.level_ensemble : array
Only defined when using Ensembles.
Environment.height_ensemble : array
Only defined when using Ensembles.
Environment.temperature_ensemble : array
Only defined when using Ensembles.
Environment.wind_u_ensemble : array
Only defined when using Ensembles.
Environment.wind_v_ensemble : array
Only defined when using Ensembles.
Environment.wind_heading_ensemble : array
Only defined when using Ensembles.
Environment.wind_direction_ensemble : array
Only defined when using Ensembles.
Environment.wind_speed_ensemble : array
Only defined when using Ensembles.
Environment.num_ensemble_members : int
Number of ensemble members. Only defined when using Ensembles.
Environment.ensemble_member : int
Current selected ensemble member. Only defined when using Ensembles.
Environment.earth_rotation_vector : list[float]
Earth's angular velocity vector in the Flight Coordinate System.
Notes
-----
All the attributes listed as Function objects can be accessed as
regular arrays, or called as a Function. See :class:`rocketpy.Function`
for more information.
"""
def __init__(
self,
gravity=None,
date=None,
latitude=0.0,
longitude=0.0,
elevation=0.0,
datum="SIRGAS2000",
timezone="UTC",
max_expected_height=80000.0,
):
"""Initializes the Environment class, capturing essential parameters of
the launch site, including the launch date, geographical coordinates,
and elevation. This class is designed to calculate crucial variables
for the Flight simulation, such as atmospheric air pressure, density,
and gravitational acceleration.
Note that the default atmospheric model is the International Standard
Atmosphere as defined by ISO 2533 unless specified otherwise in
:meth:`Environment.set_atmospheric_model`.
Parameters
----------
gravity : int, float, callable, string, array, optional
Surface gravitational acceleration. Positive values point the
acceleration down. If None, the Somigliana formula is used.
See :meth:`Environment.set_gravity_model` for more information.
date : list or tuple, optional
List or tuple of length 4, stating (year, month, day, hour) in the
time zone of the parameter ``timezone``.
Alternatively, can be a ``datetime`` object specifying launch
date and time. The dates are stored as follows:
- :attr:`Environment.local_date`: Local time of launch in
the time zone specified by the parameter ``timezone``.
- :attr:`Environment.datetime_date`: UTC time of launch.
Must be given if a ``windy``, ``forecast``, ``reanalysis``
or ``ensemble`` atmospheric model will be used.
Default is None.
See :meth:`Environment.set_date` for more information.
latitude : float, optional
Latitude in degrees (ranging from -90 to 90) of rocket
launch location. Must be given if a ``windy``, ``forecast``,
``reanalysis`` or ``ensemble`` atmospheric model will be used or if
Open-Elevation will be used to compute elevation. Positive
values correspond to the North. Default value is 0, which
corresponds to the equator.
longitude : float, optional
Longitude in degrees (ranging from -180 to 180) of rocket
launch location. Must be given if a ``windy``, ``forecast``,
``reanalysis`` or ``ensemble`` atmospheric model will be used or if
Open-Elevation will be used to compute elevation. Positive
values correspond to the East. Default value is 0, which
corresponds to the Greenwich Meridian.
elevation : float, optional
Elevation of launch site measured as height above sea
level in meters. Alternatively, can be set as
``Open-Elevation`` which uses the Open-Elevation API to
find elevation data. For this option, latitude and
longitude must also be specified. Default value is 0.
datum : string, optional
The desired reference ellipsoidal model, the following options are
available: "SAD69", "WGS84", "NAD83", and "SIRGAS2000". The default
is "SIRGAS2000".
timezone : string, optional
Name of the time zone. To see all time zones, import pytz and run
``print(pytz.all_timezones)``. Default time zone is "UTC".
max_expected_height : float, optional
Maximum altitude in meters to keep weather data. The altitude must
be above sea level (ASL). Especially useful for visualization. Can
be altered as desired by running ``max_expected_height = number``.
Depending on the atmospheric model, this value may be automatically
modified.
Returns
-------
None
"""
# Initialize constants and atmospheric variables
self.__initialize_empty_variables()
self.__initialize_constants()
self.__initialize_elevation_and_max_height(elevation, max_expected_height)
# Initialize plots and prints objects
self.prints = _EnvironmentPrints(self)
self.plots = _EnvironmentPlots(self)
# Set the atmosphere model to the standard atmosphere
self.set_atmospheric_model("standard_atmosphere")
# Initialize date, latitude, longitude, and Earth geometry
self.__initialize_date(date, timezone)
self.set_location(latitude, longitude)
self.__initialize_earth_geometry(datum)
self.__initialize_utm_coordinates()
self.__set_earth_rotation_vector()
# Set the gravity model
self.gravity = self.set_gravity_model(gravity)
def __initialize_constants(self):
"""Sets some important constants and atmospheric variables."""
self.earth_radius = 6.3781 * (10**6)
self.air_gas_constant = 287.05287 # in J/K/kg
self.standard_g = 9.80665
self.__weather_model_map = WeatherModelMapping()
self.__atm_type_file_to_function_map = {
"forecast": {
"AIGFS": fetch_aigfs_file_return_dataset,
"GFS": fetch_gfs_file_return_dataset,
"NAM": fetch_nam_file_return_dataset,
"RAP": fetch_rap_file_return_dataset,
"HRRR": fetch_hrrr_file_return_dataset,
"HIRESW": fetch_hiresw_file_return_dataset,
},
"ensemble": {
"GEFS": fetch_gefs_ensemble,
},
}
self.__standard_atmosphere_layers = {
"geopotential_height": [ # in geopotential m
-2e3,
0,
11e3,
20e3,
32e3,
47e3,
51e3,
71e3,
80e3,
],
"temperature": [ # in K
301.15,
288.15,
216.65,
216.65,
228.65,
270.65,
270.65,
214.65,
196.65,
],
"beta": [-6.5e-3, -6.5e-3, 0, 1e-3, 2.8e-3, 0, -2.8e-3, -2e-3, 0], # in K/m
"pressure": [ # in Pa
1.27774e5,
1.01325e5,
2.26320e4,
5.47487e3,
8.680164e2,
1.10906e2,
6.69384e1,
3.95639e0,
8.86272e-2,
],
}
def __initialize_empty_variables(self):
self.atmospheric_model_file = str()
self.atmospheric_model_dict = {}
def __initialize_elevation_and_max_height(self, elevation, max_expected_height):
"""Saves the elevation and the maximum expected height."""
self.elevation = elevation
self.set_elevation(elevation)
self._max_expected_height = max_expected_height
def __initialize_date(self, date, timezone):
"""Saves the date and configure timezone."""
if date is not None:
self.set_date(date, timezone)
else:
self.date = None
self.datetime_date = None
self.local_date = None
self.timezone = None
def __initialize_earth_geometry(self, datum):
"""Initialize Earth geometry, save datum and Recalculate Earth Radius"""
self.datum = datum
self.ellipsoid = self.set_earth_geometry(datum)
self.earth_radius = self.calculate_earth_radius(
lat=self.latitude,
semi_major_axis=self.ellipsoid.semi_major_axis,
flattening=self.ellipsoid.flattening,
)
def __initialize_utm_coordinates(self):
"""Store launch site coordinates referenced to UTM projection system."""
if -80 < self.latitude < 84:
(
self.initial_east,
self.initial_north,
self.initial_utm_zone,
self.initial_utm_letter,
self.initial_hemisphere,
self.initial_ew,
) = geodesic_to_utm(
lat=self.latitude,
lon=self.longitude,
flattening=self.ellipsoid.flattening,
semi_major_axis=self.ellipsoid.semi_major_axis,
)
else: # pragma: no cover
warnings.warn(
"UTM coordinates are not available for latitudes "
"above 84 or below -80 degrees. The UTM conversions will fail."
)
self.initial_north = None
self.initial_east = None
self.initial_utm_zone = None
self.initial_utm_letter = None
self.initial_hemisphere = None
self.initial_ew = None
# Auxiliary private setters.
def __set_pressure_function(self, source):
self.pressure = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Pressure (Pa)",
interpolation="linear",
)
def __set_barometric_height_function(self, source):
self.barometric_height = Function(
source,
inputs="Pressure (Pa)",
outputs="Height Above Sea Level (m)",
interpolation="linear",
extrapolation="natural",
)
if callable(self.barometric_height.source):
# discretize to speed up flight simulation
self.barometric_height.set_discrete(
0,
self.max_expected_height,
100,
extrapolation="constant",
mutate_self=True,
)
def __set_temperature_function(self, source):
self.temperature = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Temperature (K)",
interpolation="linear",
)
def __set_wind_velocity_x_function(self, source):
self.wind_velocity_x = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Wind Velocity X (m/s)",
interpolation="linear",
)
def __set_wind_velocity_y_function(self, source):
self.wind_velocity_y = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Wind Velocity Y (m/s)",
interpolation="linear",
)
def __set_wind_speed_function(self, source):
self.wind_speed = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Wind Speed (m/s)",
interpolation="linear",
)
def __set_wind_direction_function(self, source):
self.wind_direction = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Wind Direction (Deg True)",
interpolation="linear",
)
def __set_wind_heading_function(self, source):
self.wind_heading = Function(
source,
inputs="Height Above Sea Level (m)",
outputs="Wind Heading (Deg True)",
interpolation="linear",
)
def __reset_barometric_height_function(self):
# NOTE: this assumes self.pressure and max_expected_height are already set.
self.barometric_height = self.pressure.inverse_function()
if callable(self.barometric_height.source):
# discretize to speed up flight simulation
self.barometric_height.set_discrete(
0,
self.max_expected_height,
100,
extrapolation="constant",
mutate_self=True,
)
self.barometric_height.set_inputs("Pressure (Pa)")
self.barometric_height.set_outputs("Height Above Sea Level (m)")
def __reset_wind_speed_function(self):
# NOTE: assume wind_velocity_x and wind_velocity_y as Function objects
self.wind_speed = (self.wind_velocity_x**2 + self.wind_velocity_y**2) ** 0.5
self.wind_speed.set_inputs("Height Above Sea Level (m)")
self.wind_speed.set_outputs("Wind Speed (m/s)")
self.wind_speed.set_title("Wind Speed Profile")
# commented because I never finished, leave it for future implementation
# def __reset_wind_heading_function(self):
# NOTE: this assumes wind_u and wind_v as numpy arrays with same length.
# TODO: should we implement arctan2 in the Function class?
# self.wind_heading = calculate_wind_heading(
# self.wind_velocity_x, self.wind_velocity_y
# )
# self.wind_heading.set_inputs("Height Above Sea Level (m)")
# self.wind_heading.set_outputs("Wind Heading (Deg True)")
# self.wind_heading.set_title("Wind Heading Profile")
def __reset_wind_direction_function(self):
self.wind_direction = convert_wind_heading_to_direction(self.wind_heading)
self.wind_direction.set_inputs("Height Above Sea Level (m)")
self.wind_direction.set_outputs("Wind Direction (Deg True)")
self.wind_direction.set_title("Wind Direction Profile")
def __set_earth_rotation_vector(self):
"""Calculates and stores the Earth's angular velocity vector in the Flight
Coordinate System, which is essential for evaluating inertial forces.
"""
# Sidereal day
T = 86164.1 # seconds
# Earth's angular velocity magnitude
w_earth = 2 * np.pi / T
# Vector in the Flight Coordinate System
lat = np.radians(self.latitude)
w_local = [0, w_earth * np.cos(lat), w_earth * np.sin(lat)]
# Store the attribute
self.earth_rotation_vector = w_local
# Validators (used to verify an attribute is being set correctly.)
@staticmethod
def __dictionary_matches_dataset(dictionary, dataset):
"""Check whether a mapping dictionary is compatible with a dataset."""
variables = dataset.variables
required_keys = (
"time",
"latitude",
"longitude",
"level",
"temperature",
"u_wind",
"v_wind",
)
for key in required_keys:
variable_name = dictionary.get(key)
if variable_name is None or variable_name not in variables:
return False
projection_name = dictionary.get("projection")
if projection_name is not None and projection_name not in variables:
return False
geopotential_height_name = dictionary.get("geopotential_height")
geopotential_name = dictionary.get("geopotential")
has_geopotential_height = (
geopotential_height_name is not None
and geopotential_height_name in variables
)
has_geopotential = (
geopotential_name is not None and geopotential_name in variables
)
return has_geopotential_height or has_geopotential
def __resolve_dictionary_for_dataset(self, dictionary, dataset):
"""Resolve a compatible mapping dictionary for the loaded dataset.
If the provided mapping is incompatible with the dataset variables,
this method tries built-in mappings and falls back to the first
compatible one.
"""
if self.__dictionary_matches_dataset(dictionary, dataset):
return dictionary
for model_name, candidate in self.__weather_model_map.all_dictionaries.items():
if self.__dictionary_matches_dataset(candidate, dataset):
warnings.warn(
"Provided weather mapping does not match dataset variables. "
f"Falling back to built-in mapping '{model_name}'."
)
return candidate
return dictionary
def __validate_dictionary(self, file, dictionary):
# removed CMC until it is fixed.
available_models = [
"AIGFS",
"GFS",
"NAM",
"RAP",
"HRRR",
"HIRESW",
"GEFS",
"ERA5",
"MERRA2",
]
if isinstance(dictionary, str):
dictionary = self.__weather_model_map.get(dictionary)
elif isinstance(file, str):
matching_model = next(
(model for model in available_models if model.lower() == file.lower()),
None,
)
if matching_model is not None:
dictionary = self.__weather_model_map.get(matching_model)
if not isinstance(dictionary, dict):
raise TypeError(
"Please specify a dictionary or choose a valid model from the "
f"following list: {available_models}"
)
return dictionary
def __validate_datetime(self):
if self.datetime_date is None:
raise ValueError(
"Please specify the launch date and time using the "
"Environment.set_date() method."
)
# Define setters
def set_date(self, date, timezone="UTC"):
"""Set date and time of launch and update weather conditions if
date dependent atmospheric model is used.
Parameters
----------
date : list, tuple, datetime
List or tuple of length 4, stating (year, month, day, hour) in the
time zone of the parameter ``timezone``. See Notes for more
information. Alternatively, can be a ``datetime`` object specifying
launch date and time.
timezone : string, optional
Name of the time zone. To see all time zones, import pytz and run
``print(pytz.all_timezones)``. Default time zone is "UTC".
Returns
-------
None
Notes
-----
- If the ``date`` is given as a list or tuple, it should be in the same
time zone as specified by the ``timezone`` parameter. This local
time will be available in the attribute :attr:`Environment.local_date`
while the UTC time will be available in the attribute
:attr:`Environment.datetime_date`.
- If the ``date`` is given as a ``datetime`` object without a time zone,
it will be assumed to be in the same time zone as specified by the
``timezone`` parameter. However, if the ``datetime`` object has a time
zone specified in its ``tzinfo`` attribute, the ``timezone``
parameter will be ignored.
Examples
--------
Let's set the launch date as an list:
>>> date = [2000, 1, 1, 13] # January 1st, 2000 at 13:00 UTC+1
>>> env = Environment()
>>> env.set_date(date, timezone="Europe/Rome")
>>> print(env.datetime_date) # Get UTC time
2000-01-01 12:00:00+00:00
>>> print(env.local_date)
2000-01-01 13:00:00+01:00
Now let's set the launch date as a ``datetime`` object:
>>> from datetime import datetime
>>> date = datetime(2000, 1, 1, 13, 0, 0)
>>> env = Environment()
>>> env.set_date(date, timezone="Europe/Rome")
>>> print(env.datetime_date) # Get UTC time
2000-01-01 12:00:00+00:00
>>> print(env.local_date)
2000-01-01 13:00:00+01:00
"""
# Store date and configure time zone
self.timezone = timezone
tz = pytz.timezone(self.timezone)
if not isinstance(date, datetime):
local_date = datetime(*date)
else:
local_date = date
if local_date.tzinfo is None:
local_date = tz.localize(local_date)
self.date = date
self.local_date = local_date
self.datetime_date = self.local_date.astimezone(pytz.UTC)
# Update atmospheric conditions if atmosphere type is Forecast,
# Reanalysis or Ensemble
if hasattr(self, "atmospheric_model_type") and self.atmospheric_model_type in [
"Forecast",
"Reanalysis",
"Ensemble",
]:
self.set_atmospheric_model(
type=self.atmospheric_model_type,
file=self.atmospheric_model_file,
dictionary=self.atmospheric_model_dict,
)
def set_location(self, latitude, longitude):
"""Set latitude and longitude of launch and update atmospheric
conditions if location dependent model is being used.
Parameters
----------
latitude : float
Latitude of launch site. May range from -90 to 90 degrees.
longitude : float
Longitude of launch site. Either from 0 to 360 degrees or from -180
to 180 degrees.
Returns
-------
None
"""
if not isinstance(latitude, NUMERICAL_TYPES) and isinstance(
longitude, NUMERICAL_TYPES
): # pragma: no cover
raise TypeError("Latitude and Longitude must be numbers!")
# Store latitude and longitude
self.latitude = latitude
self.longitude = longitude
# Update atmospheric conditions if atmosphere type is Forecast,
# Reanalysis or Ensemble
if hasattr(self, "atmospheric_model_type") and self.atmospheric_model_type in [
"Forecast",
"Reanalysis",
"Ensemble",
]:
self.set_atmospheric_model(
type=self.atmospheric_model_type,
file=self.atmospheric_model_file,
dictionary=self.atmospheric_model_dict,
)
def set_gravity_model(self, gravity=None):
"""Defines the gravity model based on the given user input to the
gravity parameter. The gravity model is responsible for computing the
gravity acceleration at a given height above sea level in meters.
Parameters
----------
gravity : int, float, callable, string, list, optional
The gravitational acceleration in m/s² to be used in the
simulation, this value is positive when pointing downwards.
The input type can be one of the following:
- ``int`` or ``float``: The gravity acceleration is set as a\
constant function with respect to height;
- ``callable``: This callable should receive the height above\
sea level in meters and return the gravity acceleration;
- ``list``: The datapoints should be structured as\
``[(h_i,g_i), ...]`` where ``h_i`` is the height above sea\
level in meters and ``g_i`` is the gravity acceleration in m/s²;
- ``string``: The string should correspond to a path to a CSV file\
containing the gravity acceleration data;
- ``None``: The Somigliana formula is used to compute the gravity\
acceleration.
This parameter is used as a :class:`Function` object source, check\
out the available input types for a more detailed explanation.
Returns
-------
Function
Function object representing the gravity model.
Notes
-----
This method **does not** set the gravity acceleration, it only returns
a :class:`Function` object representing the gravity model.
Examples
--------
Let's prepare a `Environment` object with a constant gravity
acceleration:
>>> g_0 = 9.80665
>>> env_cte_g = Environment(gravity=g_0)
>>> env_cte_g.gravity([0, 100, 1000])
[np.float64(9.80665), np.float64(9.80665), np.float64(9.80665)]
It's also possible to variate the gravity acceleration by defining
its function of height:
>>> R_t = 6371000
>>> g_func = lambda h : g_0 * (R_t / (R_t + h))**2
>>> env_var_g = Environment(gravity=g_func)
>>> g = env_var_g.gravity(1000)
>>> print(f"{g:.6f}")
9.803572
"""
if gravity is None:
return self.somigliana_gravity.set_discrete(
0, self.max_expected_height, 100
)
else:
return Function(gravity, "height (m)", "gravity (m/s²)").set_discrete(
0, self.max_expected_height, 100
)
@property
def max_expected_height(self):
return self._max_expected_height
@max_expected_height.setter
def max_expected_height(self, value):
if value < self.elevation: # pragma: no cover
raise ValueError(
"Max expected height cannot be lower than the surface elevation"
)
self._max_expected_height = value
self.plots.grid = np.linspace(self.elevation, self.max_expected_height)
@funcify_method("height (m)", "gravity (m/s²)")
def somigliana_gravity(self, height):
"""Computes the gravity acceleration with the Somigliana formula [1]_.
An height correction is applied to the normal gravity that is
accurate for heights used in aviation. The formula is based on the
WGS84 ellipsoid, but is accurate for other reference ellipsoids.
Parameters
----------
height : float
Height above the reference ellipsoid in meters.
Returns
-------
Function
Function object representing the gravity model.
References
----------
.. [1] https://en.wikipedia.org/wiki/Theoretical_gravity#Somigliana_equation
"""
a = 6378137.0 # semi_major_axis
f = 1 / 298.257223563 # flattening_factor
m_rot = 3.449786506841e-3 # rotation_factor
g_e = 9.7803253359 # normal gravity at equator
k_somgl = 1.931852652458e-3 # normal gravity formula const.
first_ecc_sqrd = 6.694379990141e-3 # square of first eccentricity
# Compute quantities
sin_lat_sqrd = (np.sin(self.latitude * np.pi / 180)) ** 2
gravity_somgl = g_e * (
(1 + k_somgl * sin_lat_sqrd) / (np.sqrt(1 - first_ecc_sqrd * sin_lat_sqrd))
)
height_correction = (
1
- height * 2 / a * (1 + f + m_rot - 2 * f * sin_lat_sqrd)
+ 3 * height**2 / a**2
)
return height_correction * gravity_somgl
def set_elevation(self, elevation="Open-Elevation"):
"""Set elevation of launch site given user input or using the
Open-Elevation API.
Parameters
----------
elevation : float, string, optional
Elevation of launch site measured as height above sea level in
meters. Alternatively, can be set as ``Open-Elevation`` which uses
the Open-Elevation API to find elevation data. For this option,
latitude and longitude must have already been specified.
See Also
--------
:meth:`rocketpy.Environment.set_location`
Returns
-------
None
"""
if elevation not in ["Open-Elevation", "SRTM"]:
# NOTE: this is assuming the elevation is a number (i.e. float, int, etc.)
self.elevation = elevation
else:
self.elevation = fetch_open_elevation(self.latitude, self.longitude)
print(f"Elevation received: {self.elevation} m")
def set_topographic_profile( # pylint: disable=redefined-builtin, unused-argument
self, type, file, dictionary="netCDF4", crs=None
):
"""[UNDER CONSTRUCTION] Defines the Topographic profile, importing data
from previous downloaded files. Mainly data from the Shuttle Radar
Topography Mission (SRTM) and NASA Digital Elevation Model will be used
but other models and methods can be implemented in the future.
So far, this function can only handle data from NASADEM, available at:
https://cmr.earthdata.nasa.gov/search/concepts/C1546314436-LPDAAC_ECS.html
Parameters
----------
type : string
Defines the topographic model to be used, usually 'NASADEM Merged
DEM Global 1 arc second nc' can be used. To download this kind of
data, access 'https://search.earthdata.nasa.gov/search'.
NASADEM data products were derived from original telemetry data from
the Shuttle Radar Topography Mission (SRTM).
file : string