-
-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathenvironment_analysis.py
More file actions
2971 lines (2576 loc) · 107 KB
/
Copy pathenvironment_analysis.py
File metadata and controls
2971 lines (2576 loc) · 107 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
import bisect
import copy
import datetime
import json
import logging
import warnings
from collections import defaultdict
from functools import cached_property
import netCDF4
import numpy as np
import pytz
from ..mathutils.function import Function
from ..plots.environment_analysis_plots import _EnvironmentAnalysisPlots
from ..prints.environment_analysis_prints import _EnvironmentAnalysisPrints
from ..tools import (
bilinear_interpolation,
check_requirement_version,
geopotential_to_height_agl,
geopotential_to_height_asl,
import_optional_dependency,
time_num_to_date_string,
)
from ..units import convert_units
from .environment import Environment
logger = logging.getLogger(__name__)
# TODO: the average_wind_speed_profile_by_hour and similar methods could be more abstract than currently are
class EnvironmentAnalysis: # pylint: disable=too-many-public-methods
"""Class for analyzing the environment.
List of properties currently implemented:
- average max/min temperature at surface level
- record max/min temperature at surface level
- temperature progression throughout the day
- temperature profile over an average day
- average max wind gust at surface level
- record max wind gust at surface level
- average, 1, 2, 3 sigma wind profile
- average day wind rose
- animation of how average wind rose evolves throughout an average day
- animation of how wind profile evolves throughout an average day
- pressure profile over an average day
- wind velocity x profile over average day
- wind velocity y profile over average day
- wind speed profile over an average day
- average max surface 100m wind speed
- average max surface 10m wind speed
- average min surface 100m wind speed
- average min surface 10m wind speed
- average sustained surface100m wind along day
- average sustained surface10m wind along day
- maximum surface 10m wind speed
- average cloud base height
- percentage of days with no cloud coverage
- percentage of days with precipitation
You can also visualize all those attributes by exploring the methods:
- plot of wind gust distribution (should be Weibull)
- plot wind profile over average day
- plot sustained surface wind speed distribution over average day
- plot wind gust distribution over average day
- plot average day wind rose all hours
- plot average day wind rose specific hour
- plot average pressure profile
- plot average surface10m wind speed along day
- plot average sustained surface100m wind speed along day
- plot average temperature along day
- plot average wind speed profile
- plot surface10m wind speed distribution
- animate wind profile over average day
- animate sustained surface wind speed distribution over average day
- animate wind gust distribution over average day
- animate average wind rose
- animation of how the wind gust distribution evolves over average day
- all_info
All items listed are relevant to either
1. participant safety
2. launch operations (range closure decision)
3. rocket performance
How does this class work?
- The class is initialized with a start_date, end_date, start_hour and
end_hour.
- The class then parses the weather data from the start date to the end
date.
Always parsing the data from start_hour to end_hour.
- The class then calculates the average max/min temperature, average max
wind gust, and average day wind rose.
- The class then allows for plotting the average max/min temperature,
average max wind gust, and average day wind rose.
"""
def __init__( # pylint: disable=too-many-statements
self,
start_date,
end_date,
latitude,
longitude,
start_hour=0,
end_hour=24,
surface_data_file=None,
pressure_level_data_file=None,
timezone=None,
unit_system="metric",
forecast_date=None,
forecast_args=None,
max_expected_altitude=None,
):
"""Constructor for the EnvironmentAnalysis class.
Parameters
----------
start_date : datetime.datetime
Start date and time of the analysis. When parsing the weather data
from the source file, only data after this date will be parsed.
end_date : datetime.datetime
End date and time of the analysis. When parsing the weather data
from the source file, only data before this date will be parsed.
latitude : float
Latitude coordinate of the location where the analysis will be
carried out.
longitude : float
Longitude coordinate of the location where the analysis will be
carried out.
start_hour : int, optional
Starting hour of the analysis. When parsing the weather data
from the source file, only data after this hour will be parsed.
end_hour : int, optional
End hour of the analysis. When parsing the weather data
from the source file, only data before this hour will be parsed.
surface_data_file : str, optional
Path to the netCDF file containing the surface data.
pressure_level_data_file : str, optional
Path to the netCDF file containing the pressure level data.
timezone : str, optional
Name of the timezone to be used when displaying results. To see all
available time zones, import pytz and run print(pytz.all_timezones).
Default time zone is the local time zone at the latitude and
longitude specified.
unit_system : str, optional
Unit system to be used when displaying results.
Options are: SI, metric, imperial. Default is metric.
forecast_date : datetime.date, optional
Date for the forecast models. It will be requested the environment
forecast for multiple hours within that specified date.
forecast_args : dictionary, optional
Arguments for setting the forecast on the Environment class. With this argument
it is possible to change the forecast model being used.
max_expected_altitude : float, optional
Maximum expected altitude for your analysis. This is used to calculate
plot limits from pressure level data profiles. If None is set, the
maximum altitude will be calculated from the pressure level data.
Default is None.
Returns
-------
None
"""
# Save inputs
self.start_date = start_date
self.end_date = end_date
self.start_hour = start_hour
self.end_hour = end_hour
self.latitude = latitude
self.longitude = longitude
self.surface_data_file = surface_data_file
self.pressure_level_data_file = pressure_level_data_file
self.preferred_timezone = timezone
self.unit_system = unit_system
self.max_expected_altitude = max_expected_altitude
# Check if extra requirements are installed
self.__check_requirements()
# Manage units and timezones
self.__init_data_parsing_units()
self.__find_preferred_timezone()
self.__localize_input_dates()
# Convert units
self.__set_unit_system(unit_system)
# Initialize plots and prints object
self.plots = _EnvironmentAnalysisPlots(self)
self.prints = _EnvironmentAnalysisPrints(self)
# Processing forecast
self.forecast = None
if forecast_date:
self.forecast = {}
hours = list(self.original_pressure_level_data.values())[0].keys()
for hour in hours:
hour_date_time = datetime.datetime(
year=forecast_date.year,
month=forecast_date.month,
day=forecast_date.day,
hour=int(hour),
)
env = Environment(
date=hour_date_time,
latitude=self.latitude,
longitude=self.longitude,
elevation=self.converted_elevation,
)
forecast_args = forecast_args or {"type": "Forecast", "file": "GFS"}
env.set_atmospheric_model(**forecast_args)
self.forecast[hour] = env
# Private, auxiliary methods
def __check_requirements(self):
"""Check if extra requirements are installed. If not, print a message
informing the user that some methods may not work and how to install
the extra requirements for environment analysis.
Returns
-------
None
"""
env_analysis_require = { # The same as in the setup.py file
"timezonefinder": "",
"windrose": ">=1.6.8",
"IPython": "",
"ipywidgets": ">=7.6.3",
"jsonpickle": "",
}
has_error = False
for module_name, version in env_analysis_require.items():
version = ">=0" if not version else version
try:
check_requirement_version(module_name, version)
except (ValueError, ImportError) as e:
has_error = True
logger.error(
"The following error occurred while importing %s: %s",
module_name,
e,
)
if has_error:
logger.error(
"Given the above errors, some methods may not work. Please run "
"'pip install rocketpy[env_analysis]' to install extra requirements."
)
def __init_surface_dictionary(self):
# Create dictionary of file variable names to process surface data
return {
"surface100m_wind_velocity_x": "u100",
"surface100m_wind_velocity_y": "v100",
"surface10m_wind_velocity_x": "u10",
"surface10m_wind_velocity_y": "v10",
"surface_temperature": "t2m",
"cloud_base_height": "cbh",
"surface_wind_gust": "i10fg",
"surface_pressure": "sp",
"total_precipitation": "tp",
}
def __init_pressure_level_dictionary(self):
# Create dictionary of file variable names to process pressure level data
return {
"geopotential": "z",
"wind_velocity_x": "u",
"wind_velocity_y": "v",
"temperature": "t",
}
def __get_nearest_index(self, array, value):
"""Find nearest index of the given value in the array.
Made for latitudes and longitudes, supporting arrays that range from
-180 to 180 or from 0 to 360.
Parameters
----------
array : array
Array of values.
value : float
Value to be found in the array.
Returns
-------
index : int
Index of the nearest value in the array.
"""
# Create value convention
if np.min(array) < 0:
# File uses range from -180 to 180, make sure value follows convention
value = value if value < 180 else value % 180 - 180 # Example: 190 => -170
else:
# File probably uses range from 0 to 360, make sure value follows convention
value = value % 360 # Example: -10 becomes 350
# Find index
if array[0] < array[-1]:
# Array is sorted correctly, find index
# Deal with sorted array
index = bisect.bisect(array, value)
else:
# Array is reversed, no big deal, just bisect reversed one and subtract length
index = len(array) - bisect.bisect_left(array[::-1], value)
# Apply fix
if index == len(array) and array[index - 1] == value:
# If value equal the last array entry, fix to avoid being considered out of grid
index = index - 1
return index
def __extract_surface_data_value(
self, surface_data, variable, indices, lon_array, lat_array
):
"""Extract value from surface data netCDF4 file. Performs bilinear
interpolation along longitude and latitude.
Parameters
----------
surface_data : netCDF4.Dataset
Surface data netCDF4 file.
variable : str
Variable to be extracted from the file. Must be an existing variable
in the surface_data.
indices : tuple
Indices of the variable in the file. Must be given as a tuple
(time_index, lon_index, lat_index).
lon_array : array
Array of longitudes.
lat_array : array
Array of latitudes.
Returns
-------
value : float
Value of the variable at the given indices.
"""
time_index, lon_index, lat_index = indices
variable_data = surface_data[variable]
# Get values for variable on the four nearest points
z11 = variable_data[time_index, lon_index - 1, lat_index - 1]
z12 = variable_data[time_index, lon_index - 1, lat_index]
z21 = variable_data[time_index, lon_index, lat_index - 1]
z22 = variable_data[time_index, lon_index, lat_index]
# Compute interpolated value on desired lat lon pair
value = bilinear_interpolation(
x=self.longitude,
y=self.latitude,
x1=lon_array[lon_index - 1],
x2=lon_array[lon_index],
y1=lat_array[lat_index - 1],
y2=lat_array[lat_index],
z11=z11,
z12=z12,
z21=z21,
z22=z22,
)
return value
def __extract_pressure_level_data_value(
self, pressure_level_data, variable, indices, lon_array, lat_array
):
"""Extract value from surface data netCDF4 file. Performs bilinear
interpolation along longitude and latitude.
Parameters
----------
pressure_level_data : netCDF4.Dataset
Pressure level data netCDF4 file.
variable : str
Variable to be extracted from the file. Must be an existing variable
in the pressure_level_data.
indices : tuple
Indices of the variable in the file. Must be given as a tuple
(time_index, lon_index, lat_index).
lon_array : array
Array of longitudes.
lat_array : array
Array of latitudes.
Returns
-------
value : float
Value of the variable at the given indices.
"""
time_index, lon_index, lat_index = indices
variable_data = pressure_level_data[variable]
# Get values for variable on the four nearest points
z11 = variable_data[time_index, :, lon_index - 1, lat_index - 1]
z12 = variable_data[time_index, :, lon_index - 1, lat_index]
z21 = variable_data[time_index, :, lon_index, lat_index - 1]
z22 = variable_data[time_index, :, lon_index, lat_index]
# Compute interpolated value on desired lat lon pair
value_list_as_a_function_of_pressure_level = bilinear_interpolation(
x=self.longitude,
y=self.latitude,
x1=lon_array[lon_index - 1],
x2=lon_array[lon_index],
y1=lat_array[lat_index - 1],
y2=lat_array[lat_index],
z11=z11,
z12=z12,
z21=z21,
z22=z22,
)
return value_list_as_a_function_of_pressure_level
def __check_coordinates_inside_grid(
self, lon_index, lat_index, lon_array, lat_array
):
if (
lon_index == 0
or lon_index > len(lon_array) - 1
or lat_index == 0
or lat_index > len(lat_array) - 1
):
raise ValueError(
f"Latitude and longitude pair {(self.latitude, self.longitude)} "
"is outside the grid available in the given file, which "
f"is defined by {(lat_array[0], lon_array[0])} and "
f"{(lat_array[-1], lon_array[-1])}."
)
def __localize_input_dates(self):
if self.start_date.tzinfo is None:
self.start_date = self.preferred_timezone.localize(self.start_date)
if self.end_date.tzinfo is None:
self.end_date = self.preferred_timezone.localize(self.end_date)
def __find_preferred_timezone(self):
if self.preferred_timezone is None:
# Use local time zone based on lat lon pair
try:
timezonefinder = import_optional_dependency("timezonefinder")
tf = timezonefinder.TimezoneFinder()
self.preferred_timezone = pytz.timezone(
tf.timezone_at(lng=self.longitude, lat=self.latitude)
)
except ImportError:
warnings.warning( # pragma: no cover
"'timezonefinder' not installed, defaulting to UTC."
+ " Install timezonefinder to get local time zone."
+ " To do so, run 'pip install timezonefinder'"
)
self.preferred_timezone = pytz.timezone("UTC")
elif isinstance(self.preferred_timezone, str):
self.preferred_timezone = pytz.timezone(self.preferred_timezone)
def __init_data_parsing_units(self):
"""Define units for pressure level and surface data parsing"""
self.current_units = {
"height_ASL": "m",
"pressure": "hPa",
"temperature": "K",
"wind_direction": "deg",
"wind_heading": "deg",
"wind_speed": "m/s",
"wind_velocity_x": "m/s",
"wind_velocity_y": "m/s",
"surface100m_wind_velocity_x": "m/s",
"surface100m_wind_velocity_y": "m/s",
"surface10m_wind_velocity_x": "m/s",
"surface10m_wind_velocity_y": "m/s",
"surface_temperature": "K",
"cloud_base_height": "m",
"surface_wind_gust": "m/s",
"surface_pressure": "Pa",
"total_precipitation": "m",
}
# Create a variable to store updated units when units are being updated
self.updated_units = self.current_units.copy()
def __init_unit_system(self):
"""Initialize preferred units for output (SI, metric or imperial)."""
if self.unit_system_string == "metric":
self.unit_system = {
"length": "m",
"velocity": "m/s",
"acceleration": "g",
"mass": "kg",
"time": "s",
"pressure": "hPa",
"temperature": "degC",
"angle": "deg",
"precipitation": "mm",
"wind_speed": "m/s",
}
elif self.unit_system_string == "imperial":
self.unit_system = {
"length": "ft",
"velocity": "mph",
"acceleration": "ft/s^2",
"mass": "lb",
"time": "s",
"pressure": "inHg",
"temperature": "degF",
"angle": "deg",
"precipitation": "in",
"wind_speed": "mph",
}
else:
# Default to SI
logger.warning(
"Defaulting to SI unit system, the '%s' unit system was not found.",
self.unit_system_string,
)
self.unit_system = {
"length": "m",
"velocity": "m/s",
"acceleration": "m/s^2",
"mass": "kg",
"time": "s",
"pressure": "Pa",
"temperature": "K",
"angle": "rad",
"precipitation": "m",
"wind_speed": "m/s",
}
def __set_unit_system(self, unit_system="metric"):
"""Set preferred unit system for output (SI, metric or imperial). The
data with new values will be stored in ``converted_pressure_level_data``
and ``converted_surface_data`` dictionaries, while the original parsed
data will be kept in ``original_pressure_level_data`` and
``original_surface_data``. The performance of this method is not optimal
since it will loop through all the data (dates, hours and variables) and
convert the units of each variable, one by one. However, this method is
only called once.
Parameters
----------
unit_system : str, optional
The unit system to be used, by default "metric".
The options are "metric", "imperial" or "SI".
Returns
-------
None
"""
# Check if unit system is valid and define units mapping
self.unit_system_string = unit_system
self.__init_unit_system()
# Update current units
self.current_units = self.updated_units.copy()
# General properties
# pylint: disable=too-many-locals, too-many-statements
@cached_property
def __parse_pressure_level_data(self):
"""
Parse pressure level data from a weather file.
Sources of information:
- https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-era5-pressure-levels?tab=form
Must get the following variables from a ERA5 file:
- Geopotential
- U-component of wind
- V-component of wind
- Temperature
Must compute the following for each date and hour available in the dataset:
- pressure = Function(..., inputs="Height Above Ground Level (m)", outputs="Pressure (Pa)")
- temperature = Function(..., inputs="Height Above Ground Level (m)", outputs="Temperature (K)")
- wind_direction = Function(..., inputs="Height Above Ground Level (m)", outputs="Wind Direction (Deg True)")
- wind_heading = Function(..., inputs="Height Above Ground Level (m)", outputs="Wind Heading (Deg True)")
- wind_speed = Function(..., inputs="Height Above Ground Level (m)", outputs="Wind Speed (m/s)")
- wind_velocity_x = Function(..., inputs="Height Above Ground Level (m)", outputs="Wind Velocity X (m/s)")
- wind_velocity_y = Function(..., inputs="Height Above Ground Level (m)", outputs="Wind Velocity Y (m/s)")
Return a dictionary with all the computed data with the following structure:
.. code-block:: python
pressure_level_data_dict = {
"date" : {
"hour": {
"data": ...,
"data": ...
},
"hour": {
"data": ...,
"data": ...
}
},
"date" : {
"hour": {
"data": ...,
"data": ...
},
"hour": {
"data": ...,
"data": ...
}
}
}
The results will be cached, so that the parsing is only done once.
"""
dictionary = {}
# Setup dictionary used to read weather file
pressure_level_file_dict = self.__init_pressure_level_dictionary()
# Read weather file
pressure_level_data = netCDF4.Dataset(self.pressure_level_data_file)
# Get time, pressure levels, latitude and longitude data from file
time_num_array = pressure_level_data.variables["time"]
pressure_level_array = pressure_level_data.variables["level"]
lon_array = pressure_level_data.variables["longitude"]
lat_array = pressure_level_data.variables["latitude"]
# Determine latitude and longitude range for pressure level file
lat0 = lat_array[0]
lat1 = lat_array[-1]
lon0 = lon_array[0]
lon1 = lon_array[-1]
# Find index needed for latitude and longitude for specified location
lon_index = self.__get_nearest_index(lon_array, self.longitude)
lat_index = self.__get_nearest_index(lat_array, self.latitude)
# Can't handle lat and lon out of grid
self.__check_coordinates_inside_grid(lon_index, lat_index, lon_array, lat_array)
# Loop through time and save all values
for time_index, time_num in enumerate(time_num_array):
date_string, hour_string, date_time = time_num_to_date_string(
time_num,
time_num_array.units,
self.preferred_timezone,
calendar="gregorian",
)
# Check if date is within analysis range
if not self.start_date <= date_time < self.end_date:
continue
if not self.start_hour <= date_time.hour < self.end_hour:
continue
# Make sure keys exist
if date_string not in dictionary:
dictionary[date_string] = {}
if hour_string not in dictionary[date_string]:
dictionary[date_string][hour_string] = {}
# Extract data from weather file
indices = (time_index, lon_index, lat_index)
# Retrieve geopotential first and compute altitudes
geopotential_array = self.__extract_pressure_level_data_value(
pressure_level_data,
pressure_level_file_dict["geopotential"],
indices,
lon_array,
lat_array,
)
height_above_ground_level_array = geopotential_to_height_agl(
geopotential_array, self.original_elevation
)
# Loop through wind components and temperature, get value and convert to Function
for key, value in pressure_level_file_dict.items():
value_array = self.__extract_pressure_level_data_value(
pressure_level_data, value, indices, lon_array, lat_array
)
variable_points_array = np.array(
[height_above_ground_level_array, value_array]
).T
variable_function = Function(
variable_points_array,
inputs="Height Above Ground Level (m)",
outputs=key,
extrapolation="constant",
)
dictionary[date_string][hour_string][key] = variable_function
# Create function for pressure levels
pressure_points_array = np.array(
[height_above_ground_level_array, pressure_level_array]
).T
pressure_function = Function(
pressure_points_array,
inputs="Height Above Ground Level (m)",
outputs="Pressure (Pa)",
extrapolation="constant",
)
dictionary[date_string][hour_string]["pressure"] = pressure_function
# Create function for wind speed levels
wind_velocity_x_array = self.__extract_pressure_level_data_value(
pressure_level_data,
pressure_level_file_dict["wind_velocity_x"],
indices,
lon_array,
lat_array,
)
wind_velocity_y_array = self.__extract_pressure_level_data_value(
pressure_level_data,
pressure_level_file_dict["wind_velocity_y"],
indices,
lon_array,
lat_array,
)
wind_speed_array = np.sqrt(
np.square(wind_velocity_x_array) + np.square(wind_velocity_y_array)
)
wind_speed_points_array = np.array(
[height_above_ground_level_array, wind_speed_array]
).T
wind_speed_function = Function(
wind_speed_points_array,
inputs="Height Above Ground Level (m)",
outputs="Wind Speed (m/s)",
extrapolation="constant",
)
dictionary[date_string][hour_string]["wind_speed"] = wind_speed_function
# Create function for wind heading levels
wind_heading_array = (
np.arctan2(wind_velocity_x_array, wind_velocity_y_array)
* (180 / np.pi)
% 360
)
wind_heading_points_array = np.array(
[height_above_ground_level_array, wind_heading_array]
).T
wind_heading_function = Function(
wind_heading_points_array,
inputs="Height Above Ground Level (m)",
outputs="Wind Heading (Deg True)",
extrapolation="constant",
)
dictionary[date_string][hour_string]["wind_heading"] = wind_heading_function
# Create function for wind direction levels
wind_direction_array = (wind_heading_array - 180) % 360
wind_direction_points_array = np.array(
[height_above_ground_level_array, wind_direction_array]
).T
wind_direction_function = Function(
wind_direction_points_array,
inputs="Height Above Ground Level (m)",
outputs="Wind Direction (Deg True)",
extrapolation="constant",
)
dictionary[date_string][hour_string]["wind_direction"] = (
wind_direction_function
)
return (dictionary, lat0, lat1, lon0, lon1)
@property
def original_pressure_level_data(self):
"""Return the original pressure level data dictionary. Units are
defined by the units in the file.
Returns
-------
dictionary
Dictionary with the original pressure level data. This dictionary
has the following structure:
.. code-block:: python
original_pressure_level_data = {
"date" : {
"hour": {
"data": ...,
"data": ...
},
"hour": {
"data": ...,
"data": ...
}
},
"date" : {
"hour": {
...
}
}
}
"""
return self.__parse_pressure_level_data[0]
@property
def pressure_level_lat0(self):
"""Return the initial latitude of the pressure level data."""
return self.__parse_pressure_level_data[1]
@property
def pressure_level_lat1(self):
"""Return the final latitude of the pressure level data."""
return self.__parse_pressure_level_data[2]
@property
def pressure_level_lon0(self):
"""Return the initial longitude of the pressure level data."""
return self.__parse_pressure_level_data[3]
@property
def pressure_level_lon1(self):
"""Return the final longitude of the pressure level data."""
return self.__parse_pressure_level_data[4]
@cached_property
def __parse_surface_data(self): # pylint: disable=too-many-statements
"""
Parse surface data from a weather file.
Currently only supports files from ECMWF.
You can download a file from the following website:
https://cds.climate.copernicus.eu/cdsapp#!/dataset/reanalysis-era5-single-levels?tab=form
Must get the following variables:
- surface elevation: float # Select 'Geopotential'
- 2m temperature: float
- Surface pressure: float
- 10m u-component of wind: float
- 10m v-component of wind: float
- 100m u-component of wind: float
- 100m V-component of wind: float
- Instantaneous 10m wind gust: float
- Total precipitation: float
- Cloud base height: float
Return a dictionary with all the computed data with the following
structure:
.. code-block:: python
surface_data_dict = {
"date" : {
"hour": {
"data": ...,
...
},
...
},
...
}
"""
# Setup dictionary used to read weather file
dictionary = {}
surface_file_dict = self.__init_surface_dictionary()
# Read weather file
surface_data = netCDF4.Dataset(self.surface_data_file)
# Get time, latitude and longitude data from file
time_num_array = surface_data.variables["time"]
lon_array = surface_data.variables["longitude"]
lat_array = surface_data.variables["latitude"]
# Determine latitude and longitude range for surface level file
lat0 = lat_array[0]
lat1 = lat_array[-1]
lon0 = lon_array[0]
lon1 = lon_array[-1]
# Find index needed for latitude and longitude for specified location
lon_index = self.__get_nearest_index(lon_array, self.longitude)
lat_index = self.__get_nearest_index(lat_array, self.latitude)
# Can't handle lat and lon out of grid
self.__check_coordinates_inside_grid(lon_index, lat_index, lon_array, lat_array)
# Loop through time and save all values
for time_index, time_num in enumerate(time_num_array):
date_string, hour_string, date_time = time_num_to_date_string(
time_num,
time_num_array.units,
self.preferred_timezone,
calendar="gregorian",
)
# Check if date is within analysis range
if not self.start_date <= date_time < self.end_date:
continue
if not self.start_hour <= date_time.hour < self.end_hour:
continue
# Make sure keys exist
if date_string not in dictionary:
dictionary[date_string] = {}
if hour_string not in dictionary[date_string]:
dictionary[date_string][hour_string] = {}
# Extract data from weather file
indices = (time_index, lon_index, lat_index)
for key, value in surface_file_dict.items():
dictionary[date_string][hour_string][key] = (
self.__extract_surface_data_value(
surface_data, value, indices, lon_array, lat_array
)
)
# Get elevation, time index does not matter, use last one
surface_geopotential = self.__extract_surface_data_value(
surface_data, "z", indices, lon_array, lat_array
)
elevation = geopotential_to_height_asl(surface_geopotential)
return (dictionary, lat0, lat1, lon0, lon1, elevation)
@property
def original_surface_data(self):
"""Returns the surface data dictionary. Units are defined by the units
in the file.
Returns
-------
dictionary:
Dictionary with the original surface data. This dictionary has the
following structure:
.. code-block:: python
original_surface_data: {
"date" : {
"hour": {
"data": ...,
"data": ...
},
"hour": {
"data": ...,
"data": ...
}
},
"date" : {
"hour": {
...
}
}
}
"""
return self.__parse_surface_data[0]
@property
def original_elevation(self):
"""Return the elevation of the surface data."""
return self.__parse_surface_data[5]
@property
def single_level_lat0(self):
"""Return the initial latitude of the surface data."""
return self.__parse_surface_data[1]
@property
def single_level_lat1(self):
"""Return the final latitude of the surface data."""
return self.__parse_surface_data[2]
@property
def single_level_lon0(self):
"""Return the initial longitude of the surface data."""
return self.__parse_surface_data[3]
@property
def single_level_lon1(self):
"""Return the final longitude of the surface data."""
return self.__parse_surface_data[4]
@cached_property
def converted_pressure_level_data(self):
"""Convert pressure level data to desired unit system. This method will
loop through all the data (dates, hours and variables) and convert
the units of each variable. therefore, the performance of this method is
not optimal. However, this method is only called once and the results
are cached, so that the conversion is only done once.
Returns
-------
dictionary
Dictionary with the converted pressure level data. This dictionary
has the same structure as the ``original_pressure_level_data``
dictionary.
"""
# Create conversion dict (key: to_unit)
conversion_dict = {
"pressure": self.unit_system["pressure"],
"temperature": self.unit_system["temperature"],
"wind_direction": self.unit_system["angle"],
"wind_heading": self.unit_system["angle"],
"wind_speed": self.unit_system["wind_speed"],
"wind_velocity_x": self.unit_system["wind_speed"],
"wind_velocity_y": self.unit_system["wind_speed"],
}