-
Notifications
You must be signed in to change notification settings - Fork 3
/
climatefiller.py
1843 lines (1513 loc) · 99.3 KB
/
climatefiller.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from data_science_toolkit.dataframe import DataFrame
import datetime
import os
from datetime import timedelta
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.neighbors import LocalOutlierFactor
from sklearn.ensemble import IsolationForest
from lib import Lib
import ee
import geemap
import re
import requests
from sklearn.metrics import mean_squared_error, r2_score
from xgboost import XGBRegressor
from catboost import CatBoostRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet
from sklearn.model_selection import KFold
class ClimateFiller():
"""The ClimateFiller class
"""
def __init__(self, data_link=None, data_type='csv', datetime_column_name='datetime',
datetime_format='%Y-%m-%d %H:%M:%S', backend='gee',
lat=31.65410805, lon=-7.603140831, tz_offset=-7, elevation=None, **kwargs):
"""
Initializes an instance of the class with the specified parameters.
Args:
self (object): The instance of the class.
data_link (str or None): A string representing the link or path to the data source. Defaults to None.
data_type (str): The type of the data source. Defaults to 'csv'.
datetime_column_name (str): The name of the column that contains datetime information. Defaults to 'datetime'.
date_time_format (str): The format of the datetime values in the data source. Defaults to '%Y-%m-%d %H:%M:%S'.
tz_offset (int): The time zone offset in hours comparint to GMT. Defaults to -7.
Returns:
None
Notes:
- The initialization of the class instance allows for handling and processing of the data.
- The data_link parameter specifies the location of the data source, which can be a link or a local path.
- The data_type parameter indicates the format or type of the data source, with 'csv' as the default value.
- The datetime_column_name parameter identifies the column in the data source that contains datetime information.
- The date_time_format parameter defines the format of the datetime values in the data source.
- If data_link is not provided, the instance will be initialized without any data source.
"""
self.datetime_column_name = datetime_column_name
self.lat = lat
self.lon = lon
self.tz_offset = tz_offset
self.elevation = elevation
self.backend = backend
self.et0_output_data = DataFrame()
if backend == 'gee':
ee.Initialize(project='climatefiller-427208')
if data_link is None:
self.data = DataFrame()
else:
self.data = DataFrame(data_path=data_link, data_type=data_type, **kwargs)
self.data.rename_columns({datetime_column_name:'datetime'})
datetime_column_name = 'datetime'
self.data.column_to_date(datetime_column_name, datetime_format)
self.data.reindex_dataframe(datetime_column_name)
self.datetime_column_name = datetime_column_name
self.data_reanalysis = DataFrame()
def show(self, number_of_row=None):
"""
Displays a specified number of rows from the data source.
Args:
self (object): The instance of the class.
number_of_row (int or None, optional): The number of rows to display. Defaults to None.
Returns:
None
Notes:
- The show method is used to visualize a specified number of rows from the data source.
- If the number_of_row parameter is not provided, all available rows will be displayed.
- The displayed rows provide a preview or snapshot of the data in the data source.
"""
if number_of_row is None:
return self.data.get_dataframe()
elif number_of_row < 0:
return self.data.get_dataframe().tail(abs(number_of_row))
else:
return self.data.get_dataframe().head(number_of_row)
def recursive_fill(self, column_to_fill_name='ta',
variable='ta',
longitude=-7.593311291,
latitude=31.66749781):
"""
Recursively fills missing values in the specified column using a specified variable and coordinates.
Args:
column_to_fill_name (str): The name of the column to fill. Defaults to 'ta'.
variable (str): The variable to use for filling missing values. Defaults to 'ta'.
latitude (float): The latitude coordinate to use for filling missing values. Defaults to 31.66749781.
longitude (float): The longitude coordinate to use for filling missing values. Defaults to -7.593311291.
Returns:
None
"""
if self.missing_data_checking(column_to_fill_name) == 0:
print("No missing data found.")
elif self.missing_data_checking(column_to_fill_name) > 1000:
import numpy as np
data_chuncks = np.array_split(self.data.get_dataframe(), 2)
return DataFrame(ClimateFiller(data_chuncks[0], data_type='df').fill(column_to_fill_name,
variable,
latitude,
longitude), data_type='df').append_dataframe(ClimateFiller(data_chuncks[1], data_type='df').fill(
column_to_fill_name,
variable,
latitude,
longitude))
def fill(self, column_to_fill_name='ta',
lon=-7.593311291,
lat=31.66749781,
product="era5_land",
machine_learning_enabled=False,
):
"""
Fills missing values in the specified column using data retrieval and optionally machine learning techniques.
Args:
self (object): The instance of the class.
column_to_fill_name (str): The name of the column to fill. Defaults to 'ta'.
longitude (float): The longitude coordinate to use for data retrieval. Defaults to -7.593311291.
latitude (float): The latitude coordinate to use for data retrieval. Defaults to 31.66749781.
product (str): The data product to retrieve for filling missing values. Defaults to "era5_Land".
machine_learning_enabled (bool): Whether to use machine learning techniques for filling missing values. Defaults to False.
backend (str or None): The backend to use for data retrieval. Defaults to None.
Returns:
None
Notes:
- Missing values in the specified column will be replaced with appropriate data retrieved from the specified coordinates.
- The data product specified will be used to retrieve relevant data for filling missing values.
- The option to enable machine learning techniques allows for more sophisticated filling strategies.
- If the backend is not specified, the method will use the default backend associated with the class.
- The effectiveness of the filling process may depend on the data availability and the chosen backend.
"""
if self.backend == 'gee':
if self.missing_data_checking(column_to_fill_name, verbose=False) == 0:
print('No missing data found in ' + column_to_fill_name)
return
if product=='era5_land':
if column_to_fill_name == 'ta':
era5_land_variables = ['temperature_2m']
elif column_to_fill_name == 'rh':
era5_land_variables = ['temperature_2m', 'dewpoint_temperature_2m']
elif column_to_fill_name == 'rs':
era5_land_variables = ['surface_solar_radiation_downwards']
elif column_to_fill_name == 'ws':
era5_land_variables = ['u_component_of_wind_10m', 'v_component_of_wind_10m']
elif column_to_fill_name == 'p':
era5_land_variables = ['total_precipitation']
indexes = []
for p in self.data.get_missing_data_indexes_in_column(column_to_fill_name):
if isinstance(p, str) is True:
indexes.append(datetime.datetime.strptime(p, '%Y-%m-%d %H:%M:%S'))
else:
indexes.append(p)
years = set()
for p in indexes:
years.add(p.year)
missing_data_dates = {}
years = list(years)
years.sort()
print("Found missing data for {} in year(s): {}".format(column_to_fill_name, years))
self.download_era5_land_data_by_years(era5_land_variables, lon, lat, datetime.datetime(min(years), 1, 1), datetime.datetime(max(years), 12, 31))
from data_science_toolkit.gis import GIS
gis = GIS()
data = DataFrame()
if column_to_fill_name == 'ta':
for year in years:
data_year = DataFrame('data/cache/era5_land_' + '_'.join([str(s) for s in era5_land_variables] + [str(lon), str(lat), str(year)]) + '.csv')
data.append_dataframe(data_year.dataframe)
data.rename_columns({'first': 't2m'})
data.reset_index()
data.column_to_date('datetime')
data.reindex_dataframe("datetime")
data.sort()
data.missing_data('t2m')
data.transform_column('t2m', lambda o: o - 273.15)
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
data.drop_duplicated_indexes()
if machine_learning_enabled:
self.best_ml_model(column_to_fill_name, lon, lat, product)
for p in nan_indices:
print(self.data_reanalysis.get_row(p))
prediction = self.best_model.predict(self.data_reanalysis.get_row(p).values[0].reshape(1, -1))
self.data.set_row('ta', p, prediction)
"""for p in nan_indices:
if not df.loc[df['datetime'] == p, column_to_fill_name].empty:
prediction = self.best_model.predict(df.loc[df['datetime'] == p, column_to_fill_name].values[0].reshape(1, -1))
self.data.set_row(column_to_fill_name, p, prediction)"""
else:
for p in nan_indices:
try:
self.data.set_row('ta', p, data.get_row(p)['t2m'])
except KeyError as e:
print(f'Data about {p} not found in ERA5-Land')
print('Imputation of missing data for ta from ERA5-Land was done!')
elif column_to_fill_name == 'rh':
for year in years:
data_year = DataFrame('data/cache/era5_land_' + '_'.join([str(s) for s in era5_land_variables] + [str(lon), str(lat), str(year)]) + '.csv')
data.append_dataframe(data_year.dataframe)
data.reset_index()
data.column_to_date("datetime")
data.reindex_dataframe("datetime")
data.rename_columns({'temperature_2m': 't2m', 'dewpoint_temperature_2m': 'd2m'})
data.missing_data('t2m')
data.missing_data('d2m')
data.transform_column('t2m', lambda o: o - 273.15)
data.transform_column('d2m', lambda o: o - 273.15)
data.add_column_based_on_function('era5_hr', lambda row: Lib.relative_humidity_magnus(row['t2m'], row['d2m']))
data.missing_data('era5_hr')
nan_indices = self.data.get_missing_data_indexes_in_column(column_to_fill_name)
for p in nan_indices:
self.data.set_row('rh', p, data.get_row(p)['era5_hr'])
print('Imputation of missing data for rh from ERA5-Land was done!')
elif column_to_fill_name == 'ws':
for year in years:
data_year = DataFrame('data/cache/era5_land_' + '_'.join([str(s) for s in era5_land_variables] + [str(lon), str(lat), str(year)]) + '.csv')
data.append_dataframe(data_year.dataframe)
data.reset_index()
data.column_to_date("datetime")
data.reindex_dataframe("datetime")
data.rename_columns({'u_component_of_wind_10m': 'u10', 'v_component_of_wind_10m': 'v10'})
data.add_column_based_on_function('era5_ws', lambda row: Lib.logarithmic_wind_profile(row['u10'], row['v10']))
nan_indices = self.data.get_missing_data_indexes_in_column(column_to_fill_name)
data.missing_data('u10')
data.missing_data('era5_ws')
for p in nan_indices:
self.data.set_row('ws', p, data.get_row(p)['era5_ws'])
print('Imputation of missing data for wind speed from ERA5-Land was done!')
elif column_to_fill_name == 'rs':
for year in years:
data_year = DataFrame('data/cache/era5_land_' + '_'.join([str(s) for s in era5_land_variables] + [str(lon), str(lat), str(year)]) + '.csv')
data.append_dataframe(data_year.dataframe)
data.rename_columns({'first': 'ssrd'})
data.reset_index()
data.column_to_date('datetime')
data.reindex_dataframe("datetime")
data.missing_data('ssrd')
l = []
for p in data.get_index():
if p.hour == 1:
new_value = data.get_row(p)['ssrd']/3600
else:
try:
previous_hour = data.get_row(p-timedelta(hours=1))['ssrd']
except KeyError: # if age is not convertable to int
previous_hour = data.get_row(p)['ssrd']
new_value = (data.get_row(p)['ssrd'] - previous_hour)/3600
l.append(new_value)
data.add_column('rs', l)
data.keep_columns(['rs'])
data.rename_columns({'rs': 'ssrd'})
data.transform_column('ssrd', lambda o : o if abs(o) < 1500 else 0 )
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
for p in nan_indices:
self.data.set_row('rs', p, data.get_row(p)['ssrd'])
print('Imputation of missing data for ' + column_to_fill_name + ' from ERA5-Land was done.')
elif column_to_fill_name == 'p':
for year in years:
data_year = DataFrame('data/cache/era5_land_' + '_'.join([str(s) for s in era5_land_variables] + [str(lon), str(lat), str(year)]) + '.csv')
data.append_dataframe(data_year.dataframe)
data.rename_columns({'first': 'tp'})
data.reset_index()
data.column_to_date('datetime')
data.reindex_dataframe("datetime")
data.sort()
data.missing_data('tp')
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
data.drop_duplicated_indexes()
l = []
for p in data.get_index():
if p.hour == 1:
new_value = data.get_row(p)['tp'] * 1000
else:
try:
previous_hour = data.get_row(p-timedelta(hours=1))['tp']
except KeyError:
previous_hour = data.get_row(p)['tp']
new_value = (data.get_row(p)['tp'] - previous_hour)*1000
l.append(new_value)
data.add_column('p', l)
data.keep_columns(['p'])
data.rename_columns({'p': 'tp'})
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
for p in nan_indices:
self.data.set_row('p', p, data.get_row(p)['tp'])
print('Imputation of missing data for ' + column_to_fill_name + ' from ERA5-Land was done.')
elif product == 'merra2':
merra2_variables = {
'ta': 'T2M',
'rh': 'RH2M',
'ws': 'WS2M',
'rs': 'ALLSKY_SFC_SW_DWN',
'pr': 'PRECTOTCORR',
'wd': 'WD2M'
}
if column_to_fill_name not in merra2_variables:
print(f'Invalid column_to_fill_name: {column_to_fill_name}')
return
start = self.data.get_dataframe().index[0]
end = self.data.get_dataframe().index[-1]
start = datetime.datetime.strftime(start, '%Y%m%d')
end = datetime.datetime.strftime(end, '%Y%m%d')
api_url = 'https://power.larc.nasa.gov/api/temporal/hourly/point'
format = 'json'
community = 'ag'
timezone = 'utc'
params = {
'start': start,
'end': end,
'latitude': lat,
'longitude': lon,
'community': community,
'parameters': merra2_variables[column_to_fill_name],
'format': format,
'user': 'ysouidi1',
'header': 'true',
'time-standard': timezone
}
response = requests.get(api_url, params=params)
if response.status_code != 200:
print('Failed to retrieve data:', response.status_code)
return None
data_merra = response.json()
result = data_merra['properties']['parameter'][merra2_variables[column_to_fill_name]]
df = pd.DataFrame(result.items(), columns=['datetime', column_to_fill_name])
df['datetime'] = pd.to_datetime(df['datetime'], format='%Y%m%d%H')
nan_indices = self.data.get_missing_data_indexes_in_column(column_to_fill_name)
if len(nan_indices) == 0:
return
if machine_learning_enabled:
self.best_ml_model(column_to_fill_name, lon, lat, product)
for p in nan_indices:
if not df.loc[df['datetime'] == p, column_to_fill_name].empty:
prediction = self.best_model.predict(df.loc[df['datetime'] == p, column_to_fill_name].values[0].reshape(1, -1))
self.data.set_row(column_to_fill_name, p, prediction)
else:
for p in nan_indices:
corresponding_row = df[df['datetime'] == p][column_to_fill_name]
if not corresponding_row.empty:
self.data.set_row(column_to_fill_name, p, df.loc[df['datetime'] == p, column_to_fill_name].values[0])
self.data.index_to_column()
print('Imputation of missing data for ' + column_to_fill_name + ' from MERRA2 was done.')
# other data source
else:
pass
pass
else:
if self.missing_data_checking(column_to_fill_name, verbose=False) == 0:
print('No missing data found in ' + column_to_fill_name)
return
if product=='era5_land':
if column_to_fill_name == 'ta':
era5_land_variables = ['2m_temperature']
elif column_to_fill_name == 'rh':
era5_land_variables = ['2m_temperature', '2m_dewpoint_temperature']
elif column_to_fill_name == 'rs':
era5_land_variables = ['surface_solar_radiation_downwards']
elif column_to_fill_name == 'ws':
era5_land_variables = ['10m_u_component_of_wind', '10m_v_component_of_wind']
elif column_to_fill_name == 'p':
era5_land_variables = ['total_precipitation']
from data_science_toolkit.gis import GIS
import cdsapi
c = cdsapi.Client()
"""if self.datetime_column_name is not None:
self.data.reindex_dataframe(self.datetime_column_name)"""
indexes = []
for p in self.data.get_missing_data_indexes_in_column(column_to_fill_name):
if isinstance(p, str) is True:
indexes.append(datetime.datetime.strptime(p, '%Y-%m-%d %H:%M:%S'))
else:
indexes.append(p)
years = set()
for p in indexes:
years.add(p.year)
missing_data_dates = {}
years = list(years)
print("Found missing data for {} in year(s): {}".format(column_to_fill_name, years))
for y in years:
missing_data_dict = {}
missing_data_dict['month'] = set()
missing_data_dict['day'] = set()
for p in indexes:
if p.year == y:
missing_data_dict['month'].add(p.strftime('%m'))
missing_data_dict['day'].add(p.strftime('%d'))
missing_data_dict['month'] = list(missing_data_dict['month'])
missing_data_dict['day'] = list(missing_data_dict['day'])
missing_data_dates[y] = missing_data_dict
for month in missing_data_dict['month']:
for p in era5_land_variables:
data_month_path = 'data\era5land_' + p + '_' + str(lon) + '_' + str(lat) + '_' + str(y) + '_' + month + '.grib'
if os.path.exists(data_month_path) is False:
c.retrieve(
'reanalysis-era5-land',
{
'format': 'grib',
'variable': p,
'year': str(y),
'month': month,
'day': missing_data_dict['day'],
'time': [
'00:00', '01:00', '02:00',
'03:00', '04:00', '05:00',
'06:00', '07:00', '08:00',
'09:00', '10:00', '11:00',
'12:00', '13:00', '14:00',
'15:00', '16:00', '17:00',
'18:00', '19:00', '20:00',
'21:00', '22:00', '23:00',
],
'area': [lat, lon, lat, lon],
},
data_month_path)
else:
print(f'Data of {y}-{month} found in {data_month_path}')
gis = GIS()
data = DataFrame()
if column_to_fill_name == 'ta':
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
data_month_path = 'data\era5land_' + column_to_fill_name + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data.append_dataframe(gis.get_era5_land_grib_as_dataframe(data_month_path, "ta"),)
data.reset_index()
data.column_to_date('valid_time')
data.reindex_dataframe("valid_time")
data.sort()
data.missing_data('t2m')
data.transform_column('t2m', lambda o: o - 273.15)
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
data.drop_duplicated_indexes()
if machine_learning_enabled:
self.best_ml_model(column_to_fill_name, lon, lat, product)
for p in nan_indices:
print(self.data_reanalysis.get_row(p))
prediction = self.best_model.predict(self.data_reanalysis.get_row(p).values[0].reshape(1, -1))
self.data.set_row('ta', p, prediction)
"""for p in nan_indices:
if not df.loc[df['datetime'] == p, column_to_fill_name].empty:
prediction = self.best_model.predict(df.loc[df['datetime'] == p, column_to_fill_name].values[0].reshape(1, -1))
self.data.set_row(column_to_fill_name, p, prediction)"""
else:
for p in nan_indices:
try:
self.data.set_row('ta', p, data.get_row(p)['t2m'])
except KeyError as e:
print(f'Data about {p} not found in ERA5-Land')
print('Imputation of missing data for ta from ERA5-Land was done!')
elif column_to_fill_name == 'rh':
data_t2m = DataFrame()
data_d2m = DataFrame()
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
month_data_t2m = 'data\era5land_' + '2m_temperature' + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data_t2m.append_dataframe(gis.get_era5_land_grib_as_dataframe(month_data_t2m, "ta"),)
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
month_data_d2m = 'data\era5land_' + '2m_dewpoint_temperature' + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data_d2m.append_dataframe(gis.get_era5_land_grib_as_dataframe(month_data_d2m, "ta"),)
data_d2m.reset_index()
data_d2m.reindex_dataframe("valid_time")
data_d2m.keep_columns(['d2m'])
data_t2m.reset_index()
data_t2m.reindex_dataframe("valid_time")
data_t2m.keep_columns(['t2m'])
data_t2m.join(data_d2m.get_dataframe())
data = data_t2m
data.missing_data('t2m')
data.transform_column('t2m', lambda o: o - 273.15)
data.transform_column('d2m', lambda o: o - 273.15)
data.add_column_based_on_function('era5_hr', lambda row: Lib.get_relative_humidity(row['t2m', 'd2m']))
#data.add_transformed_columns('era5_hr', '100*exp(-((243.12*17.62*t2m)-(d2m*17.62*t2m)-d2m*17.62*(243.12+t2m))/((243.12+t2m)*(243.12+d2m)))')
data.missing_data('era5_hr')
nan_indices = self.data.get_missing_data_indexes_in_column(column_to_fill_name)
for p in nan_indices:
self.data.set_row('rh', p, data.get_row(p)['era5_hr'])
print('Imputation of missing data for rh from ERA5-Land was done!')
elif column_to_fill_name == 'ws':
data_u10 = DataFrame()
data_v10 = DataFrame()
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
month_data_u10 = 'data\era5land_' + '10m_u_component_of_wind' + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data_u10.append_dataframe(gis.get_era5_land_grib_as_dataframe(month_data_u10, "ta"),)
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
month_data_v10 = 'data\era5land_' + '10m_v_component_of_wind' + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data_v10.append_dataframe(gis.get_era5_land_grib_as_dataframe(month_data_v10, "ta"),)
data_u10.reset_index()
data_u10.reindex_dataframe("valid_time")
data_u10.keep_columns(['u10'])
data_v10.reset_index()
data_v10.reindex_dataframe("valid_time")
data_v10.keep_columns(['v10'])
data_v10.join(data_u10.get_dataframe())
data = data_v10
data.add_column_based_on_function('era5_ws', Lib.get_2m_wind_speed)
nan_indices = self.data.get_missing_data_indexes_in_column(column_to_fill_name)
data.missing_data('u10')
data.missing_data('era5_ws')
for p in nan_indices:
self.data.set_row('ws', p, data.get_row(p)['era5_ws'])
print('Imputation of missing data for wind speed from ERA5-Land was done!')
elif column_to_fill_name == 'rs':
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
data_month_path = 'data\era5land_' + 'surface_solar_radiation_downwards' + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data.append_dataframe(gis.get_era5_land_grib_as_dataframe(data_month_path, "ta"),)
data.reset_index()
data.reindex_dataframe("valid_time")
data.missing_data('ssrd')
l = []
for p in data.get_index():
if p.hour == 1:
new_value = data.get_row(p)['ssrd']/3600
else:
try:
previous_hour = data.get_row(p-timedelta(hours=1))['ssrd']
except KeyError: # if age is not convertable to int
previous_hour = data.get_row(p)['ssrd']
new_value = (data.get_row(p)['ssrd'] - previous_hour)/3600
l.append(new_value)
data.add_column('rs', l)
data.keep_columns(['rs'])
data.rename_columns({'rs': 'ssrd'})
data.transform_column('ssrd', lambda o : o if abs(o) < 1500 else 0 )
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
for p in nan_indices:
self.data.set_row('rs', p, data.get_row(p)['ssrd'])
print('Imputation of missing data for ' + column_to_fill_name + ' from ERA5-Land was done.')
elif column_to_fill_name == 'p':
for year in missing_data_dates:
for month in missing_data_dates[year]['month']:
data_month_path = 'data\era5land_' + 'total_precipitation' + '_' + str(lon) + '_' + str(lat) + '_' + str(year) + '_' + month + '.grib'
data.append_dataframe(gis.get_era5_land_grib_as_dataframe(data_month_path, "ta"),)
data.reset_index()
data.column_to_date('valid_time')
data.reindex_dataframe("valid_time")
data.sort()
data.missing_data('tp')
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
data.drop_duplicated_indexes()
l = []
for p in data.get_index():
if p.hour == 1:
new_value = data.get_row(p)['tp'] * 1000
else:
try:
previous_hour = data.get_row(p-timedelta(hours=1))['tp']
except KeyError:
previous_hour = data.get_row(p)['tp']
new_value = (data.get_row(p)['tp'] - previous_hour)*1000
l.append(new_value)
data.add_column('p', l)
data.keep_columns(['p'])
data.rename_columns({'p': 'tp'})
nan_indices = self.data.get_nan_indexes_of_column(column_to_fill_name)
for p in nan_indices:
self.data.set_row('p', p, data.get_row(p)['tp'])
print('Imputation of missing data for ' + column_to_fill_name + ' from ERA5-Land was done.')
elif product == 'merra2':
merra2_variables = {
'ta': 'T2M',
'rh': 'RH2M',
'ws': 'WS2M',
'rs': 'ALLSKY_SFC_SW_DWN',
'pr': 'PRECTOTCORR',
'wd': 'WD2M'
}
if column_to_fill_name not in merra2_variables:
print(f'Invalid column_to_fill_name: {column_to_fill_name}')
return
start = self.data.get_dataframe().index[0]
end = self.data.get_dataframe().index[-1]
start = datetime.datetime.strftime(start, '%Y%m%d')
end = datetime.datetime.strftime(end, '%Y%m%d')
api_url = 'https://power.larc.nasa.gov/api/temporal/hourly/point'
format = 'json'
community = 'ag'
timezone = 'utc'
params = {
'start': start,
'end': end,
'latitude': lat,
'longitude': lon,
'community': community,
'parameters': merra2_variables[column_to_fill_name],
'format': format,
'user': 'ysouidi1',
'header': 'true',
'time-standard': timezone
}
response = requests.get(api_url, params=params)
if response.status_code != 200:
print('Failed to retrieve data:', response.status_code)
return None
data_merra = response.json()
result = data_merra['properties']['parameter'][merra2_variables[column_to_fill_name]]
df = pd.DataFrame(result.items(), columns=['datetime', column_to_fill_name])
df['datetime'] = pd.to_datetime(df['datetime'], format='%Y%m%d%H')
nan_indices = self.data.get_missing_data_indexes_in_column(column_to_fill_name)
if len(nan_indices) == 0:
return
if machine_learning_enabled:
self.best_ml_model(column_to_fill_name, lon, lat, product)
for p in nan_indices:
if not df.loc[df['datetime'] == p, column_to_fill_name].empty:
prediction = self.best_model.predict(df.loc[df['datetime'] == p, column_to_fill_name].values[0].reshape(1, -1))
self.data.set_row(column_to_fill_name, p, prediction)
else:
for p in nan_indices:
corresponding_row = df[df['datetime'] == p][column_to_fill_name]
if not corresponding_row.empty:
self.data.set_row(column_to_fill_name, p, df.loc[df['datetime'] == p, column_to_fill_name].values[0])
self.data.index_to_column()
print('Imputation of missing data for ' + column_to_fill_name + ' from MERRA2 was done.')
# other data source
else:
pass
def best_ml_model(self, column_to_fill_name, lon, lat, product, metric='rmse'):
list_models = [
LinearRegression(),
DecisionTreeRegressor(),
RandomForestRegressor(),
XGBRegressor(),
CatBoostRegressor(verbose=False),
Ridge(),
Lasso(),
ElasticNet()
]
print(f'Finding the best machine learning model...')
start_datetime = self.data.get_dataframe().index[0]
end_datetime = self.data.get_dataframe().index[-1]
self.download(column_to_fill_name, lon, lat, start_datetime, end_datetime, product)
output_file = 'data/era5_land_' + '_'.join([str(column_to_fill_name), str(lon), str(lat), str(start_datetime.strftime('%Y-%m-%d')), str(end_datetime.strftime('%Y-%m-%d'))]) + '.csv'
data_temp = DataFrame(output_file)
self.data_reanalysis.set_dataframe(data_temp.get_dataframe())
self.data_reanalysis.column_to_date('datetime')
self.data_reanalysis.reindex_dataframe('datetime')
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
self.data.keep_columns([column_to_fill_name])
self.data_reanalysis.join(self.data.get_dataframe())
self.data_reanalysis.missing_data(column_to_fill_name)
self.data_reanalysis.reset_index()
y = self.data_reanalysis.get_column(column_to_fill_name)
X = self.data_reanalysis.drop_column(column_to_fill_name)
rmse_scores = {}
r2_scores = {}
if metric=='rmse':
for model in list_models:
model_rmse_scores = []
for train_index, test_index in kfold.split(X):
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
model_rmse_scores.append(rmse)
avg_rmse = np.mean(model_rmse_scores)
rmse_scores[model.__class__.__name__] = avg_rmse
elif metric=='r2':
for model in list_models:
model_r2_scores = []
for train_index, test_index in kfold.split(X):
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
model_r2_scores.append(r2)
avg_r2 = np.mean(model_r2_scores)
r2_scores[model.__class__.__name__] = avg_r2
best_model_name = min(rmse_scores, key=rmse_scores.get)
best_model = next((model for model in list_models if model.__class__.__name__ == best_model_name), None)
self.best_model = best_model
print(f'The Best perfoming model is: {best_model_name} with {metric.upper()}={rmse_scores[best_model_name]}')
def missing_data_checking(self, column_name=None, verbose=True):
"""Function Name: missing_data_checking
Description:
This function checks for missing data in a column of a dataframe.
Parameters:
self: the instance of the class that the function is a part of.
column_name: (optional) the name of the column to check for missing data. If not provided, the function will check for missing data in all columns of the dataframe. Default value is None.
verbose: (optional) a boolean value that determines whether the function should print a summary of the missing data. Default value is True.
Returns:
A dictionary that contains the number and percentage of missing values for each column checked.
Note:
This function assumes that the dataframe has already been loaded into the class instance.
"""
miss = 0
if column_name is not None:
if any(pd.isna(self.data.get_dataframe()[column_name])) is True:
miss = self.data.get_dataframe()[column_name].isnull().sum()
missing_data_percent = round((miss/self.data.get_shape()[0])*100, 2)
if verbose is True:
print("{} has {} missing value(s) which represents {}% of dataset size".format(column_name, miss, missing_data_percent))
else:
if verbose is True:
print("No missed data in column " + column_name)
else:
miss = []
for c in self.data.get_dataframe().columns:
miss_by_column = self.data.get_dataframe()[c].isnull().sum()
if miss_by_column>0:
missing_data_percent = round((miss_by_column/self.data.get_shape()[0])*100, 2)
if verbose is True:
print("{} has {} missing value(s) which represents {}% of dataset size".format(c, miss_by_column, missing_data_percent))
else:
if verbose is True:
print("{} has NO missing value!".format(c))
miss.append(miss_by_column)
if verbose is False:
return miss
def eliminate_outliers(self, climate_varibale_column_name='ta', method='lof', n_neighbors=48, contamination=0.005, n_estimators=100):
"""
Eliminates outliers in the specified climate variable column using the specified outlier detection method.
Args:
self (object): The instance of the class.
climate_variable_column_name (str): The name of the climate variable column to eliminate outliers from.
Defaults to 'ta'.
method (str): The outlier detection method to use. Currently supported methods include:
- 'lof': Local Outlier Factor algorithm, which measures the local deviation of a data point
with respect to its neighbors. Defaults to 'lof'.
n_neighbors (int): The number of neighbors to consider for outlier detection.
This parameter is only applicable to certain outlier detection methods. Defaults to 48.
contamination (float): The expected proportion of outliers in the data.
This parameter is only applicable to certain outlier detection methods. Defaults to 0.005.
n_estimators (int): The number of base estimators to use for ensemble-based outlier detection methods.
This parameter is only applicable to certain outlier detection methods. Defaults to 100.
Returns:
None
Notes:
- Outliers are data points that significantly deviate from the majority of the data.
- The specified climate variable column will be processed to identify and eliminate outliers.
- The chosen outlier detection method will be applied to identify and mark outliers in the data.
- The method aims to improve the quality and reliability of the climate variable data by removing outliers.
- The effectiveness and performance of the outlier elimination process may vary depending on the method and parameters used.
"""
if method == 'lof':
outliers_model = LocalOutlierFactor(n_neighbors=n_neighbors, contamination=contamination)
self.data.get_dataframe()['inlier'] = outliers_model.fit_predict(self.data.get_columns([climate_varibale_column_name]))
print('Number of detected outliers: {}'.format(self.data.count_occurence_of_each_row('inlier').iloc[0]))
self.data.dataframe.loc[self.data.get_dataframe()['inlier'] == -1, climate_varibale_column_name] = None
self.data.drop_column('inlier')
elif method == 'isolation_forest':
outliers_model = IsolationForest(contamination=contamination, n_estimators=n_estimators, random_state=42)
self.data.get_dataframe()['inlier'] = outliers_model.fit_predict(self.data.get_columns([climate_varibale_column_name]))
print('Number of detected outliers: {}'.format(self.data.count_occurence_of_each_row('inlier').iloc[0]))
self.data.dataframe.loc[self.data.get_dataframe()['inlier'] == -1, climate_varibale_column_name] = 2000
self.data.drop_column('inlier')
elif method == 'quantiles':
outliers_model = LocalOutlierFactor(n_neighbors=n_neighbors, contamination=contamination)
self.data.get_dataframe()['inlier'] = outliers_model.fit_predict(self.data.get_columns([climate_varibale_column_name]))
print('Number of detected outliers: {}'.format(self.data.count_occurence_of_each_row('inlier').iloc[0]))
self.data.dataframe.loc[self.data.get_dataframe()['inlier'] == -1, climate_varibale_column_name] = None
self.data.drop_column('inlier')
def evaluate_products(self):
pass
def plot_column(self, column):
"""Function Name: plot_column
Description:
This function creates a time-series plot of a column in a dataframe.
Parameters:
self: the instance of the class that the function is a part of.
column: the name of the column to plot.
Returns:
None. The function generates a time-series plot of the specified column.
Note:
This function assumes that the dataframe has already been loaded into the class instance. This function requires the matplotlib and seaborn libraries to be installed.
"""
self.data.get_column(column).plot()
plt.show()
def extraterrestrial_radiation_daily(self, column_name='ra', nbr_decimal_places=None):
self.data.index_to_column()
self.data.add_doy_column(datetime_column_name=self.datetime_column_name)
self.data.add_one_value_column('lat', self.lat)
self.data.add_column_based_on_function(
column_name,
lambda row: Lib.extraterrestrial_radiation_daily(
row['lat'],
row['doy'])
)
if nbr_decimal_places is not None:
self.data.transform_column(column_name, lambda o: round(o, nbr_decimal_places))
self.data.reindex_dataframe(self.datetime_column_name)
def et0_estimation(self,
ta_column_name='ta',
rs_column_name='rs',
rh_column_name='rh',
ws_column_name='ws',
method='pm',
freq='d',
reference_crop='grass',
nbr_decimal_places=2,
c_hs=0.0023,
a_hs=17.8,
b_hs=0.5,
k1_ab=0.53,
alpha_pt=1.26,
):
"""
Estimates reference evapotranspiration (ET0) using the specified meteorological data and method.
Args:
self (object): The instance of the class.
air_temperature_column_name (str): The name of the column that contains air temperature data. Defaults to 'ta'.
global_solar_radiation_column_name (str): The name of the column that contains global solar radiation data. Defaults to 'rs'.
air_relative_humidity_column_name (str): The name of the column that contains air relative humidity data. Defaults to 'rh'.
wind_speed_column_name (str): The name of the column that contains wind speed data. Defaults to 'ws'.
date_time_column_name (str): The name of the column that contains date and time information. Defaults to 'date_time'.
latitude (float): The latitude coordinate of the location for ET0 estimation. Defaults to 31.65410805.
longitude (float): The longitude coordinate of the location for ET0 estimation. Defaults to -7.603140831.
method (str): The method to use for ET0 estimation. Currently supported methods include:
- 'pm': Penman-Monteith method, which is based on the FAO56 Penman-Monteith equation. Defaults to 'pm'.
in_place (bool): Whether to replace the original ET0 column in the dataset or create a new column. Defaults to True.
Returns:
None
Notes:
- ET0 estimation is a measure of the potential evapotranspiration from a reference crop.
- The method utilizes meteorological data such as air temperature, global solar radiation, air relative humidity, and wind speed.
- The specified columns in the dataset will be used for ET0 estimation.
- The latitude and longitude coordinates define the location for ET0 estimation.
- The chosen method will be applied to calculate ET0 values.
- If in_place is True, the original ET0 column will be replaced; otherwise, a new column will be created.
"""
data_temp = DataFrame()