File size: 14,583 Bytes
61e4fc2
 
 
 
 
 
 
 
bfa0967
787f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e4fc2
2914aec
a8dd096
 
 
61e4fc2
bfa0967
61e4fc2
 
 
 
 
 
 
 
 
bfa0967
61e4fc2
 
 
 
 
 
787f4ea
61e4fc2
 
 
 
787f4ea
 
 
bfa0967
61e4fc2
 
 
bfa0967
 
787f4ea
 
 
 
 
bfa0967
 
787f4ea
 
bfa0967
787f4ea
 
 
bfa0967
 
787f4ea
 
 
 
bfa0967
787f4ea
 
 
bfa0967
787f4ea
 
 
 
 
bfa0967
 
787f4ea
 
bfa0967
787f4ea
 
 
bfa0967
 
787f4ea
bfa0967
 
 
 
 
787f4ea
bfa0967
787f4ea
bfa0967
 
 
787f4ea
 
 
bfa0967
 
 
 
 
 
 
787f4ea
a8dd096
787f4ea
 
 
 
 
bfa0967
 
 
 
 
 
 
 
 
787f4ea
a8dd096
787f4ea
 
 
 
 
 
bfa0967
 
787f4ea
bfa0967
787f4ea
 
 
bfa0967
 
787f4ea
 
 
a8dd096
 
 
 
 
 
 
787f4ea
 
 
 
 
 
 
a8dd096
 
 
 
 
 
 
 
 
787f4ea
 
 
 
 
 
 
a8dd096
bfa0967
 
787f4ea
 
 
 
 
 
61e4fc2
 
bfa0967
 
61e4fc2
787f4ea
 
a8dd096
787f4ea
bfa0967
 
787f4ea
 
 
 
 
 
bfa0967
 
 
 
 
787f4ea
 
 
bfa0967
 
 
 
 
 
61e4fc2
 
 
 
a8dd096
 
bfa0967
61e4fc2
 
 
 
 
 
bfa0967
61e4fc2
 
 
 
 
bfa0967
61e4fc2
 
a8dd096
2914aec
bfa0967
a8dd096
 
 
787f4ea
a8dd096
787f4ea
61e4fc2
 
 
787f4ea
61e4fc2
 
 
 
 
 
 
 
 
 
 
787f4ea
61e4fc2
 
 
 
 
787f4ea
61e4fc2
 
787f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfa0967
e7cdd9d
 
a8dd096
 
 
61e4fc2
a8dd096
 
 
 
 
 
bfa0967
a8dd096
 
 
bfa0967
a8dd096
 
61e4fc2
 
 
bfa0967
 
a8dd096
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
import pandas as pd  # stress hydrique and rendement, besoin en eau
import plotly.graph_objects as go
from typing import List
import plotly.express as px
from data_pipelines.historical_weather_data import (
    download_historical_weather_data,
    aggregate_hourly_weather_data,
)
import os
from forecast import get_forecast_data
from compute_et0_adjusted import compute_et0


