-
Notifications
You must be signed in to change notification settings - Fork 0
Back : Ajout des données vulnérabilités + commande de génération MVT #153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
146 changes: 146 additions & 0 deletions
146
back/iarbre_data/management/commands/import_vulnerability.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| """Heat vulnerability | ||
|
|
||
| The script assumes that the vulnerability data is stored in a geopackage file located in the 'file_data/vulnerability' directory. | ||
| This geopackage has been produced by Maurine Di Tommaso (Service Climat & Résilience – Direction Environnement, Écologie, Énergie). | ||
| A description of the approach can be found here : https://geoweb.grandlyon.com/portal/apps/storymaps/collections/7e7862ec92694601a7085074dcaf7481?item=3 | ||
| """ | ||
| import geopandas | ||
| import os | ||
|
|
||
| from django.contrib.gis.geos import GEOSGeometry | ||
| from django.core.management import BaseCommand | ||
| from tqdm import tqdm | ||
|
|
||
|
|
||
| from iarbre_data.models import Vulnerability | ||
| from iarbre_data.settings import TARGET_MAP_PROJ, TARGET_PROJ | ||
| from iarbre_data.management.commands.utils import log_progress | ||
|
|
||
|
|
||
| def load_data(): | ||
| """Open the geopackage for vulnerabilty. | ||
|
|
||
| Returns: | ||
| geopandas.GeoDataFrame: The loaded geopackage as a GeoDataFrame. | ||
|
|
||
| Raises: | ||
| FileNotFoundError: If no folder with "vulnerability" in the name is found or no .gpkg file is found in the folder. | ||
| """ | ||
| vulnerability_path = "file_data/vulnerability" | ||
| if not os.path.isdir(vulnerability_path): | ||
| raise FileNotFoundError( | ||
| "No folder for 'vulnerability' found in 'file_data/' directory." | ||
| ) | ||
| gpkg_file = None | ||
| for file in os.listdir(vulnerability_path): | ||
| if file.lower().endswith(".gpkg"): | ||
| gpkg_file = file | ||
| break | ||
| if not gpkg_file: | ||
| raise FileNotFoundError( | ||
| f"No geopackage file found in the folder '{vulnerability_path}'." | ||
| ) | ||
|
|
||
| gpkg_path = os.path.join(vulnerability_path, gpkg_file) | ||
| gdf = geopandas.read_file(gpkg_path, layer="vulnérabilité_fortes_chaleurs") | ||
| gdf.to_crs(TARGET_PROJ, inplace=True) | ||
| gdf_details = geopandas.read_file( | ||
| gpkg_path, layer="Vulnerabilite_fortes_chaleurs_détail" | ||
| ) | ||
| gdf_details.to_crs(TARGET_PROJ, inplace=True) | ||
|
|
||
| merged = gdf.merge( | ||
| gdf_details, on="ID_RSU", suffixes=("", "_details"), validate="one_to_one" | ||
| ) | ||
| merged.drop( | ||
| columns=[ | ||
| "id", | ||
| "commune", | ||
| "ID_RSU", | ||
| "Surface_RSU", | ||
| "NOTE_EXPO_JOUR", | ||
| "NOTE_EXPO_NUIT", | ||
| "NOTE_SENSI_JOUR", | ||
| "NOTE_SENSI_NUIT", | ||
| "NOTE_CAPAF_JOUR", | ||
| "NOTE_CAPAF_NUIT", | ||
| ], | ||
| inplace=True, | ||
| ) | ||
| duplicate_columns = [ | ||
| col | ||
| for col in merged.columns | ||
| if col.endswith("_details") and col[:-8] in merged.columns | ||
| ] | ||
|
|
||
| for col in duplicate_columns: | ||
| original_col = col[:-8] | ||
| if not merged[original_col].equals(merged[col]): | ||
| raise ValueError(f"Mismatch found in column '{original_col}' and '{col}'.") | ||
|
|
||
| merged.drop(columns=duplicate_columns, inplace=True) | ||
|
|
||
| def make_valid(geometry): | ||
| """Fix minor topology errors, like Polygon not closed.""" | ||
| if geometry and not geometry.is_valid: | ||
| return geometry.buffer(0) | ||
| return geometry | ||
|
|
||
| merged["geometry"] = merged["geometry"].apply(make_valid) | ||
| merged["map_geometry"] = merged.geometry.to_crs(TARGET_MAP_PROJ) | ||
| merged["map_geometry"] = merged["map_geometry"].apply(make_valid) | ||
|
|
||
| merged.fillna( | ||
| 0, inplace=True | ||
| ) # Columns ['majic_Log_av1949', 'majic_Log_1949_1989', | ||
| # 'majic_Log_ap1990', 'majic_nlogh', 'majic_stoth', 'majic_slocal', | ||
| # 'majic_nloghmais', 'majic_nloghappt', 'siret_densite_emploi'] contains NaN because | ||
| # these data (economical indices) are missing in water, forest, etc. | ||
| # For all this values 0 means absence. | ||
|
|
||
| return merged | ||
|
|
||
|
|
||
| def save_geometries(vulnearbility_datas: geopandas.GeoDataFrame) -> None: | ||
| """Save vulnerability data to the database. | ||
|
|
||
| Args: | ||
| vulnearbility_datas (GeoDataFrame): GeoDataFrame to save to the database. | ||
|
|
||
| Returns: | ||
| None | ||
| """ | ||
| batch_size = 10000 | ||
| for start in tqdm(range(0, len(vulnearbility_datas), batch_size)): | ||
| end = start + batch_size | ||
| batch = vulnearbility_datas.iloc[start:end] | ||
| Vulnerability.objects.bulk_create( | ||
| [ | ||
| Vulnerability( | ||
| geometry=GEOSGeometry(data["geometry"].wkt), | ||
| map_geometry=GEOSGeometry(data["map_geometry"].wkt), | ||
| vulnerability_index_day=data["VULNERABILITE_JOUR"], | ||
| vulnerability_index_night=data["VULNERABILITE_NUIT"], | ||
| expo_index_day=data["EXPO_JOUR"], | ||
| expo_index_night=data["EXPO_NUIT"], | ||
| capaf_index_day=data["CAPAF_JOUR"], | ||
| capaf_index_night=data["CAPAF_NUIT"], | ||
| sensibilty_index_day=data["SENSI_JOUR"], | ||
| sensibilty_index_night=data["SENSI_NUIT"], | ||
| ) | ||
| for _, data in batch.iterrows() | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| class Command(BaseCommand): | ||
| help = "Load heat vulnerability data in the DB." | ||
|
|
||
| def handle(self, *args, **options): | ||
| """Load heat vulnerability data in the DB.""" | ||
| log_progress("Remove existing data") | ||
| print(Vulnerability.objects.all().delete()) | ||
| log_progress("Loading data") | ||
| lcz_data = load_data() | ||
| log_progress("Saving data") | ||
| save_geometries(lcz_data) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
back/iarbre_data/migrations/0020_vulnerability_alter_mvttile_datatype.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| # Generated by Django 5.1.5 on 2025-03-26 09:50 | ||
|
|
||
| import django.contrib.gis.db.models.fields | ||
| from django.db import migrations, models | ||
|
|
||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| dependencies = [ | ||
| ("iarbre_data", "0019_merge_20250310_1025"), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.CreateModel( | ||
| name="Vulnerability", | ||
| fields=[ | ||
| ( | ||
| "id", | ||
| models.BigAutoField( | ||
| auto_created=True, | ||
| primary_key=True, | ||
| serialize=False, | ||
| verbose_name="ID", | ||
| ), | ||
| ), | ||
| ( | ||
| "geometry", | ||
| django.contrib.gis.db.models.fields.PolygonField(srid=2154), | ||
| ), | ||
| ( | ||
| "map_geometry", | ||
| django.contrib.gis.db.models.fields.PolygonField( | ||
| blank=True, null=True, srid=3857 | ||
| ), | ||
| ), | ||
| ("vulnerability_index_day", models.FloatField(null=True)), | ||
| ("vulnerability_index_night", models.FloatField(null=True)), | ||
| ("expo_index_day", models.FloatField(null=True)), | ||
| ("expo_index_night", models.FloatField(null=True)), | ||
| ("capaf_index_day", models.FloatField(null=True)), | ||
| ("capaf_index_night", models.FloatField(null=True)), | ||
| ("sensibilty_index_day", models.FloatField(null=True)), | ||
| ("sensibilty_index_night", models.FloatField(null=True)), | ||
| ], | ||
| ), | ||
| migrations.AlterField( | ||
| model_name="mvttile", | ||
| name="datatype", | ||
| field=models.CharField( | ||
| choices=[ | ||
| ("lcz", "LCZ"), | ||
| ("plantability", "Plantability"), | ||
| ("vulnerability", "Vulnerability"), | ||
| ], | ||
| default="plantability", | ||
| max_length=50, | ||
| ), | ||
| ), | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Joli !