Nicolas Pierson commited on
^^
Browse files- src/pages/1_Historical_Prices.py +111 -218
src/pages/1_Historical_Prices.py
CHANGED
|
@@ -1,20 +1,23 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
-
import streamlit as st
|
| 3 |
-
import os
|
| 4 |
import boto3
|
| 5 |
import json
|
| 6 |
import io
|
| 7 |
import plotly.colors as pcolors
|
| 8 |
import plotly.express as px
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
| 10 |
AWS_S3_BUCKET = os.getenv("AWS_S3_BUCKET", "oasis-prd-001")
|
| 11 |
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
|
| 12 |
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
|
| 13 |
-
|
| 14 |
ROOT_DIR = "./data/"
|
|
|
|
|
|
|
| 15 |
|
|
|
|
| 16 |
def load_file_s3(object_key: str) -> pd.DataFrame:
|
| 17 |
-
"""Load a file from S3 and return its contents as a pandas DataFrame."""
|
| 18 |
if not AWS_S3_BUCKET or not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
|
| 19 |
raise ValueError(
|
| 20 |
"AWS credentials or bucket name not set in environment variables."
|
|
@@ -25,7 +28,6 @@ def load_file_s3(object_key: str) -> pd.DataFrame:
|
|
| 25 |
aws_access_key_id=AWS_ACCESS_KEY_ID,
|
| 26 |
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
|
| 27 |
)
|
| 28 |
-
|
| 29 |
response = s3_client.get_object(Bucket=AWS_S3_BUCKET, Key=object_key)
|
| 30 |
status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
| 31 |
|
|
@@ -34,142 +36,102 @@ def load_file_s3(object_key: str) -> pd.DataFrame:
|
|
| 34 |
raise ValueError(f"Unsuccessful S3 get_object response. Status - {status}")
|
| 35 |
|
| 36 |
|
|
|
|
| 37 |
def load_geojson_from_s3(object_key: str) -> dict:
|
| 38 |
-
|
| 39 |
-
if
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
)
|
| 43 |
|
| 44 |
s3_client = boto3.client(
|
| 45 |
"s3",
|
| 46 |
aws_access_key_id=AWS_ACCESS_KEY_ID,
|
| 47 |
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
|
| 48 |
)
|
| 49 |
-
|
| 50 |
-
local_file_path = f"{ROOT_DIR}{object_key}"
|
| 51 |
-
if os.path.exists(local_file_path):
|
| 52 |
-
print(
|
| 53 |
-
f"File {local_file_path} already exists locally. Loading from local file."
|
| 54 |
-
)
|
| 55 |
-
with open(local_file_path, "r") as f:
|
| 56 |
-
return json.load(f)
|
| 57 |
-
|
| 58 |
-
print(f"Downloading {local_file_path} from S3 bucket {AWS_S3_BUCKET}.")
|
| 59 |
response = s3_client.get_object(Bucket=AWS_S3_BUCKET, Key=object_key)
|
| 60 |
status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
| 61 |
|
| 62 |
if status == 200:
|
| 63 |
-
print(f"Successful S3 get_object response. Status - {status}")
|
| 64 |
os.makedirs(os.path.dirname(local_file_path), exist_ok=True)
|
| 65 |
with open(local_file_path, "wb") as f:
|
| 66 |
f.write(response["Body"].read())
|
| 67 |
-
print(f"File {local_file_path} downloaded and saved locally.")
|
| 68 |
with open(local_file_path, "r") as f:
|
| 69 |
return json.load(f)
|
| 70 |
-
|
| 71 |
raise ValueError(f"Unsuccessful S3 get_object response. Status - {status}")
|
| 72 |
|
| 73 |
|
| 74 |
@st.cache_data
|
| 75 |
-
def
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
@st.cache_data
|
| 80 |
-
def load_dataset_housing_prices():
|
| 81 |
-
df = load_file_s3("processed/housing/dataset_housing_prices.csv")
|
| 82 |
-
return df
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
#####################################################################
|
| 86 |
-
# Data loading
|
| 87 |
-
#####################################################################
|
| 88 |
-
|
| 89 |
-
dataset_departements_housing_prices = load_dataset_departements_housing_prices()
|
| 90 |
-
departements_geojson = load_geojson_from_s3(
|
| 91 |
-
"processed/referentiel/departements.geojson"
|
| 92 |
-
)
|
| 93 |
-
dataset_housing_prices = load_dataset_housing_prices()
|
| 94 |
-
communes_geojson = load_geojson_from_s3("processed/referentiel/communes.geojson")
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
#####################################################################
|
| 98 |
-
# Graphical representation of the data
|
| 99 |
-
#####################################################################
|
| 100 |
-
def display_choropleth_map(
|
| 101 |
-
df: pd.DataFrame,
|
| 102 |
-
geojson_data: dict,
|
| 103 |
-
):
|
| 104 |
-
dataset_departements_housing_prices = (
|
| 105 |
-
df[df["prixm2moyen"] > 0]
|
| 106 |
-
.groupby(["code_departement", "annee"])["prixm2moyen"]
|
| 107 |
-
.mean()
|
| 108 |
-
.reset_index()
|
| 109 |
)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
"prixm2moyen"
|
| 113 |
-
].min()
|
| 114 |
-
max_actual_departement_prixm2moyen = dataset_departements_housing_prices[
|
| 115 |
-
"prixm2moyen"
|
| 116 |
-
].max()
|
| 117 |
-
|
| 118 |
-
dataset_departements_housing_prices = (
|
| 119 |
-
df.groupby(["code_departement", "annee"])["prixm2moyen"].mean().reset_index()
|
| 120 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
normalized_min_actual = (min_actual_departement_prixm2moyen - color_range_min) / (
|
| 129 |
-
color_range_max - color_range_min
|
| 130 |
)
|
| 131 |
-
normalized_max_actual = (
|
| 132 |
-
|
| 133 |
)
|
| 134 |
|
| 135 |
-
custom_colorscale = []
|
| 136 |
-
# Add the color for missing values
|
| 137 |
-
custom_colorscale.append([0.0, "lightgrey"])
|
| 138 |
-
reversed_rdylgn_colors = pcolors.diverging.RdYlGn[
|
| 139 |
-
::-1
|
| 140 |
-
] # <--- Correct way to reverse
|
| 141 |
-
# Add the reversed RdYlGn colors for the actual data range
|
| 142 |
num_steps = len(reversed_rdylgn_colors)
|
| 143 |
for i, color in enumerate(reversed_rdylgn_colors):
|
| 144 |
normalized_point = normalized_min_actual + (
|
| 145 |
normalized_max_actual - normalized_min_actual
|
| 146 |
) * (i / (num_steps - 1))
|
| 147 |
-
if normalized_point > 0.0:
|
| 148 |
custom_colorscale.append([normalized_point, color])
|
|
|
|
|
|
|
| 149 |
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
fig = px.choropleth_map(
|
| 154 |
-
|
| 155 |
geojson=geojson_data,
|
| 156 |
locations="code_departement",
|
| 157 |
featureidkey="properties.code",
|
| 158 |
color="prixm2moyen",
|
| 159 |
labels={"prixm2moyen": "Average Price per m²"},
|
| 160 |
-
range_color=[
|
| 161 |
-
min_actual_departement_prixm2moyen,
|
| 162 |
-
max_actual_departement_prixm2moyen,
|
| 163 |
-
],
|
| 164 |
color_continuous_scale=custom_colorscale,
|
| 165 |
center={"lat": 46.603354, "lon": 1.888334},
|
| 166 |
zoom=5,
|
| 167 |
opacity=0.75,
|
| 168 |
hover_name="code_departement",
|
| 169 |
-
hover_data={
|
| 170 |
-
"prixm2moyen": ":.0f",
|
| 171 |
-
"annee": True,
|
| 172 |
-
},
|
| 173 |
title="Average Price per Square Meter in French Departments (2015-2024)",
|
| 174 |
height=1400,
|
| 175 |
animation_frame="annee",
|
|
@@ -178,33 +140,25 @@ def display_choropleth_map(
|
|
| 178 |
fig.update_traces(marker_line_width=0)
|
| 179 |
if fig.layout.updatemenus:
|
| 180 |
try:
|
| 181 |
-
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] =
|
| 182 |
-
|
| 183 |
-
)
|
| 184 |
-
fig.layout.updatemenus[0].buttons[0].args[1]["transition"]["duration"] = (
|
| 185 |
-
500 # transition duration
|
| 186 |
-
)
|
| 187 |
except IndexError:
|
| 188 |
-
|
| 189 |
-
"Could not set animation speed. updatemenus structure might be unexpected."
|
| 190 |
-
)
|
| 191 |
else:
|
| 192 |
-
|
| 193 |
-
"No animation updatemenus found. This usually means 'animation_frame' column has too few unique values or data issues."
|
| 194 |
-
)
|
| 195 |
-
|
| 196 |
return fig
|
| 197 |
|
| 198 |
|
|
|
|
| 199 |
def display_choropleth_map_for_department(
|
| 200 |
df: pd.DataFrame,
|
| 201 |
department_code: str,
|
| 202 |
geojson_data: dict,
|
|
|
|
|
|
|
| 203 |
):
|
| 204 |
-
""
|
| 205 |
-
_ = df[df["code_departement"] == department_code]
|
| 206 |
|
| 207 |
-
# Filter the geojson data for the specific department
|
| 208 |
filtered_features = [
|
| 209 |
feature
|
| 210 |
for feature in geojson_data["features"]
|
|
@@ -212,102 +166,40 @@ def display_choropleth_map_for_department(
|
|
| 212 |
]
|
| 213 |
filtered_geojson = {"type": "FeatureCollection", "features": filtered_features}
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
]["prixm2moyen"].min()
|
| 218 |
-
max_actual_country_prixm2moyen = dataset_housing_prices["prixm2moyen"].max()
|
| 219 |
-
|
| 220 |
-
# Color range for the choropleth map
|
| 221 |
-
color_range_min = -1
|
| 222 |
-
color_range_max = max_actual_country_prixm2moyen
|
| 223 |
-
|
| 224 |
-
# Normalize the actual min/max to a 0-1 scale for defining the custom colorscale points
|
| 225 |
-
# The placeholder will be at 0, and actual data will span from (normalized_min) to 1.
|
| 226 |
-
normalized_min_actual = (min_actual_country_prixm2moyen - color_range_min) / (
|
| 227 |
-
color_range_max - color_range_min
|
| 228 |
)
|
| 229 |
-
normalized_max_actual = (max_actual_country_prixm2moyen - color_range_min) / (
|
| 230 |
-
color_range_max - color_range_min
|
| 231 |
-
)
|
| 232 |
-
|
| 233 |
-
custom_colorscale = []
|
| 234 |
-
# Add the color for missing values
|
| 235 |
-
custom_colorscale.append([0.0, "lightgrey"])
|
| 236 |
-
reversed_rdylgn_colors = pcolors.diverging.RdYlGn[
|
| 237 |
-
::-1
|
| 238 |
-
] # <--- Correct way to reverse
|
| 239 |
-
# Add the reversed RdYlGn colors for the actual data range
|
| 240 |
-
num_steps = len(reversed_rdylgn_colors)
|
| 241 |
-
for i, color in enumerate(reversed_rdylgn_colors):
|
| 242 |
-
normalized_point = normalized_min_actual + (
|
| 243 |
-
normalized_max_actual - normalized_min_actual
|
| 244 |
-
) * (i / (num_steps - 1))
|
| 245 |
-
if normalized_point > 0.0: # Ensure we don't overwrite the grey for missing
|
| 246 |
-
custom_colorscale.append([normalized_point, color])
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
center_lon = department_centroid.x
|
| 264 |
-
|
| 265 |
-
# Determine an appropriate zoom level based on the department's bounding box
|
| 266 |
-
minx, miny, maxx, maxy = dissolved_department.total_bounds
|
| 267 |
-
# Estimate zoom level based on the size of the bounding box.
|
| 268 |
-
# This is an approximation and might need fine-tuning.
|
| 269 |
-
# A rough heuristic:
|
| 270 |
-
# Zoom 10 for small departments, 8 for medium, 6 for large.
|
| 271 |
-
# The exact formula depends on your map's projection and desired fit.
|
| 272 |
-
# For a more accurate auto-zoom, you'd typically use a library or a more complex calculation
|
| 273 |
-
# based on the map's pixel dimensions. For simplicity, we can use a basic
|
| 274 |
-
# inverse relationship with the extent.
|
| 275 |
-
width = maxx - minx
|
| 276 |
-
height = maxy - miny
|
| 277 |
-
|
| 278 |
-
# Adjust this scale factor as needed for your specific use case and map size
|
| 279 |
-
if width < 0.2 and height < 0.2:
|
| 280 |
-
zoom_level = 10
|
| 281 |
-
elif width < 0.5 and height < 0.5:
|
| 282 |
-
zoom_level = 9
|
| 283 |
-
else:
|
| 284 |
-
zoom_level = 8
|
| 285 |
-
else:
|
| 286 |
-
# Fallback if no features are found for the department
|
| 287 |
-
print(
|
| 288 |
-
f"No geojson features found for department {department_code}. Using default center and zoom."
|
| 289 |
-
)
|
| 290 |
-
center_lat = 46.603354 # Center of France
|
| 291 |
-
center_lon = 1.888334 # Center of France
|
| 292 |
-
zoom_level = 6
|
| 293 |
|
| 294 |
fig = px.choropleth_map(
|
| 295 |
-
|
| 296 |
geojson=filtered_geojson,
|
| 297 |
locations="code_commune_insee",
|
| 298 |
featureidkey="properties.code",
|
| 299 |
color="prixm2moyen",
|
| 300 |
labels={"prixm2moyen": "Average Price per m²"},
|
| 301 |
-
range_color=[
|
| 302 |
color_continuous_scale=custom_colorscale,
|
| 303 |
center={"lat": center_lat, "lon": center_lon},
|
| 304 |
zoom=zoom_level,
|
| 305 |
opacity=0.75,
|
| 306 |
hover_name="code_commune_insee",
|
| 307 |
-
hover_data={
|
| 308 |
-
"prixm2moyen": ":.0f",
|
| 309 |
-
"annee": True,
|
| 310 |
-
},
|
| 311 |
title=f"Average Price per Square Meter in Department {department_code} (Animated by Year)",
|
| 312 |
height=1400,
|
| 313 |
animation_frame="annee",
|
|
@@ -316,23 +208,16 @@ def display_choropleth_map_for_department(
|
|
| 316 |
fig.update_traces(marker_line_width=0)
|
| 317 |
if fig.layout.updatemenus:
|
| 318 |
try:
|
| 319 |
-
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] =
|
| 320 |
-
|
| 321 |
-
)
|
| 322 |
-
fig.layout.updatemenus[0].buttons[0].args[1]["transition"]["duration"] = (
|
| 323 |
-
500 # transition duration
|
| 324 |
-
)
|
| 325 |
except IndexError:
|
| 326 |
-
|
| 327 |
-
"Could not set animation speed. updatemenus structure might be unexpected."
|
| 328 |
-
)
|
| 329 |
else:
|
| 330 |
-
|
| 331 |
-
"No animation updatemenus found. This usually means 'animation_frame' column has too few unique values or data issues."
|
| 332 |
-
)
|
| 333 |
-
|
| 334 |
return fig
|
| 335 |
|
|
|
|
|
|
|
| 336 |
st.set_page_config(page_title="Oasis", page_icon=":house:", layout="wide")
|
| 337 |
|
| 338 |
st.header("Historical Price - France")
|
|
@@ -342,14 +227,25 @@ st.write(
|
|
| 342 |
"This map shows the average price per square meter in French departments over the years, with a focus on climatic events."
|
| 343 |
)
|
| 344 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
dataset_departements_housing_prices,
|
| 348 |
departements_geojson,
|
| 349 |
)
|
| 350 |
-
|
| 351 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 352 |
-
|
| 353 |
st.write("Hover over the map to see detailed information for each department and year.")
|
| 354 |
st.write(
|
| 355 |
"Missing values are represented in light grey, while actual data is shown in a gradient from red (high prices) to green (low prices)."
|
|
@@ -358,25 +254,22 @@ st.write(
|
|
| 358 |
"Note: The color scale is customized to highlight missing values in light grey, while the actual data is represented using a reversed RdYlGn color scale, where red indicates higher prices and green indicates lower prices."
|
| 359 |
)
|
| 360 |
|
| 361 |
-
|
| 362 |
-
# Dropdown for department selection (this interaction triggers a rerun)
|
| 363 |
st.subheader("Select a Department to View Commune Prices")
|
| 364 |
selected_departement = st.selectbox(
|
| 365 |
"Select a Department",
|
| 366 |
options=dataset_housing_prices["code_departement"].unique(),
|
| 367 |
)
|
| 368 |
|
| 369 |
-
|
| 370 |
dataset_housing_prices,
|
| 371 |
selected_departement,
|
| 372 |
communes_geojson,
|
|
|
|
|
|
|
| 373 |
)
|
| 374 |
|
| 375 |
st.subheader("Average Price per Square Meter in French Communes (2015-2024)")
|
| 376 |
-
st.
|
| 377 |
-
"This map shows the average price per square meter in French communes over the years, with a focus on climatic events."
|
| 378 |
-
)
|
| 379 |
-
st.plotly_chart(fig, use_container_width=True)
|
| 380 |
st.write("Hover over the map to see detailed information for each commune and year.")
|
| 381 |
st.write(
|
| 382 |
"Missing values are represented in light grey, while actual data is shown in a gradient from red (high prices) to green (low prices)."
|
|
@@ -386,4 +279,4 @@ st.write(
|
|
| 386 |
)
|
| 387 |
st.write(
|
| 388 |
"The map is animated by year, allowing you to see how the average price per square meter changes over time."
|
| 389 |
-
)
|
|
|
|
| 1 |
import pandas as pd
|
|
|
|
|
|
|
| 2 |
import boto3
|
| 3 |
import json
|
| 4 |
import io
|
| 5 |
import plotly.colors as pcolors
|
| 6 |
import plotly.express as px
|
| 7 |
+
import geopandas as gpd
|
| 8 |
+
import os
|
| 9 |
+
import streamlit as st
|
| 10 |
|
| 11 |
+
# --- Configuration and Constants ---
|
| 12 |
AWS_S3_BUCKET = os.getenv("AWS_S3_BUCKET", "oasis-prd-001")
|
| 13 |
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
|
| 14 |
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
|
|
|
|
| 15 |
ROOT_DIR = "./data/"
|
| 16 |
+
MISSING_VALUE_PLACEHOLDER = -1
|
| 17 |
+
|
| 18 |
|
| 19 |
+
# --- Data Loading Functions ---
|
| 20 |
def load_file_s3(object_key: str) -> pd.DataFrame:
|
|
|
|
| 21 |
if not AWS_S3_BUCKET or not AWS_ACCESS_KEY_ID or not AWS_SECRET_ACCESS_KEY:
|
| 22 |
raise ValueError(
|
| 23 |
"AWS credentials or bucket name not set in environment variables."
|
|
|
|
| 28 |
aws_access_key_id=AWS_ACCESS_KEY_ID,
|
| 29 |
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
|
| 30 |
)
|
|
|
|
| 31 |
response = s3_client.get_object(Bucket=AWS_S3_BUCKET, Key=object_key)
|
| 32 |
status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
| 33 |
|
|
|
|
| 36 |
raise ValueError(f"Unsuccessful S3 get_object response. Status - {status}")
|
| 37 |
|
| 38 |
|
| 39 |
+
@st.cache_data
|
| 40 |
def load_geojson_from_s3(object_key: str) -> dict:
|
| 41 |
+
local_file_path = f"{ROOT_DIR}{object_key}"
|
| 42 |
+
if os.path.exists(local_file_path):
|
| 43 |
+
with open(local_file_path, "r") as f:
|
| 44 |
+
return json.load(f)
|
|
|
|
| 45 |
|
| 46 |
s3_client = boto3.client(
|
| 47 |
"s3",
|
| 48 |
aws_access_key_id=AWS_ACCESS_KEY_ID,
|
| 49 |
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
|
| 50 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
response = s3_client.get_object(Bucket=AWS_S3_BUCKET, Key=object_key)
|
| 52 |
status = response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
| 53 |
|
| 54 |
if status == 200:
|
|
|
|
| 55 |
os.makedirs(os.path.dirname(local_file_path), exist_ok=True)
|
| 56 |
with open(local_file_path, "wb") as f:
|
| 57 |
f.write(response["Body"].read())
|
|
|
|
| 58 |
with open(local_file_path, "r") as f:
|
| 59 |
return json.load(f)
|
|
|
|
| 60 |
raise ValueError(f"Unsuccessful S3 get_object response. Status - {status}")
|
| 61 |
|
| 62 |
|
| 63 |
@st.cache_data
|
| 64 |
+
def load_all_data():
|
| 65 |
+
dataset_departements_housing_prices = load_file_s3(
|
| 66 |
+
"processed/housing/dataset_departements_housing_prices.csv"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
)
|
| 68 |
+
departements_geojson = load_geojson_from_s3(
|
| 69 |
+
"processed/referentiel/departements.geojson"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
)
|
| 71 |
+
dataset_housing_prices = load_file_s3(
|
| 72 |
+
"processed/housing/dataset_housing_prices.csv"
|
| 73 |
+
)
|
| 74 |
+
communes_geojson = load_geojson_from_s3("processed/referentiel/communes.geojson")
|
| 75 |
+
return (
|
| 76 |
+
dataset_departements_housing_prices,
|
| 77 |
+
departements_geojson,
|
| 78 |
+
dataset_housing_prices,
|
| 79 |
+
communes_geojson,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
|
| 83 |
+
# --- Helper for Color Scale ---
|
| 84 |
+
def _generate_custom_colorscale(min_val, max_val):
|
| 85 |
+
custom_colorscale = [[0.0, "lightgrey"]]
|
| 86 |
+
reversed_rdylgn_colors = pcolors.diverging.RdYlGn[::-1]
|
| 87 |
|
| 88 |
+
normalized_min_actual = (min_val - MISSING_VALUE_PLACEHOLDER) / (
|
| 89 |
+
max_val - MISSING_VALUE_PLACEHOLDER
|
|
|
|
|
|
|
| 90 |
)
|
| 91 |
+
normalized_max_actual = (max_val - MISSING_VALUE_PLACEHOLDER) / (
|
| 92 |
+
max_val - MISSING_VALUE_PLACEHOLDER
|
| 93 |
)
|
| 94 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
num_steps = len(reversed_rdylgn_colors)
|
| 96 |
for i, color in enumerate(reversed_rdylgn_colors):
|
| 97 |
normalized_point = normalized_min_actual + (
|
| 98 |
normalized_max_actual - normalized_min_actual
|
| 99 |
) * (i / (num_steps - 1))
|
| 100 |
+
if normalized_point > 0.0:
|
| 101 |
custom_colorscale.append([normalized_point, color])
|
| 102 |
+
return sorted(custom_colorscale, key=lambda x: x[0])
|
| 103 |
+
|
| 104 |
|
| 105 |
+
# --- Plotly Figure Generation Functions ---
|
| 106 |
+
@st.cache_data
|
| 107 |
+
def display_choropleth_map(df: pd.DataFrame, geojson_data: dict):
|
| 108 |
+
df_agg = (
|
| 109 |
+
df[df["prixm2moyen"] > 0]
|
| 110 |
+
.groupby(["code_departement", "annee"])["prixm2moyen"]
|
| 111 |
+
.mean()
|
| 112 |
+
.reset_index()
|
| 113 |
+
)
|
| 114 |
+
min_actual_prixm2moyen = df_agg["prixm2moyen"].min()
|
| 115 |
+
max_actual_prixm2moyen = df_agg["prixm2moyen"].max()
|
| 116 |
+
|
| 117 |
+
custom_colorscale = _generate_custom_colorscale(
|
| 118 |
+
min_actual_prixm2moyen, max_actual_prixm2moyen
|
| 119 |
+
)
|
| 120 |
|
| 121 |
fig = px.choropleth_map(
|
| 122 |
+
df_agg,
|
| 123 |
geojson=geojson_data,
|
| 124 |
locations="code_departement",
|
| 125 |
featureidkey="properties.code",
|
| 126 |
color="prixm2moyen",
|
| 127 |
labels={"prixm2moyen": "Average Price per m²"},
|
| 128 |
+
range_color=[min_actual_prixm2moyen, max_actual_prixm2moyen],
|
|
|
|
|
|
|
|
|
|
| 129 |
color_continuous_scale=custom_colorscale,
|
| 130 |
center={"lat": 46.603354, "lon": 1.888334},
|
| 131 |
zoom=5,
|
| 132 |
opacity=0.75,
|
| 133 |
hover_name="code_departement",
|
| 134 |
+
hover_data={"prixm2moyen": ":.0f", "annee": True},
|
|
|
|
|
|
|
|
|
|
| 135 |
title="Average Price per Square Meter in French Departments (2015-2024)",
|
| 136 |
height=1400,
|
| 137 |
animation_frame="annee",
|
|
|
|
| 140 |
fig.update_traces(marker_line_width=0)
|
| 141 |
if fig.layout.updatemenus:
|
| 142 |
try:
|
| 143 |
+
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 1500
|
| 144 |
+
fig.layout.updatemenus[0].buttons[0].args[1]["transition"]["duration"] = 500
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
except IndexError:
|
| 146 |
+
st.warning("Could not set animation speed.")
|
|
|
|
|
|
|
| 147 |
else:
|
| 148 |
+
st.warning("No animation updatemenus found.")
|
|
|
|
|
|
|
|
|
|
| 149 |
return fig
|
| 150 |
|
| 151 |
|
| 152 |
+
@st.cache_data
|
| 153 |
def display_choropleth_map_for_department(
|
| 154 |
df: pd.DataFrame,
|
| 155 |
department_code: str,
|
| 156 |
geojson_data: dict,
|
| 157 |
+
min_global_prixm2moyen: float,
|
| 158 |
+
max_global_prixm2moyen: float,
|
| 159 |
):
|
| 160 |
+
df_filtered = df[df["code_departement"] == department_code].copy()
|
|
|
|
| 161 |
|
|
|
|
| 162 |
filtered_features = [
|
| 163 |
feature
|
| 164 |
for feature in geojson_data["features"]
|
|
|
|
| 166 |
]
|
| 167 |
filtered_geojson = {"type": "FeatureCollection", "features": filtered_features}
|
| 168 |
|
| 169 |
+
custom_colorscale = _generate_custom_colorscale(
|
| 170 |
+
min_global_prixm2moyen, max_global_prixm2moyen
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
+
center_lat, center_lon, zoom_level = 46.603354, 1.888334, 6 # Default fallback
|
| 174 |
+
if filtered_features:
|
| 175 |
+
department_gdf = gpd.GeoDataFrame.from_features(filtered_geojson["features"])
|
| 176 |
+
if not department_gdf.empty:
|
| 177 |
+
dissolved_department = department_gdf.dissolve()
|
| 178 |
+
department_centroid = dissolved_department.geometry.centroid.iloc[0]
|
| 179 |
+
center_lat, center_lon = department_centroid.y, department_centroid.x
|
| 180 |
+
minx, miny, maxx, maxy = dissolved_department.total_bounds
|
| 181 |
+
width, height = maxx - minx, maxy - miny
|
| 182 |
+
if width < 0.2 and height < 0.2:
|
| 183 |
+
zoom_level = 10
|
| 184 |
+
elif width < 0.5 and height < 0.5:
|
| 185 |
+
zoom_level = 9
|
| 186 |
+
else:
|
| 187 |
+
zoom_level = 8
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
fig = px.choropleth_map(
|
| 190 |
+
df_filtered,
|
| 191 |
geojson=filtered_geojson,
|
| 192 |
locations="code_commune_insee",
|
| 193 |
featureidkey="properties.code",
|
| 194 |
color="prixm2moyen",
|
| 195 |
labels={"prixm2moyen": "Average Price per m²"},
|
| 196 |
+
range_color=[min_global_prixm2moyen, max_global_prixm2moyen],
|
| 197 |
color_continuous_scale=custom_colorscale,
|
| 198 |
center={"lat": center_lat, "lon": center_lon},
|
| 199 |
zoom=zoom_level,
|
| 200 |
opacity=0.75,
|
| 201 |
hover_name="code_commune_insee",
|
| 202 |
+
hover_data={"prixm2moyen": ":.0f", "annee": True},
|
|
|
|
|
|
|
|
|
|
| 203 |
title=f"Average Price per Square Meter in Department {department_code} (Animated by Year)",
|
| 204 |
height=1400,
|
| 205 |
animation_frame="annee",
|
|
|
|
| 208 |
fig.update_traces(marker_line_width=0)
|
| 209 |
if fig.layout.updatemenus:
|
| 210 |
try:
|
| 211 |
+
fig.layout.updatemenus[0].buttons[0].args[1]["frame"]["duration"] = 1500
|
| 212 |
+
fig.layout.updatemenus[0].buttons[0].args[1]["transition"]["duration"] = 500
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
except IndexError:
|
| 214 |
+
st.warning("Could not set animation speed.")
|
|
|
|
|
|
|
| 215 |
else:
|
| 216 |
+
st.warning("No animation updatemenus found.")
|
|
|
|
|
|
|
|
|
|
| 217 |
return fig
|
| 218 |
|
| 219 |
+
|
| 220 |
+
# --- Streamlit App Layout ---
|
| 221 |
st.set_page_config(page_title="Oasis", page_icon=":house:", layout="wide")
|
| 222 |
|
| 223 |
st.header("Historical Price - France")
|
|
|
|
| 227 |
"This map shows the average price per square meter in French departments over the years, with a focus on climatic events."
|
| 228 |
)
|
| 229 |
|
| 230 |
+
with st.spinner("Loading data and preparing maps..."):
|
| 231 |
+
(
|
| 232 |
+
dataset_departements_housing_prices,
|
| 233 |
+
departements_geojson,
|
| 234 |
+
dataset_housing_prices,
|
| 235 |
+
communes_geojson,
|
| 236 |
+
) = load_all_data()
|
| 237 |
|
| 238 |
+
# Calculate global min/max for the commune-level data for consistent color scaling
|
| 239 |
+
min_global_commune_prixm2moyen = dataset_housing_prices[
|
| 240 |
+
dataset_housing_prices["prixm2moyen"] > 0
|
| 241 |
+
]["prixm2moyen"].min()
|
| 242 |
+
max_global_commune_prixm2moyen = dataset_housing_prices["prixm2moyen"].max()
|
| 243 |
+
|
| 244 |
+
fig_france = display_choropleth_map(
|
| 245 |
dataset_departements_housing_prices,
|
| 246 |
departements_geojson,
|
| 247 |
)
|
| 248 |
+
st.plotly_chart(fig_france, use_container_width=True)
|
|
|
|
|
|
|
| 249 |
st.write("Hover over the map to see detailed information for each department and year.")
|
| 250 |
st.write(
|
| 251 |
"Missing values are represented in light grey, while actual data is shown in a gradient from red (high prices) to green (low prices)."
|
|
|
|
| 254 |
"Note: The color scale is customized to highlight missing values in light grey, while the actual data is represented using a reversed RdYlGn color scale, where red indicates higher prices and green indicates lower prices."
|
| 255 |
)
|
| 256 |
|
|
|
|
|
|
|
| 257 |
st.subheader("Select a Department to View Commune Prices")
|
| 258 |
selected_departement = st.selectbox(
|
| 259 |
"Select a Department",
|
| 260 |
options=dataset_housing_prices["code_departement"].unique(),
|
| 261 |
)
|
| 262 |
|
| 263 |
+
fig_department = display_choropleth_map_for_department(
|
| 264 |
dataset_housing_prices,
|
| 265 |
selected_departement,
|
| 266 |
communes_geojson,
|
| 267 |
+
min_global_commune_prixm2moyen,
|
| 268 |
+
max_global_commune_prixm2moyen,
|
| 269 |
)
|
| 270 |
|
| 271 |
st.subheader("Average Price per Square Meter in French Communes (2015-2024)")
|
| 272 |
+
st.plotly_chart(fig_department, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
| 273 |
st.write("Hover over the map to see detailed information for each commune and year.")
|
| 274 |
st.write(
|
| 275 |
"Missing values are represented in light grey, while actual data is shown in a gradient from red (high prices) to green (low prices)."
|
|
|
|
| 279 |
)
|
| 280 |
st.write(
|
| 281 |
"The map is animated by year, allowing you to see how the average price per square meter changes over time."
|
| 282 |
+
)
|