def water_deficit(df, latitude, longitude, shading_coef=0, historic=True):
    preprocessed_data = df.copy()
    preprocessed_data["irradiance"] = preprocessed_data[
        "Surface Downwelling Shortwave Radiation (W/m²)"
    ] * (1 - shading_coef)
    preprocessed_data["air_temperature_min"] = preprocessed_data[
        "Daily Minimum Near Surface Air Temperature (°C)"
    ]
    preprocessed_data["air_temperature_max"] = preprocessed_data[
        "Daily Maximum Near Surface Air Temperature (°C)"
    ]
    if historic == True:
        preprocessed_data["relative_humidity_min"] = preprocessed_data[
            "Relative Humidity_min"
        ]
        preprocessed_data["relative_humidity_max"] = preprocessed_data[
            "Relative Humidity_max"
        ]
    else:
        preprocessed_data["relative_humidity_min"] = preprocessed_data[
            "Relative Humidity (%)"
        ]
        preprocessed_data["relative_humidity_max"] = preprocessed_data[
            "Relative Humidity (%)"
        ]
    preprocessed_data["wind_speed"] = preprocessed_data["Near Surface Wind Speed (m/s)"]

    # Convert 'time' to datetime and calculate Julian day
    preprocessed_data["time"] = pd.to_datetime(
        preprocessed_data["time"], errors="coerce"
    )
    preprocessed_data["month"] = preprocessed_data["time"].dt.month
    preprocessed_data["day_of_year"] = preprocessed_data["time"].dt.dayofyear

    # Compute ET0
    et0 = compute_et0(preprocessed_data, latitude, longitude)
    preprocessed_data["Evaporation (mm/day)"] = et0
    preprocessed_data["Evaporation (mm/day)"] = preprocessed_data[
        "Evaporation (mm/day)"
    ].clip(lower=0)
    # Convert Precipitation from kg/m²/s to mm/day

    preprocessed_data["Precipitation (mm/day)"] = (
        86400 * preprocessed_data["Precipitation (kg m-2 s-1)"]
    )

    # Calculate Water Deficit: Water Deficit = ET0 - P + M
    preprocessed_data["Water Deficit (mm/day)"] = (
        preprocessed_data["Evaporation (mm/day)"]
        - preprocessed_data["Precipitation (mm/day)"]
        + 4.5
    )

    return preprocessed_data


def concatenate_historic_forecast(
    historic, forecast, cols_to_keep, value_period_col="forecast scénario modéré"
):
    historic["period"] = "historique"
    forecast["period"] = value_period_col
    historic = historic[cols_to_keep]
    forecast = forecast[cols_to_keep]
    full_data = pd.concat([historic, forecast])
    return full_data


