-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmeteorology.py
More file actions
1803 lines (1396 loc) · 98.2 KB
/
meteorology.py
File metadata and controls
1803 lines (1396 loc) · 98.2 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 21 14:42:33 2024
@author: amounier
"""
import time
import os
import pandas as pd
from datetime import date
import requests
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from pysolar.solar import get_altitude, get_altitude_fast, get_azimuth, get_azimuth_fast
import tqdm
import seaborn as sns
import pickle
from sklearn.metrics import root_mean_squared_error, mean_absolute_error
from scipy.optimize import curve_fit
import subprocess
from scipy.spatial.distance import euclidean
import geopandas as gpd
from sklearn.metrics import r2_score
# Pour ne pas utiliser numpy dans la gestion des dates de Pysolar (moins efficace et plus à jour)
import pysolar
pysolar.use_math()
from utils import plot_timeserie
from administrative import get_coordinates, France, Climat, Departement, City
import warnings
def get_open_meteo_url(longitude, latitude, year, hourly_variables):
"""
Récupération de l'url de l'API Open-Météo
Parameters
----------
longitude : float
DESCRIPTION.
latitude : float
DESCRIPTION.
year : int
DESCRIPTION.
hourly_variables : list of str or str
DESCRIPTION.
Returns
-------
url : str
DESCRIPTION.
"""
if isinstance(hourly_variables, list):
hourly_variables = ','.join(hourly_variables)
tod = pd.Timestamp(date.today())
# Si l'année demandée n'est pas terminée, il faut modifier les périodes requêtées
end_month, end_day = 12, 31
if year == tod.year:
end_day = tod.strftime('%d')
end_month = tod.strftime('%m')
url = 'https://archive-api.open-meteo.com/v1/archive?latitude={}&longitude={}&start_date={}-01-01&end_date={}-{}-{}&hourly={}&timezone=Europe%2FBerlin'.format(latitude,longitude,year,year,end_month,end_day,hourly_variables)
# print(url)
return url
def open_meteo_historical_data(longitude, latitude, year, hourly_variables=['temperature_2m','direct_radiation_instant'], force=False):
"""
Ouverture des fichiers meteo
Parameters
----------
longitude : float
DESCRIPTION.
latitude : float
DESCRIPTION.
year : int
DESCRIPTION.
hourly_variables : str or list of str, optional
DESCRIPTION. The default is ['temperature_2m','direct_radiation_instant'].
force : boolean, optional
DESCRIPTION. The default is False.
Returns
-------
data : pandas DataFrame
DESCRIPTION.
"""
# TODO : peut-etre mettre un nom de ville en entrée et en faire des nom de sauvegarde plus lisible
if isinstance(hourly_variables, list):
hourly_variables_str = ','.join(hourly_variables)
else:
hourly_variables_str = hourly_variables
save_path = os.path.join('data','Open-Meteo')
save_name = '{}_{}_{}_{}.csv'.format(hourly_variables_str, year, longitude, latitude)
save_name_units = '{}_{}_{}_{}_units.txt'.format(hourly_variables_str, year, longitude, latitude)
if save_name not in os.listdir(save_path) or force:
url = get_open_meteo_url(longitude, latitude, year, hourly_variables)
response = requests.get(url)
# print(year, response)
json_data = response.json()
units = json_data.get('hourly_units')
with open(os.path.join(save_path,save_name_units), 'w') as f:
for col, unit in units.items():
f.write('{} : {} \n'.format(col,unit))
data = pd.DataFrame().from_dict(json_data.get('hourly'))
data.to_csv(os.path.join(save_path,save_name), index=False)
data = pd.read_csv(os.path.join(save_path,save_name))
data = data.set_index('time')
data.index = pd.to_datetime(data.index)
return data
def get_meteo_data(city, period=[2020,2024],variables=['temperature_2m','direct_radiation_instant']):
longitude, latitude = get_coordinates(city)
data = None
for y in range(period[0],period[1]+1):
yearly_data = open_meteo_historical_data(longitude, latitude, y, hourly_variables=variables)
if data is None:
data = yearly_data
else:
data = pd.concat([data, yearly_data])
return data
def get_meteo_units(longitude, latitude, year, hourly_variables=['temperature_2m','direct_radiation_instant']):
"""
Récupération du dictionnaire des unités des variables météorologiques
Parameters
----------
longitude : float
DESCRIPTION.
latitude : float
DESCRIPTION.
year : int
DESCRIPTION.
hourly_variables : str or list of str, optional
DESCRIPTION. The default is ['temperature_2m','direct_radiation_instant'].
Returns
-------
d : dict
DESCRIPTION.
"""
if isinstance(hourly_variables, list):
hourly_variables_str = ','.join(hourly_variables)
else:
hourly_variables_str = hourly_variables
unit_path = os.path.join('data','Open-Meteo','{}_{}_{}_{}_units.txt'.format(hourly_variables_str, year, longitude, latitude))
with open(unit_path) as f:
d = {k: v for line in f for (k, v) in [line.strip().split(' : ')]}
return d
def get_direct_solar_irradiance_projection_ratio(orientation,sun_azimuth,sun_altitude):
"""
Coefficient de puissance solaire directe pour une paroi donnée.
Parameters
----------
orientation : str or int or float
Orientation de la paroi (str conseillé).
sun_azimuth : int or float
Angle azimutal du soleil en degré.
sun_altitude : int or float
Angle d'altitude du soleil en degré.
Raises
------
ValueError
Si l'orientation donnée est fausse.
Returns
-------
ratio : float
Coefficient compris entre 0 et 1.
"""
# gestion rapide du cas d'une paroi horizontale
if orientation == 'H':
ratio = np.sin(np.deg2rad(np.maximum(sun_altitude,0)))
# cas des parois verticales
else:
# passage d'une orientation str en angle en degrés
valid_orientations = ['N','NE','E','SE','S','SW','W','NW']
dict_angle_orientation = {i*45:o for i,o in enumerate(valid_orientations)}
dict_orientation_angle = {v:k for k,v in dict_angle_orientation.items()}
if isinstance(orientation,str):
# Vérification de l'orientation
if orientation not in valid_orientations:
raise ValueError("'{}' is not a valid orientation (must be in ['{}']).".format(orientation,"', '".join(valid_orientations)))
orientation_angle = dict_orientation_angle.get(orientation)
# l'orientation peut directement être entrée en degrés (déconseillé)
elif isinstance(orientation,int) or isinstance(orientation,float):
orientation_angle = orientation%360
ratio = np.float64(sun_altitude>0) * np.cos(np.deg2rad(sun_altitude)) * np.maximum(np.cos(np.deg2rad(list(sun_azimuth-orientation_angle))),0)
return ratio
def get_diffuse_solar_irradiance_projection_ratio(orientation):
"""
Coefficient de puissance solaire diffuse pour une paroi donnée.
Parameters
----------
orientation : int or str
Orientation de la paroi.
Returns
-------
ratio : float
Coefficient de puissance.
"""
if orientation == 'H':
ratio = 1.
else:
ratio = 0.5
return ratio
def get_init_ground_temperature(x, data, xi_1 = 0.8, xi_2=0.4, w0=1.37, second_order=True):
theta_ginit = data[(data.index.month==1)&(data.index.day==1)].temperature_2m.min()
theta_ginf = data.temperature_2m.median()
if second_order:
# res = theta_ginit + (theta_ginf-theta_ginit)*(1 - np.exp(-xi_2*w0*x) * np.cos(w0*np.sqrt(1-xi_2**2)*x))
res = get_kusuda_ground_temperature(x, data, lambda_th=1.5,cp=1000,rho=2500)[0]
else:
# data_january = data[data.index.month==1]
# TODO : tendance à sous estimer les valeurs : à modifier
# if envelope:
# theta_gs = data_january.temperature_2m.mean()
# else:
# theta_gs = data.temperature_2m.values[0]
# theta_ginf = data.temperature_2m.median()
res = theta_ginit + (theta_ginf-theta_ginit) * (1-np.exp(-x/xi_1))
return res
def get_kusuda_ground_temperature(x, data, lambda_th, rho, cp):
daily_data = data.groupby(pd.Grouper(freq='D')).agg(func='mean')
daily_data = daily_data.rolling(15,min_periods=0,center=True).mean()
theta_ginf = daily_data.temperature_2m.mean()
delta_theta = (daily_data.temperature_2m.max() - daily_data.temperature_2m.min())/2
phi_s = daily_data.temperature_2m.idxmin().dayofyear
alpha = lambda_th/(rho*cp)
omega = 2*np.pi/365
delta = np.sqrt(2*alpha*3600*24/omega)
nb_years = len(set(data.index.year))
list_t = np.linspace(0,365*nb_years,len(data))
res = np.asarray([theta_ginf - delta_theta*np.exp(-x/delta)*np.cos(omega*t-np.pi*phi_s/365-x/delta) for t in list_t])
return res
def get_list_orientations(principal_orientation):
# définition des dictionnaires d'angles
valid_orientations = ['N','NE','E','SE','S','SW','W','NW']
dict_angle_orientation = {i*45:o for i,o in enumerate(valid_orientations)}
dict_orientation_angle = {v:k for k,v in dict_angle_orientation.items()}
# liste des orientations
orientation_0 = principal_orientation
orientation_1 = dict_angle_orientation.get((dict_orientation_angle.get(orientation_0)+90)%360)
orientation_2 = dict_angle_orientation.get((dict_orientation_angle.get(orientation_1)+90)%360)
orientation_3 = dict_angle_orientation.get((dict_orientation_angle.get(orientation_2)+90)%360)
orientations_list = [orientation_0, orientation_1, orientation_2, orientation_3] + ['H']
return orientations_list
def get_historical_weather_data(city, period, display_units=False):
# initialisation des données météo
variables = ['temperature_2m','diffuse_radiation_instant','direct_normal_irradiance_instant']
coordinates = get_coordinates(city)
data = get_meteo_data(city,period,variables=variables)
# formatage des dates sur le bon fuseau horaire
dates = data.copy().index
dates = dates.tz_localize(tz='CET',ambiguous='NaT',nonexistent='NaT')
dates = dates.to_pydatetime()
# ajout de la hauteur du soleil (en degrés)
altitude = [get_altitude_fast(coordinates[1],coordinates[0],t) if t is not pd.NaT else np.nan for t in dates]
data['sun_altitude'] = altitude
# ajout de l'azimuth du soleil (en degrés)
azimuth = [float(get_azimuth_fast(coordinates[1],coordinates[0],t)) if t is not pd.NaT else np.nan for t in dates]
data['sun_azimuth'] = azimuth
# défintion de la liste des orientations du bâtiment
# orientations = get_list_orientations(principal_orientation)
orientations = ['N','NE','E','SE','S','SW','W','NW','H']
for ori in orientations:
col_coef_dri = 'coefficient_direct_{}_irradiance'.format(ori)
col_coef_dif = 'coefficient_diffuse_{}_irradiance'.format(ori)
col_dri = 'direct_sun_radiation_{}'.format(ori)
col_dif = 'diffuse_sun_radiation_{}'.format(ori)
# global_ri = 'sun_radiation_{}'.format(ori)
data[col_coef_dri] = get_direct_solar_irradiance_projection_ratio(ori, data.sun_azimuth, data.sun_altitude)
data[col_coef_dif] = get_diffuse_solar_irradiance_projection_ratio(ori)
data[col_dri] = data.direct_normal_irradiance_instant * data[col_coef_dri]
data[col_dif] = data.diffuse_radiation_instant * data[col_coef_dif]
# je garde les apports diffus et directs séparés pour pouvoir traiter les masquages différemment
# data[global_ri] = data[col_dri] + data[col_dif]
# suppression des colonnes intermédiaires de calcul
data = data.drop(columns=[col_coef_dri,col_coef_dif])
if display_units:
meteo_units = get_meteo_units(longitude=coordinates[0], latitude=coordinates[1], year=period[0], hourly_variables=variables)
meteo_units['sun_altitude'] = '°'
meteo_units['sun_azimuth'] = '°'
meteo_units['direct_sun_radiation'] = 'W/m²'
meteo_units['diffuse_sun_radiation'] = 'W/m²'
print(meteo_units)
return data
def aggregate_resolution(data, resolution='h', agg_method='mean'):
agg_data = data.groupby(pd.Grouper(freq=resolution)).agg(func=agg_method)
return agg_data
def refine_resolution(data, resolution):
upsampled = data.resample(resolution)
interpolated = upsampled.interpolate(method='linear')
return interpolated
def download_MF_compressed_files():
departements = France().departements
output_path = os.path.join(os.getcwd(),'data','Meteo-France')
for dep in departements:
folder = os.path.join('data','Meteo-France')
file = 'MENSQ_{}_previous-1950-2021.csv'.format(dep.code)
if file in os.listdir(folder):
continue
url = 'https://object.files.data.gouv.fr/meteofrance/data/synchro_ftp/BASE/MENS/MENSQ_{}_previous-1950-2023.csv.gz'.format(dep.code)
subprocess.run('wget "{}" -P {}'.format(url,output_path), shell=True)
return
def get_safran_weather_data(city, period, param=['SSI_Q'],verbose=False):
param_name = ','.join(param)
city_coords = City(city).coordinates
coord = "POINT({} {})".format(city_coords[0],city_coords[1])
projection = "EPSG:4326"
formatage = "CoverageJSON"
date = "{}-01-01/{}-12-31".format(period[0],period[1])
url = "https://api.geosas.fr/edr/collections/safran-isba/position"
params = {
"coords": coord,
"crs": projection,
"parameter-name": param_name,
"f": formatage,
"datetime": date
}
r = requests.get(url, params=params)
if verbose:
print(r.request.url)
if r.ok:
if verbose:
print("requête ok")
data = r.json()
else:
if verbose:
print(f"erreur code : {r.status_code}")
if isinstance(param, str):
date_value = data["domain"]["axes"]["t"]["values"]
values = data["ranges"][param_name]["values"]
df = pd.DataFrame()
df[param_name] = values
df["date"] = pd.to_datetime(date_value, format="%Y-%m-%dT%H-%M-%SZ")
df = df.set_index('date')
if isinstance(param, list):
df = pd.DataFrame()
date_value = data["domain"]["axes"]["t"]["values"]
df["date"] = pd.to_datetime(date_value, format="%Y-%m-%dT%H-%M-%SZ")
for p in param:
values = data["ranges"][p]["values"]
df[p] = values
df = df.set_index('date')
return df
def compute_safran_weather_data(zcl_code):
zcl = Climat(zcl_code)
city = City(zcl.center_prefecture)
coordinates = city.coordinates
# print(daily_data.columns)
if '{}.parquet'.format(zcl_code) not in os.listdir(os.path.join('data','SAFRAN','hourly')):
daily_data = get_safran_weather_data(city.name, period=[2000,2020],param=['SSI_Q','TINF_H_Q','TSUP_H_Q','T_Q'])
daily_data = daily_data.rename(columns={'SSI_Q':'rsds','TINF_H_Q':'tasmin','TSUP_H_Q':'tasmax','T_Q':'tas'})
daily_data['rsds'] = daily_data['rsds'] / 3600 / 1e-4 / 24
hourly_data = pd.DataFrame(index=pd.date_range(daily_data.index[0],'{}-01-01'.format(daily_data.index[-1].year+1),freq='h'))
hourly_data = hourly_data.drop(hourly_data.iloc[-1].name)
dates = hourly_data.copy().index
dates = dates.tz_localize(tz='CET',ambiguous='NaT',nonexistent='NaT')
dates = dates.to_pydatetime()
altitude = [get_altitude_fast(coordinates[1],coordinates[0],t) if t is not pd.NaT else np.nan for t in tqdm.tqdm(dates, desc='altitude')]
azimuth = [float(get_azimuth_fast(coordinates[1],coordinates[0],t)) if t is not pd.NaT else np.nan for t in tqdm.tqdm(dates, desc='azimuth')]
hourly_data['sun_azimuth'] = azimuth
hourly_data['sun_altitude'] = altitude
hourly_data['sunrise'] = hourly_data.sun_altitude.lt(0) & hourly_data.sun_altitude.shift(-1).ge(0)
daily_data['hour_sunrise'] = hourly_data.index[hourly_data['sunrise']].hour.values[:len(daily_data)]
# construction des données de temperature
hourly_data['temp'] = [np.nan]*len(hourly_data)
hour_min_rel_sunrise = 0
hour_max = 15
mask_max = hourly_data.index.hour == hour_max
hourly_data.loc[mask_max,'temp'] = list(daily_data.tasmax.values) + [np.nan]*(len(hourly_data.loc[mask_max,'temp'])-len(daily_data))
mask_min = hourly_data.sunrise.shift(hour_min_rel_sunrise).infer_objects(copy=False).fillna(False)
hourly_data.loc[mask_min,'temp'] = list(daily_data.tasmin.values) + [np.nan]*(len(hourly_data.loc[mask_min,'temp'])-len(daily_data))
# weather_data_modelled = weather_data_modelled[['temperature']]
temperature_sin14R1 = [np.nan]*len(hourly_data)
prev_T, prev_t, next_T, next_t = [np.nan]*4
flag = False
def get_previous_temperature(t, data=hourly_data):
try:
d = hourly_data[hourly_data.index<t].dropna().iloc[-1]
t = d.name
T = d.temp
return t, T
except IndexError:
return np.nan, np.nan
def get_next_temperature(t, data=hourly_data):
try:
d = hourly_data[hourly_data.index>t].dropna().iloc[0]
t = d.name
T = d.temp
return t, T
except IndexError:
return np.nan, np.nan
def compute_temperature_sin14R1(t,prev_T,prev_t,next_T,next_t):
T = (next_T + prev_T)/2 - ((next_T-prev_T)/2 * np.cos(np.pi*(t-prev_t)/(next_t-prev_t)))
return T
for idx,t in tqdm.tqdm(enumerate(hourly_data.index),total=len(hourly_data), desc='temperature'):
T = hourly_data.loc[t].temp
if flag:
prev_t, prev_T = get_previous_temperature(t, hourly_data)
next_t, next_T = get_next_temperature(t, hourly_data)
flag = False
if not pd.isnull(T):
flag = True
temperature_sin14R1[idx] = T
else:
if pd.isnull(prev_t) or pd.isnull(next_t):
continue
temperature_sin14R1[idx] = compute_temperature_sin14R1(t,prev_T,prev_t,next_T,next_t)
hourly_data['temperature_2m'] = temperature_sin14R1
hourly_data.to_parquet(os.path.join('data','SAFRAN','hourly','{}.parquet'.format(zcl_code)))
hourly_data['rsds'] = np.cos(np.deg2rad(90-hourly_data.sun_altitude))
hourly_data['rsds'] = hourly_data['rsds'].clip(lower=0.)
daily_data['rsds_model'] = aggregate_resolution(hourly_data[['rsds']],resolution='D', agg_method='mean')
daily_data['rsds_factor'] = daily_data.rsds/daily_data.rsds_model # *1.09 # caution
rsds_factor = np.asarray([[e]*24 for e in daily_data['rsds_factor']]).flatten()
rsds_factor = list(rsds_factor) + [np.nan]*(len(hourly_data)-len(rsds_factor))
hourly_data['rsds'] = hourly_data['rsds']*np.asarray(rsds_factor)
direct_ratio = 0.749
hourly_data['rsds_direct'] = hourly_data['rsds']*direct_ratio
hourly_data['diffuse_radiation_instant'] = hourly_data['rsds']*(1-direct_ratio)
normal_ratio = np.sin(np.deg2rad(np.maximum(hourly_data['sun_altitude'],0)))
hourly_data['direct_normal_irradiance_instant'] = hourly_data['rsds_direct']/normal_ratio
orientations = ['N','NE','E','SE','S','SW','W','NW','H']
for ori in orientations:
col_coef_dri = 'coefficient_direct_{}_irradiance'.format(ori)
col_coef_dif = 'coefficient_diffuse_{}_irradiance'.format(ori)
col_dri = 'direct_sun_radiation_{}'.format(ori)
col_dif = 'diffuse_sun_radiation_{}'.format(ori)
hourly_data[col_coef_dri] = get_direct_solar_irradiance_projection_ratio(ori, hourly_data.sun_azimuth, hourly_data.sun_altitude)
hourly_data[col_coef_dif] = get_diffuse_solar_irradiance_projection_ratio(ori)
hourly_data[col_dri] = hourly_data.direct_normal_irradiance_instant * hourly_data[col_coef_dri]
hourly_data[col_dif] = hourly_data.diffuse_radiation_instant * hourly_data[col_coef_dif]
hourly_data = hourly_data[['temperature_2m', 'diffuse_radiation_instant',
'direct_normal_irradiance_instant', 'sun_altitude', 'sun_azimuth',
'direct_sun_radiation_N', 'diffuse_sun_radiation_N',
'direct_sun_radiation_NE', 'diffuse_sun_radiation_NE',
'direct_sun_radiation_E', 'diffuse_sun_radiation_E',
'direct_sun_radiation_SE', 'diffuse_sun_radiation_SE',
'direct_sun_radiation_S', 'diffuse_sun_radiation_S',
'direct_sun_radiation_SW', 'diffuse_sun_radiation_SW',
'direct_sun_radiation_W', 'diffuse_sun_radiation_W',
'direct_sun_radiation_NW', 'diffuse_sun_radiation_NW',
'direct_sun_radiation_H', 'diffuse_sun_radiation_H']]
hourly_data.to_parquet(os.path.join('data','SAFRAN','hourly','{}.parquet'.format(zcl_code)))
hourly_data = pd.read_parquet(os.path.join('data','SAFRAN','hourly','{}.parquet'.format(zcl_code)))
hourly_data = hourly_data.fillna(0.)
return hourly_data
def get_safran_hourly_weather_data(zcl_code,period=[2000,2020]):
hourly = compute_safran_weather_data(zcl_code)
hourly = hourly[hourly.index.year.isin(list(range(period[0],period[1]+1)))]
return hourly
#%% ===========================================================================
# Script principal
# =============================================================================
def main():
tic = time.time()
# Défintion de la date du jour
today = pd.Timestamp(date.today()).strftime('%Y%m%d')
# Défintion des dossiers de sortie
output = 'output'
folder = '{}_meteorology'.format(today)
figs_folder = os.path.join(output, folder, 'figs')
# Création des dossiers de sortie
if folder not in os.listdir(output):
os.mkdir(os.path.join(output,folder))
if 'figs' not in os.listdir(os.path.join(output, folder)):
os.mkdir(figs_folder)
# -------------------------------------------------------------------------
#%% Affichage des données météo
if False:
city = 'Paris'
year = 2022
coordinates = get_coordinates(city)
data = open_meteo_historical_data(longitude=coordinates[0], latitude=coordinates[1], year=year)
meteo_units = get_meteo_units(longitude=coordinates[0], latitude=coordinates[1], year=year)
for c in ['temperature_2m','direct_radiation_instant']:
plot_timeserie(data[[c]], labels=['{} ({})'.format(c,meteo_units.get(c))], figsize=(15,5),figs_folder = figs_folder,
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))])
#%% Étude de la température du sol en fonction de la température de surface
if False:
city = 'Marseille'
# city = 'Chaumont'
year = 2021
# year = 2010
# year = 2024
year = 2023
# 2021
variables = ['temperature_2m','soil_temperature_0_to_7cm','soil_temperature_7_to_28cm','soil_temperature_28_to_100cm','soil_temperature_100_to_255cm']
coordinates = get_coordinates(city)
data = open_meteo_historical_data(longitude=coordinates[0], latitude=coordinates[1], year=year, hourly_variables=variables)
data_year_before = open_meteo_historical_data(longitude=coordinates[0], latitude=coordinates[1], year=year-1, hourly_variables=variables)
data = pd.concat([data_year_before, data])
meteo_units = get_meteo_units(longitude=coordinates[0], latitude=coordinates[1], year=year, hourly_variables=variables)
# Modélisation des températures souterraines en fonction des températures de surface
if True:
def ground_temperature(theta_g, t, x, D,h, data,x_stationary=10):
time_ = np.asarray(data.index)
delta_t = (time_[1]-time_[0]) / np.timedelta64(1, 's')
D = D*delta_t
t = min(t,len(data)-1)
theta_e = data.temperature_2m.iloc[int(t)]
te_mean = data.temperature_2m.mean()
# RC = x/h + x**2/D
RC = x**2/D
dtheta_gdt = (1/RC)*(theta_e-theta_g) #+ 1/(x*x_stationary/D-x**2/D) * (te_mean-theta_g)
return dtheta_gdt
def model_ground_temperature(depth_list, data, lambda_th=1.5,cp=1000,rho=2500,h=0.05, res='1h'):
data_res = data.copy()
# si besoin d'augmentaer la résolution temporelle pour éviter l'instabilité d'intégration
data_high_res = pd.DataFrame(index=pd.date_range(data_res.index[0],data_res.index[-1],freq=res))
data_high_res = data_high_res.join(data_res,how='left')
data_high_res = data_high_res.interpolate()
# paramètres thermiques du sol
# lambda_th = 1.5 #W/(m.K) https://energieplus-lesite.be/donnees/enveloppe44/caracteristiques-thermiques-des-sols/
# cp = 1000 #K/(kg.K)
# rho = 2500 #kg/m3
# h = 0.05 #W/(m2.K) https://fr.wikipedia.org/wiki/Coefficient_de_convection_thermique
D = lambda_th/(rho*cp) #m2/s
t = np.arange(0,len(data_high_res))
depth_col_list = []
for depth in tqdm.tqdm(depth_list):
# initialisation en fonction de la profondeur
theta_g0 = get_init_ground_temperature(depth, data_res, second_order=True)
modelled_col = 'modelled_soil_temperature_{:.0f}cm'.format(depth*100)
depth_col_list.append(modelled_col)
data_high_res[modelled_col] = odeint(ground_temperature, theta_g0, t, args=(depth,D,h, data_high_res)).T[0]
hourly_data_high_res = data_high_res.groupby(pd.Grouper(freq='h')).mean()
for col in depth_col_list:
data_res[col] = hourly_data_high_res[col]
return data_res
# Affichage des séries temporelles
if True:
# depth_list = [((3/5)*mh+(2/5)*ml)/100 for ml,mh in [(28,100),(100,255)]]
depth_list = [((2/3)*mh+(1/3)*ml)/100 for ml,mh in [(28,100),(100,255)]]
# depth_list = [((1/2)*mh+(1/2)*ml)/100 for ml,mh in [(28,100),(100,255)]]
ground_data = model_ground_temperature(depth_list, data)
ground_data['kusuda_soil_temperature_{:.0f}cm'.format(depth_list[0]*100)] = get_kusuda_ground_temperature(depth_list[0],data,lambda_th=1.5,cp=1000,rho=2500)
ground_data['kusuda_soil_temperature_{:.0f}cm'.format(depth_list[1]*100)] = get_kusuda_ground_temperature(depth_list[1],data,lambda_th=1.5,cp=1000,rho=2500)
colors = plt.get_cmap('viridis')
color_1 = colors(0.0)
color_2 = colors(0.5)
print(ground_data)
fig,ax = plot_timeserie(ground_data[['soil_temperature_28_to_100cm',
'modelled_soil_temperature_{:.0f}cm'.format(depth_list[0]*100),
'kusuda_soil_temperature_{:.0f}cm'.format(depth_list[0]*100),
'soil_temperature_100_to_255cm',
'modelled_soil_temperature_{:.0f}cm'.format(depth_list[1]*100),
'kusuda_soil_temperature_{:.0f}cm'.format(depth_list[1]*100),
]],
colors = [color_2,color_2,color_2,color_1,color_1,color_1],
labels=['']*6,
linestyles=['-','--',':','-','--',':'],show=False,
figsize=(10,5),figs_folder = figs_folder,
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))])
ax.set_ylabel('Soil temperature (°C)')
ax.plot(ground_data.iloc[0]['soil_temperature_28_to_100cm'],ls='-',color=color_2,label='$d \\in [28,100]~cm$')
ax.plot(ground_data.iloc[0]['soil_temperature_100_to_255cm'],ls='-',color=color_1,label='$d \\in [100,255]~cm$')
# ground_data['kusuda_soil_temperature_{:.0f}cm'.format(0*100)] = get_kusuda_ground_temperature(0,data,lambda_th=1.5,cp=1000,rho=2500)
# ax.plot(ground_data['kusuda_soil_temperature_{:.0f}cm'.format(0*100)],ls=':',color='k',label='0')
# ax.plot(ground_data['temperature_2m'],ls='-',color='k',label='0 data')
# ax2 = ax.twinx()
# ax2.tick_params(right=False)
# ax2.set(yticklabels=[])
r2_data = ground_data[ground_data.index.year == year]
r2_rc_75 = root_mean_squared_error(r2_data['soil_temperature_28_to_100cm'], r2_data['modelled_soil_temperature_{:.0f}cm'.format(depth_list[0]*100)])
r2_rc_150 = root_mean_squared_error(r2_data['soil_temperature_100_to_255cm'], r2_data['modelled_soil_temperature_{:.0f}cm'.format(depth_list[1]*100)])
r2_kusuda_75 = root_mean_squared_error(r2_data['soil_temperature_28_to_100cm'], r2_data['kusuda_soil_temperature_{:.0f}cm'.format(depth_list[0]*100)])
r2_kusuda_150 = root_mean_squared_error(r2_data['soil_temperature_100_to_255cm'], r2_data['kusuda_soil_temperature_{:.0f}cm'.format(depth_list[1]*100)])
print('RMSE')
print('\tRC RMSE {:.0f}cm'.format(depth_list[0]*100), r2_rc_75)
print('\tKusuda RMSE {:.0f}cm'.format(depth_list[0]*100), r2_kusuda_75)
print('\tRC RMSE {:.0f}cm'.format(depth_list[1]*100), r2_rc_150)
print('\tKusuda RMSE {:.0f}cm'.format(depth_list[1]*100), r2_kusuda_150)
ax.plot(ground_data.iloc[0]['soil_temperature_28_to_100cm'],ls='-',color='k',label='Data')
ax.plot(ground_data.iloc[0]['soil_temperature_100_to_255cm'],ls='--',color='k',label='RC Model')
ax.plot(ground_data.iloc[0]['soil_temperature_100_to_255cm'],ls=':',color='k',label='Kusuda & Achenbach Model')
# ax2.legend(loc='upper right')
ax.legend(loc='upper left')
plt.savefig(os.path.join(figs_folder,'{}.png'.format('timeserie_ground_temperature_{}_{}'.format(city,year))),bbox_inches='tight')
plt.show()
# Affichage de la température en fonction de la profondeur à partir des données Open-Météo
if False:
fig, ax = plt.subplots(figsize=(5,5),dpi=300)
dict_col = {4/100:'soil_temperature_0_to_7cm',
18/100:'soil_temperature_7_to_28cm',
64/100:'soil_temperature_28_to_100cm',
178/100:'soil_temperature_100_to_255cm'}
for depth in dict_col.keys():
modelled_col = dict_col.get(depth)
# ax.plot(data[modelled_col].values, [depth]*len(data),ls='',marker='.',color='tab:blue',alpha=0.01)
ax.plot(data[(data.index.month==1)&(data.index.day==1)&(data.index.hour==0)][modelled_col].values, [depth]*len(data[(data.index.month==1)&(data.index.day==1)&(data.index.hour==0)]),ls='',marker='.',color='tab:red',alpha=0.5)
# calibration de xi pour l'estimation de la température initiale
if True:
Y = np.linspace(0,3)
X = [get_init_ground_temperature(y, data) for y in Y]
ax.plot(X,Y,color='k')
ax.set_ylim(ax.get_ylim()[::-1])
depth_list = [((1/2)*mh+(1/2)*ml)/100 for ml,mh in [(28,100),(100,255)]]
ax.plot([data.temperature_2m.median(),data.temperature_2m.median()],[min(depth_list), max(depth_list)],color='k')
plt.show()
# Affichage (moche) de la température en fonction de la profondeur par modélisation
if False:
# liste des profondeur modélisées
depth_list = [x/100 for x in np.linspace(5,1000,20)]
ground_data = model_ground_temperature(depth_list, data)
fig, ax = plt.subplots(figsize=(5,5),dpi=300)
for depth in depth_list:
modelled_col = 'modelled_soil_temperature_{:.0f}cm'.format(depth*100)
ax.plot(ground_data[modelled_col].values, [depth]*len(ground_data),ls='',marker='.',color='tab:blue',alpha=0.01)
ax.set_ylim(ax.get_ylim()[::-1])
ax.plot([ground_data.temperature_2m.median(),ground_data.temperature_2m.median()],[min(depth_list), max(depth_list)],color='k')
ax.set_ylabel('Profondeur (m)')
ax.set_ylabel('Température du sol (°C)')
plt.show()
# Affichage des températures sous terraines avec des moyennes par saison (ou par mois ?)
if True:
season = False
month = True
# liste des profondeur modélisées
depth_list = [x/100 for x in np.linspace(5,1000,30)]
ground_data = model_ground_temperature(depth_list, data)
ground_data = ground_data[ground_data.index.year==year]
if season:
fig, ax = plt.subplots(figsize=(5,5),dpi=300)
seasons_dict = {'DJF':([12,1,2],'tab:blue'),
'MAM':([3,4,5],'tab:green'),
'JJA':([6,7,8],'tab:red'),
'SON':([9,10,11],'tab:orange')}
for season in seasons_dict.keys():
season_months, season_color = seasons_dict.get(season)
season_mean = ground_data[ground_data.index.month.isin(season_months)]
season_mean = pd.DataFrame(season_mean.mean()).T
season_plot = []
for depth in depth_list:
modelled_col = 'modelled_soil_temperature_{:.0f}cm'.format(depth*100)
season_plot.append(season_mean[modelled_col].values[0])
ax.plot(season_plot, depth_list,color=season_color,label=season)
ax.set_ylim(ax.get_ylim()[::-1])
ax.legend()
# ax.plot([ground_data.temperature_2m.median(),ground_data.temperature_2m.median()],[min(depth_list), max(depth_list)],color='k')
ax.set_ylabel('Profondeur (m)')
ax.set_xlabel('Température du sol (°C)')
plt.savefig(os.path.join(figs_folder,'{}.png'.format('modelling_of_ground_temperature_seasons')),bbox_inches='tight')
plt.show()
if month:
fig, ax = plt.subplots(figsize=(5,5),dpi=300)
cmap = plt.colormaps.get_cmap('viridis')
line_styles = ['-',':','--','-.']
month_dict = {pd.to_datetime('2000-{:02d}-01'.format(m)).strftime('%B'):([m],cmap(0.5-np.cos(2*np.pi*(m-1)/12)/2),line_styles[m%4]) for m in range(1,13)}
for month in month_dict.keys():
month_months, month_color, ls_month = month_dict.get(month)
month_mean = ground_data[ground_data.index.month.isin(month_months)]
month_mean = pd.DataFrame(month_mean.mean()).T
month_plot = []
for depth in depth_list:
modelled_col = 'modelled_soil_temperature_{:.0f}cm'.format(depth*100)
month_plot.append(month_mean[modelled_col].values[0])
ax.plot(month_plot, depth_list,color=month_color,ls=ls_month,label=month)
ax.set_ylim(ax.get_ylim()[::-1])
ax.legend()
# ax.plot([ground_data.temperature_2m.median(),ground_data.temperature_2m.median()],[min(depth_list), max(depth_list)],color='k')
ax.set_ylabel('Depth (m)')
ax.set_xlabel('Soil temperature (°C)')
plt.savefig(os.path.join(figs_folder,'{}.png'.format('modelling_of_ground_temperature_months_{}_{}'.format(city,year))),bbox_inches='tight')
plt.show()
# Affichage des données annuelles
if False:
for i,c in enumerate(variables):
if c == variables[0]:
fig, ax = plot_timeserie(data[[c]], labels=['{} ({})'.format(c,meteo_units.get(c))], figsize=(15,5),figs_folder = figs_folder, show=False,
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))])
elif c == variables[-1]:
plot_timeserie(data[[c]], labels=['{} ({})'.format(c,meteo_units.get(c))], figsize=(15,5),figs_folder = figs_folder, show=True, figax=(fig,ax),
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))],save_fig='soil_temperature_{}_{}'.format(city,year))
else:
fig, ax = plot_timeserie(data[[c]], labels=['{} ({})'.format(c,meteo_units.get(c))], figsize=(15,5),figs_folder = figs_folder, show=False,figax=(fig,ax),
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))])
# Affichage des versus plot (diagramme de phase)
if False:
for i,c in enumerate(variables[1:]):
fig,ax = plt.subplots(figsize=(5,5), dpi=300)
ax.plot(data['temperature_2m'],data[c], marker='o',ls='',alpha=0.2)
min_t, max_t = [data.temperature_2m.min(), data.temperature_2m.max()]
ax.set_xlim([min_t, max_t])
ax.set_ylim([min_t, max_t])
ax.plot([min_t, max_t], [min_t, max_t], color='k')
ax.set_ylabel('{} ({})'.format(c,meteo_units.get(c)))
ax.set_xlabel('{} ({})'.format(c,meteo_units.get('temperature_2m')))
ax.set_title('{} ({})'.format(city,year))
plt.show()
#%% Caractérisation et étude du flux solaire par orientation
if False:
variables = ['direct_radiation_instant','diffuse_radiation_instant','direct_normal_irradiance_instant']
city = 'Marseille'
year = 2022
coordinates = get_coordinates(city)
data = open_meteo_historical_data(longitude=coordinates[0], latitude=coordinates[1], year=year, hourly_variables=variables)
meteo_units = get_meteo_units(longitude=coordinates[0], latitude=coordinates[1], year=year, hourly_variables=variables)
# Affichage des données annuelles
if False:
for i,c in enumerate(variables):
plot_timeserie(data[[c]], labels=['{} ({})'.format(c,meteo_units.get(c))], figsize=(15,5),figs_folder = figs_folder, show=True,
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))],save_fig='{}_{}_{}'.format(c,city,year))
# Étude de l'azimuth et de l'élévation
if True:
warnings.simplefilter("ignore")
dates = data.copy().index
dates = dates.tz_localize(tz='CET',ambiguous='NaT',nonexistent='NaT')
altitude = [get_altitude_fast(coordinates[1],coordinates[0],t) if t is not pd.NaT else np.nan for t in dates]
azimuth = [get_azimuth_fast(coordinates[1],coordinates[0],t) if t is not pd.NaT else np.nan for t in dates]
# ajout de la hauteur du soleil (en degrés)
data['sun_altitude'] = altitude
# ajout de l'azimuth du soleil (en degrés)
data['sun_azimuth'] = azimuth
# vérification du lien entre l'irradiance normale et directe
if False:
data.sun_altitude = [max(0,e) for e in data.sun_altitude]
data['verif_sun_direct_irradiance'] = np.sin(np.deg2rad(data.sun_altitude))*data.direct_normal_irradiance_instant
plot_timeserie(data[['verif_sun_direct_irradiance','direct_radiation_instant']], labels=['{} ({})'.format('direct_normal_irradiance_instant',meteo_units.get('direct_normal_irradiance_instant'))]*2, figsize=(15,5),figs_folder = figs_folder, show=True,alpha=0.5,
xlim=[pd.to_datetime('{}-01-01'.format(year)), pd.to_datetime('{}-12-31'.format(year))],save_fig='verif_solar_{}_{}'.format(city,year))
# graphe polaire du parcours du soleil dans l'année
if False:
fig,ax = plt.subplots(dpi=300,figsize=(5,5),subplot_kw={'projection': 'polar'})
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_rlabel_position(0)
ax.set_rlim(bottom=90, top=0)
ax.set_rticks(list(range(0,91,20)))
ax.set_yticklabels(['{}°'.format(e) if e!=0 else '' for e in ax.get_yticks()])
ax.set_xticks(np.pi/180. * np.linspace(0, 360, 12, endpoint=False))
ax.grid(True)
ax.set_xticklabels([{0:'N',90:'E',180:'S',270:'W'}.get(e,'{:.0f}°'.format(e)) for e in np.linspace(0, 360, 12, endpoint=False)])
data_solstice_summer = data[(data.index.day==21)&(data.index.month==6)]
data_solstice_winter = data[(data.index.day==21)&(data.index.month==12)]
ax.plot(2*np.pi/360*data_solstice_summer.sun_azimuth,data_solstice_summer.sun_altitude,color='tab:blue',zorder=3)
ax.plot(2*np.pi/360*data_solstice_winter.sun_azimuth,data_solstice_winter.sun_altitude,color='tab:blue',zorder=3)
ax.fill_between(list(2*np.pi/360*data_solstice_summer.sun_azimuth.values),0,list(data_solstice_summer.sun_altitude.values), alpha=0.2,color='tab:blue')
ax.fill_between(list(2*np.pi/360*data_solstice_winter.sun_azimuth.values),0,list(data_solstice_winter.sun_altitude.values), color='w')
# dessin de l'analemme à 12h UTC (13h en hiver en heure locale)
data_analemme = data.copy()
data_analemme = data_analemme.tz_localize(tz='CET',ambiguous='NaT',nonexistent='NaT').tz_convert('UTC')
data_analemme = data_analemme[(data_analemme.index.hour==12)]
ax.plot(2*np.pi/360*data_analemme.sun_azimuth,data_analemme.sun_altitude,color='tab:blue',lw=1,alpha=0.5,zorder=2)
ax.set_title('{}'.format(city))
plt.savefig(os.path.join(figs_folder,'{}.png'.format('sun_path_{}_{}'.format(city,year))),bbox_inches='tight')
plt.show()
# graphe polaire du parcours du soleil dans l'année (comparaison entre villes)
if True:
variables = ['direct_radiation_instant','diffuse_radiation_instant','direct_normal_irradiance_instant']
year = 2022
city_north = 'Brest'
city_south = 'Nice'
colors = plt.get_cmap('viridis')
color_1 = colors(0.0)
color_2 = colors(0.5)
coordinates_Marseille = get_coordinates(city_south)
coordinates_Lille = get_coordinates(city_north)
data_Lille = open_meteo_historical_data(longitude=coordinates_Lille[0], latitude=coordinates_Lille[1], year=year, hourly_variables=variables)
data_Marseille = open_meteo_historical_data(longitude=coordinates_Marseille[0], latitude=coordinates_Marseille[1], year=year, hourly_variables=variables)
dates_Lille = data_Lille.copy().index
dates_Lille = dates_Lille.tz_localize(tz='CET',ambiguous='NaT',nonexistent='NaT')
altitude_Lille = [get_altitude_fast(coordinates_Lille[1],coordinates_Lille[0],t) if t is not pd.NaT else np.nan for t in dates_Lille]
azimuth_Lille = [get_azimuth_fast(coordinates_Lille[1],coordinates_Lille[0],t) if t is not pd.NaT else np.nan for t in dates_Lille]
data_Lille['sun_altitude'] = altitude_Lille
data_Lille['sun_azimuth'] = azimuth_Lille
dates_Marseille = data_Marseille.copy().index
dates_Marseille = dates_Marseille.tz_localize(tz='CET',ambiguous='NaT',nonexistent='NaT')
altitude_Marseille = [get_altitude_fast(coordinates_Marseille[1],coordinates_Marseille[0],t) if t is not pd.NaT else np.nan for t in dates_Marseille]
azimuth_Marseille = [get_azimuth_fast(coordinates_Marseille[1],coordinates_Marseille[0],t) if t is not pd.NaT else np.nan for t in dates_Marseille]
data_Marseille['sun_altitude'] = altitude_Marseille
data_Marseille['sun_azimuth'] = azimuth_Marseille
fig,ax = plt.subplots(dpi=300,figsize=(5,5),subplot_kw={'projection': 'polar'})
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_rlabel_position(0)
ax.set_rlim(bottom=90, top=0)
ax.set_rticks(list(range(0,91,20)))
ax.set_yticklabels(['{}°'.format(e) if e!=0 else '' for e in ax.get_yticks()])
ax.set_xticks(np.pi/180. * np.linspace(0, 360, 12, endpoint=False))
ax.grid(True)
ax.set_xticklabels([{0:'N',90:'E',180:'S',270:'W'}.get(e,'{:.0f}°'.format(e)) for e in np.linspace(0, 360, 12, endpoint=False)])
data_solstice_summer_Lille = data_Lille[(data_Lille.index.day==21)&(data_Lille.index.month==6)]
data_solstice_winter_Lille = data_Lille[(data_Lille.index.day==21)&(data_Lille.index.month==12)]
data_solstice_summer_Marseille = data_Marseille[(data_Marseille.index.day==21)&(data_Marseille.index.month==6)]
data_solstice_winter_Marseille = data_Marseille[(data_Marseille.index.day==21)&(data_Marseille.index.month==12)]
ax.plot(2*np.pi/360*data_solstice_summer_Lille.sun_azimuth,data_solstice_summer_Lille.sun_altitude,color=color_1,zorder=3)
ax.plot(2*np.pi/360*data_solstice_winter_Lille.sun_azimuth,data_solstice_winter_Lille.sun_altitude,color=color_1,zorder=3)
ax.fill_between(list(2*np.pi/360*data_solstice_summer_Lille.sun_azimuth.values),0,list(data_solstice_summer_Lille.sun_altitude.values), alpha=0.2,color=color_1,label=city_north)
ax.fill_between(list(2*np.pi/360*data_solstice_winter_Lille.sun_azimuth.values),0,list(data_solstice_winter_Lille.sun_altitude.values), color='w')