forked from RocketPy-Team/RocketPy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnvironmentAnalysis.py
More file actions
3249 lines (2956 loc) · 129 KB
/
EnvironmentAnalysis.py
File metadata and controls
3249 lines (2956 loc) · 129 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
# -*- coding: utf-8 -*-
__author__ = "Patrick Sampaio, Giovani Hidalgo Ceotto, Guilherme Fernandes Alves, Franz Masatoshi Yuri, Mateus Stano Junqueira,"
__copyright__ = "Copyright 20XX, RocketPy Team"
__license__ = "MIT"
import bisect
import datetime
import json
import warnings
from collections import defaultdict
import ipywidgets as widgets
import jsonpickle
import matplotlib.ticker as mtick
import netCDF4
import numpy as np
import pytz
from cftime import num2pydate
from IPython.display import HTML
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.animation import PillowWriter as ImageWriter
from scipy import stats
from windrose import WindroseAxes
from rocketpy.Environment import Environment
from rocketpy.Function import Function
from rocketpy.units import convert_units
class EnvironmentAnalysis:
"""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 some of 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 who wind gust distribution evolves over average day
- allInfo
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.
Remaining TODOs:
- Make 'windSpeedLimit' a dynamic/flexible variable
"""
def __init__(
self,
start_date,
end_date,
latitude,
longitude,
start_hour=0,
end_hour=24,
surfaceDataFile=None,
pressureLevelDataFile=None,
timezone=None,
unit_system="metric",
forecast_date=None,
forecast_args=None,
maxExpectedAltitude=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.
surfaceDataFile : str, optional
Path to the netCDF file containing the surface data.
pressureLevelDataFile : 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.
maxExpectedAltitude : 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
"""
warnings.warn(
"Please notice this class is still under development, and some features may not work as expected as they were not exhaustively tested yet. In case of having any trouble, please raise an issue at https://github.com/RocketPy-Team/RocketPy/issues"
)
# 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.surfaceDataFile = surfaceDataFile
self.pressureLevelDataFile = pressureLevelDataFile
self.preferred_timezone = timezone
self.unit_system = unit_system
self.maxExpectedAltitude = maxExpectedAltitude
# Manage units and timezones
self.__init_data_parsing_units()
self.__find_preferred_timezone()
self.__localize_input_dates()
# Parse data files, surface goes first to calculate elevation
self.surfaceDataDict = {}
self.parseSurfaceData()
self.pressureLevelDataDict = {}
self.parsePressureLevelData()
# Convert units
self.set_unit_system(unit_system)
# Initialize result variables
self.average_max_temperature = 0
self.average_min_temperature = 0
self.record_max_temperature = 0
self.record_min_temperature = 0
self.average_max_wind_gust = 0
self.maximum_wind_gust = 0
self.wind_gust_distribution = None
self.average_temperature_along_day = Function(0)
self.average_wind_profile = Function(0)
self.average_wind_profile_at_given_hour = None
self.average_wind_heading_profile = Function(0)
self.average_wind_heading_profile_at_given_hour = Function(0)
self.max_wind_speed = None
self.min_wind_speed = None
self.wind_speed_per_hour = None
self.wind_direction_per_hour = None
# Run calculations
self.process_data()
# Processing forecast
self.forecast = None
if forecast_date:
self.forecast = {}
hours = list(self.pressureLevelDataDict.values())[0].keys()
for hour in hours:
hour_datetime = datetime.datetime(
year=forecast_date.year,
month=forecast_date.month,
day=forecast_date.day,
hour=int(hour),
)
Env = Environment(
railLength=5,
date=hour_datetime,
latitude=self.latitude,
longitude=self.longitude,
elevation=self.elevation,
)
forecast_args = forecast_args or {"type": "Forecast", "file": "GFS"}
Env.setAtmosphericModel(**forecast_args)
self.forecast[hour] = Env
def __bilinear_interpolation(self, x, y, x1, x2, y1, y2, z11, z12, z21, z22):
"""
Bilinear interpolation.
Source: GitHub Copilot
"""
return (
z11 * (x2 - x) * (y2 - y)
+ z21 * (x - x1) * (y2 - y)
+ z12 * (x2 - x) * (y - y1)
+ z22 * (x - x1) * (y - y1)
) / ((x2 - x1) * (y2 - y1))
def __init_surface_dictionary(self):
# Create dictionary of file variable names to process surface data
self.surfaceFileDict = {
"surface100mWindVelocityX": "u100",
"surface100mWindVelocityY": "v100",
"surface10mWindVelocityX": "u10",
"surface10mWindVelocityY": "v10",
"surfaceTemperature": "t2m",
"cloudBaseHeight": "cbh",
"surfaceWindGust": "i10fg",
"surfacePressure": "sp",
"totalPrecipitation": "tp",
}
def __init_pressure_level_dictionary(self):
# Create dictionary of file variable names to process pressure level data
self.pressureLevelFileDict = {
"geopotential": "z",
"windVelocityX": "u",
"windVelocityY": "v",
"temperature": "t",
}
def __getNearestIndex(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.
TODO: improve docs by giving one example
Parameters
----------
array : array
value : float
Returns
-------
index : int
"""
# 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 __timeNumToDateString(self, timeNum, units, calendar="gregorian"):
"""Convert time number (usually hours before a certain date) into two
strings: one for the date (example: 2022.04.31) and one for the hour
(example: 14). See cftime.num2date for details on units and calendar.
Automatically converts time number from UTC to local timezone based on
lat,lon coordinates.
"""
dateTimeUTC = num2pydate(timeNum, units, calendar=calendar)
dateTimeUTC = dateTimeUTC.replace(tzinfo=pytz.UTC)
dateTime = dateTimeUTC.astimezone(self.preferred_timezone)
dateString = f"{dateTime.year}.{dateTime.month}.{dateTime.day}"
hourString = f"{dateTime.hour}"
return dateString, hourString, dateTime
def __extractSurfaceDataValue(
self, surfaceData, variable, indices, lonArray, latArray
):
"""Extract value from surface data netCDF4 file. Performs bilinear
interpolation along longitude and latitude."""
timeIndex, lonIndex, latIndex = indices
variableData = surfaceData[variable]
# Get values for variable on the four nearest points
z11 = variableData[timeIndex, lonIndex - 1, latIndex - 1]
z12 = variableData[timeIndex, lonIndex - 1, latIndex]
z21 = variableData[timeIndex, lonIndex, latIndex - 1]
z22 = variableData[timeIndex, lonIndex, latIndex]
# Compute interpolated value on desired lat lon pair
value = self.__bilinear_interpolation(
x=self.longitude,
y=self.latitude,
x1=lonArray[lonIndex - 1],
x2=lonArray[lonIndex],
y1=latArray[latIndex - 1],
y2=latArray[latIndex],
z11=z11,
z12=z12,
z21=z21,
z22=z22,
)
return value
def __extractPressureLevelDataValue(
self, pressureLevelData, variable, indices, lonArray, latArray
):
"""Extract value from surface data netCDF4 file. Performs bilinear
interpolation along longitude and latitude."""
timeIndex, lonIndex, latIndex = indices
variableData = pressureLevelData[variable]
# Get values for variable on the four nearest points
z11 = variableData[timeIndex, :, lonIndex - 1, latIndex - 1]
z12 = variableData[timeIndex, :, lonIndex - 1, latIndex]
z21 = variableData[timeIndex, :, lonIndex, latIndex - 1]
z22 = variableData[timeIndex, :, lonIndex, latIndex]
# Compute interpolated value on desired lat lon pair
value_list_as_a_function_of_pressure_level = self.__bilinear_interpolation(
x=self.longitude,
y=self.latitude,
x1=lonArray[lonIndex - 1],
x2=lonArray[lonIndex],
y1=latArray[latIndex - 1],
y2=latArray[latIndex],
z11=z11,
z12=z12,
z21=z21,
z22=z22,
)
return value_list_as_a_function_of_pressure_level
def __compute_height_above_sea_level(self, geopotential):
"""Compute height above sea level from geopotential.
Source: https://en.wikipedia.org/wiki/Geopotential
"""
R = 63781370 # Earth radius in m
g = 9.80665 # Gravity acceleration in m/s^2
geopotential_height = geopotential / g
return R * geopotential_height / (R - geopotential_height)
def __compute_height_above_ground_level(self, geopotential, elevation):
"""Compute height above ground level from geopotential and elevation."""
return self.__compute_height_above_sea_level(geopotential) - elevation
def __check_coordinates_inside_grid(self, lonIndex, latIndex, lonArray, latArray):
if (
lonIndex == 0
or lonIndex > len(lonArray) - 1
or latIndex == 0
or latIndex > len(latArray) - 1
):
raise ValueError(
f"Latitude and longitude pair {(self.latitude, self.longitude)} is outside the grid available in the given file, which is defined by {(latArray[0], lonArray[0])} and {(latArray[-1], lonArray[-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:
try:
import timezonefinder as TimezoneFinder
except ImportError:
raise ImportError(
"The timezonefinder package is required to automatically "
+ "determine local timezone based on lat,lon coordinates. "
+ "Please specify the desired timezone using the `timezone` "
+ "argument when initializing the EnvironmentAnalysis class "
+ "or install timezonefinder with `pip install timezonefinder`."
)
# Use local timezone based on lat lon pair
tf = TimezoneFinder()
self.preferred_timezone = pytz.timezone(
tf.timezone_at(lng=self.longitude, lat=self.latitude)
)
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",
"windDirection": "deg",
"windHeading": "deg",
"windSpeed": "m/s",
"windVelocityX": "m/s",
"windVelocityY": "m/s",
"surface100mWindVelocityX": "m/s",
"surface100mWindVelocityY": "m/s",
"surface10mWindVelocityX": "m/s",
"surface10mWindVelocityY": "m/s",
"surfaceTemperature": "K",
"cloudBaseHeight": "m",
"surfaceWindGust": "m/s",
"surfacePressure": "Pa",
"totalPrecipitation": "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
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"):
self.unit_system_string = unit_system
self.__init_unit_system()
self.convertPressureLevelData()
self.convertSurfaceData()
self.current_units = self.updated_units.copy()
@staticmethod
def _find_two_closest_integer_factors(number):
"""Find the two closest integer factors of a number.
Parameters
----------
number: int
Returns
-------
list[int]
"""
number_sqrt = number**0.5
if isinstance(number_sqrt, int):
return number_sqrt, number_sqrt
else:
guess = int(number_sqrt)
while True:
if number % guess == 0:
return guess, number // guess
else:
guess -= 1
def _beaufort_wind_scale(self, units, max_wind_speed=None):
"""Returns a list of bins equivalent to the Beaufort wind scale in the
desired unit system.
Parameters
----------
units: str
Desired units for wind speed.
Options are: "knot", "mph", "m/s", "ft/s: and "km/h".
max_wind_speed: float
Maximum wind speed to be included in the scale. Should be expressed
in the same unit as the units parameter.
Returns
-------
list[float]
"""
beaufort_wind_scale_knots = np.array(
[0, 1, 3, 6, 10, 16, 21, 27, 33, 40, 47, 55, 63, 71]
)
beaufort_wind_scale = beaufort_wind_scale_knots * convert_units(
1, "knot", units
)
beaufort_wind_scale_truncated = beaufort_wind_scale[
np.where(beaufort_wind_scale <= max_wind_speed)
]
if beaufort_wind_scale[1] < 1:
return np.round(beaufort_wind_scale_truncated, 1)
else:
return np.round(beaufort_wind_scale_truncated, 0)
def parsePressureLevelData(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 Sea Level (m)", outputs="Pressure (Pa)")
- temperature = Function(..., inputs="Height Above Sea Level (m)", outputs="Temperature (K)")
- windDirection = Function(..., inputs="Height Above Sea Level (m)", outputs="Wind Direction (Deg True)")
- windHeading = Function(..., inputs="Height Above Sea Level (m)", outputs="Wind Heading (Deg True)")
- windSpeed = Function(..., inputs="Height Above Sea Level (m)", outputs="Wind Speed (m/s)")
- windVelocityX = Function(..., inputs="Height Above Sea Level (m)", outputs="Wind Velocity X (m/s)")
- windVelocityY = Function(..., inputs="Height Above Sea Level (m)", outputs="Wind Velocity Y (m/s)")
Return a dictionary with all the computed data with the following structure:
pressureLevelDataDict: {
"date" : {
"hour": {
"data": ...,
"data": ...
},
"hour": {
"data": ...,
"data": ...
}
},
"date" : {
"hour": {
"data": ...,
"data": ...
},
"hour": {
"data": ...,
"data": ...
}
}
}
"""
# Setup dictionary used to read weather file
self.__init_pressure_level_dictionary()
# Read weather file
pressureLevelData = netCDF4.Dataset(self.pressureLevelDataFile)
# Get time, pressure levels, latitude and longitude data from file
timeNumArray = pressureLevelData.variables["time"]
pressureLevelArray = pressureLevelData.variables["level"]
lonArray = pressureLevelData.variables["longitude"]
latArray = pressureLevelData.variables["latitude"]
# Determine latitude and longitude range for pressure level file
self.pressureLevelInitLat = latArray[0]
self.pressureLevelEndLat = latArray[-1]
self.pressureLevelInitLon = lonArray[0]
self.pressureLevelEndLon = lonArray[-1]
# Find index needed for latitude and longitude for specified location
lonIndex = self.__getNearestIndex(lonArray, self.longitude)
latIndex = self.__getNearestIndex(latArray, self.latitude)
# Can't handle lat and lon out of grid
self.__check_coordinates_inside_grid(lonIndex, latIndex, lonArray, latArray)
# Loop through time and save all values
for timeIndex, timeNum in enumerate(timeNumArray):
dateString, hourString, dateTime = self.__timeNumToDateString(
timeNum, timeNumArray.units, calendar="gregorian"
)
# Check if date is within analysis range
if not (self.start_date <= dateTime < self.end_date):
continue
if not (self.start_hour <= dateTime.hour < self.end_hour):
continue
# Make sure keys exist
if dateString not in self.pressureLevelDataDict:
self.pressureLevelDataDict[dateString] = {}
if hourString not in self.pressureLevelDataDict[dateString]:
self.pressureLevelDataDict[dateString][hourString] = {}
# Extract data from weather file
indices = (timeIndex, lonIndex, latIndex)
# Retrieve geopotential first and compute altitudes
geopotentialArray = self.__extractPressureLevelDataValue(
pressureLevelData,
self.pressureLevelFileDict["geopotential"],
indices,
lonArray,
latArray,
)
heightAboveSeaLevelArray = self.__compute_height_above_ground_level(
geopotentialArray, self.elevation
)
# Loop through wind components and temperature, get value and convert to Function
for key, value in self.pressureLevelFileDict.items():
valueArray = self.__extractPressureLevelDataValue(
pressureLevelData, value, indices, lonArray, latArray
)
variablePointsArray = np.array([heightAboveSeaLevelArray, valueArray]).T
variableFunction = Function(
variablePointsArray,
inputs="Height Above Ground Level (m)", # TODO: Check if it is really AGL or ASL here, see 3 lines above
outputs=key,
extrapolation="constant",
)
self.pressureLevelDataDict[dateString][hourString][
key
] = variableFunction
# Create function for pressure levels
pressurePointsArray = np.array(
[heightAboveSeaLevelArray, pressureLevelArray]
).T
pressureFunction = Function(
pressurePointsArray,
inputs="Height Above Sea Level (m)",
outputs="Pressure (Pa)",
extrapolation="constant",
)
self.pressureLevelDataDict[dateString][hourString][
"pressure"
] = pressureFunction
# Create function for wind speed levels
windVelocityXArray = self.__extractPressureLevelDataValue(
pressureLevelData,
self.pressureLevelFileDict["windVelocityX"],
indices,
lonArray,
latArray,
)
windVelocityYArray = self.__extractPressureLevelDataValue(
pressureLevelData,
self.pressureLevelFileDict["windVelocityY"],
indices,
lonArray,
latArray,
)
windSpeedArray = np.sqrt(
np.square(windVelocityXArray) + np.square(windVelocityYArray)
)
windSpeedPointsArray = np.array(
[heightAboveSeaLevelArray, windSpeedArray]
).T
windSpeedFunction = Function(
windSpeedPointsArray,
inputs="Height Above Sea Level (m)",
outputs="Wind Speed (m/s)",
extrapolation="constant",
)
self.pressureLevelDataDict[dateString][hourString][
"windSpeed"
] = windSpeedFunction
# Create function for wind heading levels
windHeadingArray = (
np.arctan2(windVelocityXArray, windVelocityYArray) * (180 / np.pi) % 360
)
windHeadingPointsArray = np.array(
[heightAboveSeaLevelArray, windHeadingArray]
).T
windHeadingFunction = Function(
windHeadingPointsArray,
inputs="Height Above Sea Level (m)",
outputs="Wind Heading (Deg True)",
extrapolation="constant",
)
self.pressureLevelDataDict[dateString][hourString][
"windHeading"
] = windHeadingFunction
# Create function for wind direction levels
windDirectionArray = (windHeadingArray - 180) % 360
windDirectionPointsArray = np.array(
[heightAboveSeaLevelArray, windDirectionArray]
).T
windDirectionFunction = Function(
windDirectionPointsArray,
inputs="Height Above Sea Level (m)",
outputs="Wind Direction (Deg True)",
extrapolation="constant",
)
self.pressureLevelDataDict[dateString][hourString][
"windDirection"
] = windDirectionFunction
return self.pressureLevelDataDict
def parseSurfaceData(self):
"""
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: self.elevation = float # Select 'Geopotential'
- 2m temperature: surfaceTemperature = float
- Surface pressure: surfacePressure = float
- 10m u-component of wind: surface10mWindVelocityX = float
- 10m v-component of wind: surface10mWindVelocityY = float
- 100m u-component of wind: surface100mWindVelocityX = float
- 100m V-component of wind: surface100mWindVelocityY = float
- Instantaneous 10m wind gust: surfaceWindGust = float
- Total precipitation: totalPrecipitation = float
- Cloud base height: cloudBaseHeight = float
Return a dictionary with all the computed data with the following structure:
surfaceDataDict: {
"date" : {
"hour": {
"data": ...,
...
},
...
},
...
}
"""
# Setup dictionary used to read weather file
self.__init_surface_dictionary()
# Read weather file
surfaceData = netCDF4.Dataset(self.surfaceDataFile)
# Get time, latitude and longitude data from file
timeNumArray = surfaceData.variables["time"]
lonArray = surfaceData.variables["longitude"]
latArray = surfaceData.variables["latitude"]
# Determine latitude and longitude range for surface level file
self.singleLevelInitLat = latArray[0]
self.singleLevelEndLat = latArray[-1]
self.singleLevelInitLon = lonArray[0]
self.singleLevelEndLon = lonArray[-1]
# Find index needed for latitude and longitude for specified location
lonIndex = self.__getNearestIndex(lonArray, self.longitude)
latIndex = self.__getNearestIndex(latArray, self.latitude)
# Can't handle lat and lon out of grid
self.__check_coordinates_inside_grid(lonIndex, latIndex, lonArray, latArray)
# Loop through time and save all values
for timeIndex, timeNum in enumerate(timeNumArray):
dateString, hourString, dateTime = self.__timeNumToDateString(
timeNum, timeNumArray.units, calendar="gregorian"
)
# Check if date is within analysis range
if not (self.start_date <= dateTime < self.end_date):
continue
if not (self.start_hour <= dateTime.hour < self.end_hour):
continue
# Make sure keys exist
if dateString not in self.surfaceDataDict:
self.surfaceDataDict[dateString] = {}
if hourString not in self.surfaceDataDict[dateString]:
self.surfaceDataDict[dateString][hourString] = {}
# Extract data from weather file
indices = (timeIndex, lonIndex, latIndex)
for key, value in self.surfaceFileDict.items():
self.surfaceDataDict[dateString][hourString][
key
] = self.__extractSurfaceDataValue(
surfaceData, value, indices, lonArray, latArray
)
# Get elevation, time index does not matter, use last one
self.surface_geopotential = self.__extractSurfaceDataValue(
surfaceData, "z", indices, lonArray, latArray
)
self.elevation = self.__compute_height_above_sea_level(
self.surface_geopotential
)
return self.surfaceDataDict
def convertPressureLevelData(self):
"""Convert pressure level data to desired unit system."""
# Create conversion dict (key: to_unit)
conversion_dict = {
"pressure": self.unit_system["pressure"],
"temperature": self.unit_system["temperature"],
"windDirection": self.unit_system["angle"],
"windHeading": self.unit_system["angle"],
"windSpeed": self.unit_system["wind_speed"],
"windVelocityX": self.unit_system["wind_speed"],
"windVelocityY": self.unit_system["wind_speed"],
}
# Loop through dates
for date in self.pressureLevelDataDict:
for hour in self.pressureLevelDataDict[date]:
for key, value in self.pressureLevelDataDict[date][hour].items():
# Skip geopotential x asl
if key not in conversion_dict:
continue
# Convert x axis
variable = convert_units(
variable=value,
from_unit=self.current_units["height_ASL"],
to_unit=self.unit_system["length"],
axis=0,
)
# Update current units
self.updated_units["height_ASL"] = self.unit_system["length"]
# Convert y axis
variable = convert_units(
variable=value,
from_unit=self.current_units[key],
to_unit=conversion_dict[key],
axis=1,
)
# Update current units
self.updated_units[key] = conversion_dict[key]
# Save converted Function
self.pressureLevelDataDict[date][hour][key] = variable
def convertSurfaceData(self):
"""Convert surface data to desired unit system."""
# Create conversion dict (key: from_unit, to_unit)
conversion_dict = {
"surface100mWindVelocityX": self.unit_system["wind_speed"],
"surface100mWindVelocityY": self.unit_system["wind_speed"],
"surface10mWindVelocityX": self.unit_system["wind_speed"],
"surface10mWindVelocityY": self.unit_system["wind_speed"],
"surfaceTemperature": self.unit_system["temperature"],
"cloudBaseHeight": self.unit_system["length"],
"surfaceWindGust": self.unit_system["wind_speed"],
"surfacePressure": self.unit_system["pressure"],
"totalPrecipitation": self.unit_system["precipitation"],
}
# Loop through dates
for date in self.surfaceDataDict:
for hour in self.surfaceDataDict[date]:
for key, value in self.surfaceDataDict[date][hour].items():
variable = convert_units(
variable=value,
from_unit=self.current_units[key],
to_unit=conversion_dict[key],
)
self.surfaceDataDict[date][hour][key] = variable
# Update current units
self.updated_units[key] = conversion_dict[key]
# Convert surface elevation
self.elevation = convert_units(
self.elevation, self.current_units["height_ASL"], self.unit_system["length"]
)
self.updated_units["height_ASL"] = self.unit_system["length"]
# Calculations
def process_data(self):
"""Process data that is shown in the allInfo method."""
self.calculate_pressure_stats()
self.calculate_average_max_temperature()
self.calculate_average_min_temperature()
self.calculate_record_max_temperature()
self.calculate_record_min_temperature()
self.calculate_average_max_wind_gust()
self.calculate_maximum_wind_gust()
self.calculate_maximum_surface_10m_wind_speed()
self.calculate_average_max_surface_10m_wind_speed()
self.calculate_average_min_surface_10m_wind_speed()
self.calculate_record_max_surface_10m_wind_speed()
self.calculate_record_min_surface_10m_wind_speed()
self.calculate_average_max_surface_100m_wind_speed()
self.calculate_average_min_surface_100m_wind_speed()
self.calculate_record_max_surface_100m_wind_speed()
self.calculate_record_min_surface_100m_wind_speed()
self.calculate_percentage_of_days_with_precipitation()
self.calculate_average_cloud_base_height()
self.calculate_min_cloud_base_height()
self.calculate_percentage_of_days_with_no_cloud_coverage()
@property
def cloud_base_height(self):
cloud_base_height = [
dayDict[hour]["cloudBaseHeight"]
for dayDict in self.surfaceDataDict.values()
for hour in dayDict.keys()
]
masked_elem = np.ma.core.MaskedConstant
unmasked_cloud_base_height = [
np.inf if isinstance(elem, masked_elem) else elem
for elem in cloud_base_height
]
mask = [isinstance(elem, masked_elem) for elem in cloud_base_height]
return np.ma.array(unmasked_cloud_base_height, mask=mask)
def calculate_pressure_stats(self):
"""Calculate pressure level statistics."""
# Surface pressure
self.surface_pressure_list = [
dayDict[hour]["surfacePressure"]
for dayDict in self.surfaceDataDict.values()
for hour in dayDict.keys()
]
self.average_surface_pressure = np.average(self.surface_pressure_list)
self.std_surface_pressure = np.std(self.surface_pressure_list)
# Pressure at 1000 feet
self.pressure_at_1000ft_list = [
dayDict[hour]["pressure"](
convert_units(1000, "ft", self.current_units["height_ASL"])
)
for dayDict in self.pressureLevelDataDict.values()
for hour in dayDict.keys()
]
self.average_pressure_at_1000ft = np.average(self.pressure_at_1000ft_list)
self.std_pressure_at_1000ft = np.std(self.pressure_at_1000ft_list)
# Pressure at 10000 feet
self.pressure_at_10000ft_list = [
dayDict[hour]["pressure"](
convert_units(10000, "ft", self.current_units["height_ASL"])
)
for dayDict in self.pressureLevelDataDict.values()
for hour in dayDict.keys()