def visualize_climate(
    moderate: pd.DataFrame,
    historic: pd.DataFrame,
    pessimist: pd.DataFrame,
    x_axis="year",
    column: str = "Precipitation (mm)",
    cols_to_keep: List[str] = [
        "Precipitation (mm)",
        "Near Surface Air Temperature (°C)",
        "Surface Downwelling Shortwave Radiation (W/m²)",
        "Water Deficit (mm/day)",
        "year",
        "period",
    ],
):
    concatenated_moderate = concatenate_historic_forecast(
        historic, moderate, cols_to_keep
    )
    concatenated_moderate = concatenated_moderate.sort_values(by=x_axis)  # Ensure order

    fig = go.Figure()

    if column == "Precipitation (mm)":
        for condition_value in concatenated_moderate["period"].unique():
            segment = concatenated_moderate[
                concatenated_moderate["period"] == condition_value
            ]
            avg_precipitation = segment.groupby(x_axis)[column].mean().reset_index()

            fig.add_trace(
                go.Bar(
                    x=avg_precipitation[x_axis],
                    y=avg_precipitation[column],
                    name=f"{condition_value}",
                    marker=dict(
                        color="blue" if condition_value == "historique" else "purple"
                    ),
                )
            )

        concatenated_pessimist = concatenate_historic_forecast(
            historic, pessimist, cols_to_keep, "forecast scénario pessimiste"
        )
        concatenated_pessimist = concatenated_pessimist.sort_values(by=x_axis)
        concatenated_pessimist = concatenated_pessimist[
            concatenated_pessimist["period"] != "historique"
        ]
        for condition_value in concatenated_pessimist["period"].unique():
            segment = concatenated_pessimist[
                concatenated_pessimist["period"] == condition_value
            ]
            avg_precipitation = segment.groupby(x_axis)[column].mean().reset_index()

            fig.add_trace(
                go.Bar(
                    x=avg_precipitation[x_axis],
                    y=avg_precipitation[column],
                    name=f"{condition_value}",
                    marker=dict(
                        color="orange" if condition_value != "historique" else "blue"
                    ),
                )
            )

        # Update layout for bar chart
        fig.update_layout(
            title=f"Moyenne de {column} par année",
            xaxis_title="Année",  # Set the x-axis title to Year
            yaxis_title="Précipitation (mm)",  # Set the y-axis title to Precipitation
            barmode="group",  # Group bars for different conditions
        )

    else:
        # For other columns, continue with the line plot as before
        for condition_value in concatenated_moderate["period"].unique():
            segment = concatenated_moderate[
                concatenated_moderate["period"] == condition_value
            ]
            if condition_value == "historique":
                fig.add_trace(
                    go.Scatter(
                        x=segment[x_axis],  # Years on x-axis
                        y=segment[column],  # Precipitation values on y-axis
                        mode="lines",
                        name=f"{condition_value}",
                        legendgroup="group1",
                        showlegend=False,
                        line=dict(
                            color=(
                                "blue" if condition_value == "historique" else "purple"
                            )
                        ),
                    )
                )
            else:
                fig.add_trace(
                    go.Scatter(
                        x=segment[x_axis],  # Years on x-axis
                        y=segment[column],  # Precipitation values on y-axis
                        mode="lines",
                        name=f"{condition_value}",
                        legendgroup="group2",
                        showlegend=False,
                        line=dict(
                            color=(
                                "blue" if condition_value == "historique" else "purple"
                            ),
                            dash="dot",
                        ),
                    )
                )

        # Continue with pessimistic data as in the original function...
        concatenated_pessimist = concatenate_historic_forecast(
            historic, pessimist, cols_to_keep, "forecast scénario pessimiste"
        )
        concatenated_pessimist = concatenated_pessimist.sort_values(by=x_axis)
        for condition_value in concatenated_pessimist["period"].unique():
            segment = concatenated_pessimist[
                concatenated_pessimist["period"] == condition_value
            ]
            if condition_value == "historique":
                fig.add_trace(
                    go.Scatter(
                        x=segment[x_axis],  # Years on x-axis
                        y=segment[column],  # Precipitation values on y-axis
                        mode="lines",
                        name=f"{condition_value}",
                        legendgroup="group1",
                        line=dict(
                            color=(
                                "blue" if condition_value == "historique" else "orange"
                            ),
                            dash="dot" if condition_value != "historique" else None,
                        ),
                    )
                )
            else:
                fig.add_trace(
                    go.Scatter(
                        x=segment[x_axis],  # Years on x-axis
                        y=segment[column],  # Precipitation values on y-axis
                        mode="lines",
                        name=f"{condition_value}",
                        legendgroup="group3",
                        line=dict(
                            color=(
                                "blue" if condition_value == "historique" else "orange"
                            ),
                            dash="dot" if condition_value != "historique" else None,
                        ),
                    )
                )
        # Interpolation for the pessimistic scenario...
        interpolation_pessimist = concatenated_pessimist[
            concatenated_pessimist[x_axis] > 2023
        ]
        interpolation_pessimist = interpolation_pessimist[
            interpolation_pessimist[x_axis] <= 2025
        ]
        fig.add_trace(
            go.Scatter(
                x=interpolation_pessimist[x_axis],
                y=interpolation_pessimist[column].interpolate(),
                mode="lines",
                name="forecast scénario pessimiste",
                legendgroup="group3",
                showlegend=False,
                line=dict(color="orange", dash="dot"),
            ),
        )
        interpolation_moderate = concatenated_moderate[
            concatenated_moderate[x_axis] > 2023
        ]
        interpolation_moderate = interpolation_moderate[
            interpolation_moderate[x_axis] <= 2025
        ]
        fig.add_trace(
            go.Scatter(
                x=interpolation_moderate[x_axis],
                y=interpolation_moderate[column].interpolate(),
                mode="lines",
                name="forecast scénario modéré",
                legendgroup="group2",
                line=dict(color="purple", dash="dot"),
            ),
        )
        fig.update_layout(
            title=f"Historique et Forecast pour {column}",
            xaxis_title="Year",  # Set the x-axis title to Year
            yaxis_title=column,  # Set the y-axis title to Precipitation
        )

    return fig


def aggregate_yearly(df, col_to_agg, operation="mean"):
    df[col_to_agg] = df.groupby("year")[col_to_agg].transform(operation)
    return df


def generate_plots(
    moderate: pd.DataFrame,
    historic: pd.DataFrame,
    pessimist: pd.DataFrame,
    x_axes: List[str],
    cols_to_plot: List[str],
):
    plots = []
    for i, col in enumerate(cols_to_plot):
        plots.append(visualize_climate(moderate, historic, pessimist, x_axes[i], col))
    return plots


def get_plots():
    cols_to_plot = [
        "Precipitation (mm)",
        "Near Surface Air Temperature (°C)",
        "Surface Downwelling Shortwave Radiation (W/m²)",
        'Water Deficit (mm/day)'
    ]
    cols_to_keep: List[str] = [
        "Precipitation (mm)",
        "Near Surface Air Temperature (°C)",
        "Surface Downwelling Shortwave Radiation (W/m²)",
        "Water Deficit (mm/day)",
        "year",
        "period",
    ]
    x_axes = ["year"] * len(cols_to_plot)
    latitude = 47
    longitude = 5
    start_year = 2000
    end_year = 2025

    df = download_historical_weather_data(latitude, longitude, start_year, end_year)
    historic = aggregate_hourly_weather_data(df)
    historic= historic.reset_index()
    historic = historic.rename(
        columns={
            "precipitation": "Precipitation (mm)",
            "air_temperature_mean": "Near Surface Air Temperature (°C)",
            "irradiance": "Surface Downwelling Shortwave Radiation (W/m²)",
            'index': 'time'
        }
    )
    historic["time"] = pd.to_datetime(historic["time"])
    historic = historic.sort_values('time')
    historic = historic[historic["time"]<"2025-01-01"]
    historic = historic.rename(columns={"air_temperature_min":"Daily Minimum Near Surface Air Temperature (°C)",
                                        "air_temperature_max":"Daily Maximum Near Surface Air Temperature (°C)",
                                        "relative_humidity_min": 'Relative Humidity_min',
                                        "relative_humidity_max": 'Relative Humidity_max',
                                        "wind_speed":"Near Surface Wind Speed (m/s)",
                                        'Precipitation (mm)':'Precipitation (kg m-2 s-1)'
                                        })
    historic["Precipitation (kg m-2 s-1)"] = historic["Precipitation (kg m-2 s-1)"]/3600

    historic = water_deficit(historic,latitude,longitude)
    historic = historic.rename(columns={'Precipitation (kg m-2 s-1)':'Precipitation (mm)'
                                        })
    historic['Precipitation (mm)'] = historic['Precipitation (mm)']*3600

    moderate = get_forecast_data(latitude, longitude, "moderate")
    pessimist = get_forecast_data(latitude, longitude, "pessimist")
    moderate = moderate.rename(
        columns={"Precipitation (kg m-2 s-1)": "Precipitation (mm)"}
    )
    moderate["time"] = pd.to_datetime(moderate["time"])
    moderate = moderate.sort_values("time")
    moderate["year"] = moderate["time"].dt.year
    moderate["Precipitation (mm)"] = moderate["Precipitation (mm)"] * 31536000
    pessimist = pessimist.rename(
        columns={"Precipitation (kg m-2 s-1)": "Precipitation (mm)"}
    )
    pessimist["time"] = pd.to_datetime(pessimist["time"])
    pessimist = pessimist.sort_values("time")
    pessimist["year"] = pessimist["time"].dt.year
    pessimist["Precipitation (mm)"] = pessimist["Precipitation (mm)"] * 31536000
    pessimist["period"] = "forecast scénario pessimiste"
    historic["year"] = historic["time"].dt.year
    historic["Precipitation (mm)"] = historic["Precipitation (mm)"] * 8760.0
    for col in cols_to_plot:
        moderate = aggregate_yearly(moderate, col)
        historic = aggregate_yearly(historic, col)
        pessimist = aggregate_yearly(pessimist, col)
    plots = generate_plots(moderate, historic, pessimist, x_axes, cols_to_plot)
    return plots