def soilOccupationChange(input_plot_vector, output_plot_vector, footprint_vector, input_tx_files_list, evolutions_list=['0:1:11000:10:50:and', '0:1:12000:10:50:and', '0:1:21000:10:50:and', '0:1:22000:10:50:and', '0:1:23000:10:50:and'], class_label_dico={11000:'Bati', 12000:'Route', 21000:'SolNu', 22000:'Eau', 23000:'Vegetation'}, epsg=2154, no_data_value=0, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster='.tif', extension_vector='.shp', postgis_ip_host='localhost', postgis_num_port=5432, postgis_user_name='postgres', postgis_password='******', postgis_database_name='database', postgis_schema_name='public', postgis_encoding='latin1', path_time_log='', save_results_intermediate=False, overwrite=True): if debug >= 3: print('\n' + bold + green + "Evolution de l'OCS par parcelle - Variables dans la fonction :" + endC) print(cyan + " soilOccupationChange() : " + endC + "input_plot_vector : " + str(input_plot_vector) + endC) print(cyan + " soilOccupationChange() : " + endC + "output_plot_vector : " + str(output_plot_vector) + endC) print(cyan + " soilOccupationChange() : " + endC + "footprint_vector : " + str(footprint_vector) + endC) print(cyan + " soilOccupationChange() : " + endC + "input_tx_files_list : " + str(input_tx_files_list) + endC) print(cyan + " soilOccupationChange() : " + endC + "evolutions_list : " + str(evolutions_list) + endC) print(cyan + " soilOccupationChange() : " + endC + "class_label_dico : " + str(class_label_dico) + endC) print(cyan + " soilOccupationChange() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + " soilOccupationChange() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + " soilOccupationChange() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + " soilOccupationChange() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + " soilOccupationChange() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + " soilOccupationChange() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + " soilOccupationChange() : " + endC + "postgis_ip_host : " + str(postgis_ip_host) + endC) print(cyan + " soilOccupationChange() : " + endC + "postgis_num_port : " + str(postgis_num_port) + endC) print(cyan + " soilOccupationChange() : " + endC + "postgis_user_name : " + str(postgis_user_name) + endC) print(cyan + " soilOccupationChange() : " + endC + "postgis_password : "******" soilOccupationChange() : " + endC + "postgis_database_name : " + str(postgis_database_name) + endC) print(cyan + " soilOccupationChange() : " + endC + "postgis_schema_name : " + str(postgis_schema_name) + endC) print(cyan + " soilOccupationChange() : " + endC + "postgis_encoding : " + str(postgis_encoding) + endC) print(cyan + " soilOccupationChange() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + " soilOccupationChange() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + " soilOccupationChange() : " + endC + "overwrite : " + str(overwrite) + endC + '\n') # Définition des constantes EXTENSION_TEXT = '.txt' SUFFIX_TEMP = '_temp' SUFFIX_CUT = '_cut' AREA_FIELD = 'st_area' GEOM_FIELD = 'geom' # Mise à jour du log starting_event = "soilOccupationChange() : Début du traitement : " timeLine(path_time_log, starting_event) print(cyan + "soilOccupationChange() : " + bold + green + "DEBUT DES TRAITEMENTS" + endC + '\n') # Définition des variables 'basename' output_plot_basename = os.path.splitext(os.path.basename(output_plot_vector))[0] # Définition des variables temp temp_directory = os.path.dirname(output_plot_vector) + os.sep + output_plot_basename + SUFFIX_TEMP plot_vector_cut = temp_directory + os.sep + output_plot_basename + SUFFIX_CUT + extension_vector # Définition des variables PostGIS plot_table = output_plot_basename.lower() # Fichier .txt associé au fichier vecteur de sortie, sur la liste des évolutions quantifiées output_evolution_text_file = os.path.splitext(output_plot_vector)[0] + EXTENSION_TEXT # Nettoyage des traitements précédents if debug >= 3: print(cyan + "soilOccupationChange() : " + endC + "Nettoyage des traitements précédents." + endC + '\n') removeVectorFile(output_plot_vector, format_vector=format_vector) removeFile(output_evolution_text_file) cleanTempData(temp_directory) dropDatabase(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name) ############# # Etape 0/2 # Préparation des traitements ############# print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 0/2 - Début de la préparation des traitements." + endC + '\n') # Découpage du parcellaire à la zone d'étude cutVector(footprint_vector, input_plot_vector, plot_vector_cut, overwrite=overwrite, format_vector=format_vector) # Récupération du nom des champs dans le fichier source (pour isoler les champs nouvellement créés par la suite, et les renommer) attr_names_list_origin = getAttributeNameList(plot_vector_cut, format_vector=format_vector) new_attr_names_list_origin = attr_names_list_origin # Préparation de PostGIS createDatabase(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name) print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 0/2 - Fin de la préparation des traitements." + endC + '\n') ############# # Etape 1/2 # Calculs des statistiques à tx ############# print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 1/2 - Début des calculs des statistiques à tx." + endC + '\n') len_tx = len(input_tx_files_list) tx = 0 # Boucle sur les fichiers d'entrés à t0+x for input_tx_file in input_tx_files_list: if debug >= 3: print(cyan + "soilOccupationChange() : " + endC + bold + "Calcul des statistiques à tx %s/%s." % (tx+1, len_tx) + endC + '\n') # Statistiques OCS par parcelle statisticsVectorRaster(input_tx_file, plot_vector_cut, "", 1, True, False, False, [], [], class_label_dico, path_time_log, clean_small_polygons=True, format_vector=format_vector, save_results_intermediate=save_results_intermediate, overwrite=overwrite) # Récupération du nom des champs dans le fichier parcellaire (avec les champs créés précédemment dans CVR) attr_names_list_tx = getAttributeNameList(plot_vector_cut, format_vector=format_vector) # Isolement des nouveaux champs issus du CVR fields_name_list = [] for attr_name in attr_names_list_tx: if attr_name not in new_attr_names_list_origin: fields_name_list.append(attr_name) # Gestion des nouveaux noms des champs issus du CVR new_fields_name_list = [] for field_name in fields_name_list: new_field_name = 't%s_' % tx + field_name new_field_name = new_field_name[:10] new_fields_name_list.append(new_field_name) new_attr_names_list_origin.append(new_field_name) # Renommage des champs issus du CVR, pour le relancer par la suite sur d'autres dates renameFieldsVector(plot_vector_cut, fields_name_list, new_fields_name_list, format_vector=format_vector) tx += 1 print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 1/2 - Fin des calculs des statistiques à tx." + endC + '\n') ############# # Etape 2/2 # Caractérisation des changements ############# print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 2/2 - Début de la caractérisation des changements." + endC + '\n') # Pré-traitements dans PostGIS plot_table = importVectorByOgr2ogr(postgis_database_name, plot_vector_cut, plot_table, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name, epsg=epsg, codage=postgis_encoding) connection = openConnection(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name) # Requête SQL pour le calcul de la surface des parcelles sql_query = "ALTER TABLE %s ADD COLUMN %s REAL;\n" % (plot_table, AREA_FIELD) sql_query += "UPDATE %s SET %s = ST_Area(%s);\n" % (plot_table, AREA_FIELD, GEOM_FIELD) # Boucle sur les évolutions à quantifier temp_field = 1 for evolution in evolutions_list: evolution_split = evolution.split(':') idx_bef = int(evolution_split[0]) idx_aft = int(evolution_split[1]) label = int(evolution_split[2]) evol = abs(int(evolution_split[3])) evol_s = abs(int(evolution_split[4])) combi = evolution_split[5] class_name = class_label_dico[label] def_evo_field = "def_evo_%s" % str(temp_field) if debug >= 3: print(cyan + "soilOccupationChange() : " + endC + bold + "Caractérisation des changements t%s/t%s pour la classe '%s' (%s)." % (idx_bef, idx_aft, class_name, label) + endC + '\n') if evol != 0 or evol_s != 0: # Gestion de l'évolution via le taux evol_str = str(evol) + ' %' evo_field = "evo_%s" % str(temp_field) t0_field = 't%s_' % idx_bef + class_name.lower()[:7] t1_field = 't%s_' % idx_aft + class_name.lower()[:7] # Gestion de l'évolution via la surface evol_s_str = str(evol_s) + ' m²' evo_s_field = "evo_s_%s" % str(temp_field) t0_s_field = 't%s_s_' % idx_bef + class_name.lower()[:5] t1_s_field = 't%s_s_' % idx_aft + class_name.lower()[:5] # Requête SQL pour le calcul brut de l'évolution sql_query += "ALTER TABLE %s ADD COLUMN %s REAL;\n" % (plot_table, evo_field) sql_query += "UPDATE %s SET %s = %s - %s;\n" % (plot_table, evo_field, t1_field, t0_field) sql_query += "ALTER TABLE %s ADD COLUMN %s REAL;\n" % (plot_table, evo_s_field) sql_query += "UPDATE %s SET %s = %s - %s;\n" % (plot_table, evo_s_field, t1_s_field, t0_s_field) sql_query += "ALTER TABLE %s ADD COLUMN %s VARCHAR;\n" % (plot_table, def_evo_field) sql_query += "UPDATE %s SET %s = 't%s a t%s - %s - aucune evolution';\n" % (plot_table, def_evo_field, idx_bef, idx_aft, class_name) # Si évolution à la fois via taux et via surface if evol != 0 and evol_s != 0: text_evol = "taux à %s" % evol_str if combi == 'and': text_evol += " ET " elif combi == 'or': text_evol += " OU " text_evol += "surface à %s" % evol_s_str sql_where_pos = "%s >= %s %s %s >= %s" % (evo_field, evol, combi, evo_s_field, evol_s) sql_where_neg = "%s <= -%s %s %s <= -%s" % (evo_field, evol, combi, evo_s_field, evol_s) # Si évolution uniquement via taux elif evol != 0: text_evol = "taux à %s" % evol_str sql_where_pos = "%s >= %s" % (evo_field, evol) sql_where_neg = "%s <= -%s" % (evo_field, evol) # Si évolution uniquement via surface elif evol_s != 0: text_evol = "surface à %s" % evol_s_str sql_where_pos = "%s >= %s" % (evo_s_field, evol_s) sql_where_neg = "%s <= -%s" % (evo_s_field, evol_s) sql_query += "UPDATE %s SET %s = 't%s a t%s - %s - evolution positive' WHERE %s;\n" % (plot_table, def_evo_field, idx_bef, idx_aft, class_name, sql_where_pos) sql_query += "UPDATE %s SET %s = 't%s a t%s - %s - evolution negative' WHERE %s;\n" % (plot_table, def_evo_field, idx_bef, idx_aft, class_name, sql_where_neg) # Ajout des paramètres de l'évolution quantifiée (temporalités, classe, taux/surface) au fichier texte de sortie text = "%s --> évolution entre t%s et t%s, pour la classe '%s' (label %s) :\n" % (def_evo_field, idx_bef, idx_aft, class_name, label) text += " %s --> taux d'évolution brut" % evo_field + " (%)\n" text += " %s --> surface d'évolution brute" % evo_s_field + " (m²)\n" text += "Evolution quantifiée : %s\n" % text_evol appendTextFileCR(output_evolution_text_file, text) temp_field += 1 # Traitements SQL de l'évolution des classes OCS executeQuery(connection, sql_query) closeConnection(connection) exportVectorByOgr2ogr(postgis_database_name, output_plot_vector, plot_table, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name, format_type=format_vector) print(cyan + "soilOccupationChange() : " + bold + green + "ETAPE 2/2 - Fin de la caractérisation des changements." + endC + '\n') # Suppression des fichiers temporaires if not save_results_intermediate: if debug >= 3: print(cyan + "soilOccupationChange() : " + endC + "Suppression des fichiers temporaires." + endC + '\n') deleteDir(temp_directory) dropDatabase(postgis_database_name, user_name=postgis_user_name, password=postgis_password, ip_host=postgis_ip_host, num_port=postgis_num_port, schema_name=postgis_schema_name) print(cyan + "soilOccupationChange() : " + bold + green + "FIN DES TRAITEMENTS" + endC + '\n') # Mise à jour du log ending_event = "soilOccupationChange() : Fin du traitement : " timeLine(path_time_log, ending_event) return
def computeVegetationHeight( input_grid, output_grid, soil_occupation, height_model, height_vegetation, divide_vegetation_classes, vegetation_label, high_vegetation_label, low_vegetation_label, high_vegetation_field, low_vegetation_field, veg_mean_field, veg_max_field, veg_rate_field, codage_float, suffix_temp, no_data_value, format_vector, path_time_log, save_results_intermediate, overwrite): temp_grid = os.path.splitext( input_grid)[0] + suffix_temp + os.path.splitext(input_grid)[1] if height_model != "": ### Récupération de la hauteur de végétation if debug >= 3: print(cyan + "computeVegetationHeight() : " + endC + bold + "Récupération de la hauteur de végétation." + endC + '\n') if not divide_vegetation_classes: expression = "im1b1 == %s ? im2b1 : %s" % (vegetation_label, no_data_value) else: expression = "im1b1 == %s or im1b1 == %s ? im2b1 : %s" % ( high_vegetation_label, low_vegetation_label, no_data_value) command = "otbcli_BandMath -il %s %s -out %s %s -exp '%s'" % ( soil_occupation, height_model, height_vegetation, codage_float, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: raise NameError( cyan + "computeVegetationHeight() : " + bold + red + "Erreur lors de la récupération de la hauteur de végétation." + endC) ### Récupération de la hauteur moyenne de végétation if debug >= 3: print(cyan + "computeVegetationHeight() : " + endC + bold + "Récupération de la hauteur moyenne de végétation." + endC + '\n') col_to_delete_list = ["min", "median", "sum", "std", "unique", "range"] statisticsVectorRaster(height_vegetation, input_grid, temp_grid, 1, False, False, True, col_to_delete_list, [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) renameFieldsVector(temp_grid, ['mean'], [veg_mean_field], format_vector=format_vector) renameFieldsVector(temp_grid, ['max'], [veg_max_field], format_vector=format_vector) else: print( cyan + "computeVegetationHeight() : " + bold + yellow + "Pas de calcul de l'indicateur 'hauteur moyenne de végétation' (pas de MNH en entrée)." + endC + '\n') copyVectorFile(input_grid, temp_grid, format_vector=format_vector) if divide_vegetation_classes: ### Récupération du taux de végétation haute if debug >= 3: print(cyan + "computeVegetationHeight() : " + endC + bold + "Récupération du taux de végétation haute." + endC + '\n') sql_statement = "SELECT *, ((%s/(%s+%s))*100) AS %s FROM %s" % ( high_vegetation_field, high_vegetation_field, low_vegetation_field, veg_rate_field, os.path.splitext(os.path.basename(temp_grid))[0]) command = "ogr2ogr -sql '%s' -dialect SQLITE %s %s" % ( sql_statement, output_grid, temp_grid) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: raise NameError( cyan + "computeVegetationHeight() : " + bold + red + "Erreur lors de la récupération du taux de végétation haute." + endC) else: print( cyan + "computeVegetationHeight() : " + bold + yellow + "Pas de calcul de l'indicateur 'taux de végétation haute' (pas de distinction végétation haute/basse dans l'OCS)." + endC + '\n') copyVectorFile(temp_grid, output_grid, format_vector=format_vector) return 0
def computeRoughnessByOcsMnh( grid_input, grid_output, mnh_input, classif_input, class_build_list, epsg, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Constante FIELD_H_TYPE = ogr.OFTReal FIELD_ID_TYPE = ogr.OFTInteger FIELD_NAME_HSUM = "sum_h" FIELD_NAME_HRE = "mean_h" FIELD_NAME_AREA = "nb_area" FIELD_NAME_ID = "id" SUFFIX_HEIGHT = '_hauteur' SUFFIX_BUILT = '_bati' SUFFIX_TEMP = '_temp' SUFFIX_MASK = '_mask' # Mise à jour du Log timeLine(path_time_log, "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT starting : ") print(cyan + "computeRoughnessByOcsMnh() : " + endC + "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") if debug >= 3: print(bold + green + "computeRoughnessByOcsMnh() : Variables dans la fonction" + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "grid_input : " + str(grid_input) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "grid_output : " + str(grid_output) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "mnh_input : " + str(mnh_input) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "class_build_list : " + str(class_build_list) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "overwrite : " + str(overwrite) + endC) # Test si le vecteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(grid_output) if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé print(cyan + "computeRoughnessByOcsMnh() : " + bold + yellow + "Le calcul de Roughness par OCS et MNT a déjà eu lieu." + endC + "\n") print(cyan + "computeRoughnessByOcsMnh() : " + bold + yellow + "Grid vector output : " + grid_output + " already exists and will not be created again." + endC) else : if check: try: removeVectorFile(grid_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée ############################################ ### Préparation générale des traitements ### ############################################ # Récuperation de la projection de l'image epsg_proj = getProjectionImage(classif_input) if epsg_proj == 0: epsg_proj = epsg # Préparation des fichiers temporaires temp_path = os.path.dirname(grid_output) + os.sep + "RoughnessByOcsAndMnh" # Nettoyage du repertoire temporaire si il existe if os.path.exists(temp_path): shutil.rmtree(temp_path) os.makedirs(temp_path) basename = os.path.splitext(os.path.basename(grid_output))[0] built_height = temp_path + os.sep + basename + SUFFIX_HEIGHT + SUFFIX_BUILT + extension_raster built_height_temp = temp_path + os.sep + basename + SUFFIX_HEIGHT + SUFFIX_BUILT + SUFFIX_TEMP + extension_raster classif_built_mask = temp_path + os.sep + basename + SUFFIX_BUILT + SUFFIX_MASK + extension_raster grid_output_temp = temp_path + os.sep + basename + SUFFIX_TEMP + extension_vector ############################## ### Calcul de l'indicateur ### ############################## # liste des classes de bati a prendre en compte dans l'expression du BandMath expression_bati = "" for id_class in class_build_list : expression_bati += "im1b1==%s or " %(str(id_class)) expression_bati = expression_bati[:-4] expression = "(%s) and (im2b1!=%s) and (im2b1>0)" %(expression_bati, str(no_data_value)) # Creation d'un masque vecteur des batis pour la surface des zones baties command = "otbcli_BandMath -il %s %s -out %s uint8 -exp '%s ? 1 : 0'" %(classif_input, mnh_input, classif_built_mask, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Récupération de la hauteur du bati command = "otbcli_BandMath -il %s %s -out %s float -exp '%s ? im2b1 : 0'" %(classif_input, mnh_input, built_height_temp, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata %s -of %s %s %s" %(str(epsg_proj), str(no_data_value), format_raster, built_height_temp, built_height) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print(cyan + "computeRoughnessByOcsMnh() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Récupération du nombre de pixel bati de chaque maille pour definir la surface statisticsVectorRaster(classif_built_mask, grid_input, grid_output_temp, 1, False, False, True, ["min", "max", "median", "mean", "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Renomer le champ 'sum' en FIELD_NAME_AREA renameFieldsVector(grid_output_temp, ['sum'], [FIELD_NAME_AREA], format_vector) # Récupération de la hauteur moyenne du bati de chaque maille statisticsVectorRaster(built_height, grid_output_temp, grid_output, 1, False, False, True, ["min", "max", "median", 'mean', "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Renomer le champ 'mean' en FIELD_NAME_HRE renameFieldsVector(grid_output, ['sum'], [FIELD_NAME_HSUM], format_vector) # Calcul de la colonne FIELD_NAME_HRE division de FIELD_NAME_HSUM par FIELD_NAME_AREA field_values_list = getAttributeValues(grid_output, None, None, {FIELD_NAME_ID:FIELD_ID_TYPE, FIELD_NAME_HSUM:FIELD_H_TYPE, FIELD_NAME_AREA:FIELD_H_TYPE}, format_vector) field_new_values_list = [] for index in range(0, len(field_values_list[FIELD_NAME_ID])) : value_h = 0.0 if field_values_list[FIELD_NAME_AREA][index] > 0 : value_h = field_values_list[FIELD_NAME_HSUM][index] / field_values_list[FIELD_NAME_AREA][index] field_new_values_list.append({FIELD_NAME_HRE:value_h}) # Ajour de la nouvelle colonne calculé FIELD_NAME_HRE addNewFieldVector(grid_output, FIELD_NAME_HRE, FIELD_H_TYPE, 0, None, None, format_vector) setAttributeValuesList(grid_output, field_new_values_list, format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: if os.path.exists(temp_path): shutil.rmtree(temp_path) print(cyan + "computeRoughnessByOcsMnh() : " + endC + "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") timeLine(path_time_log, "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT ending : ") return
def computeRoughness(classif_input, mnh_input, vector_grid_input, vector_grid_output, class_label_dico, epsg, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Constante FIELD_NAME_HRE = "mean_h" # Mise à jour du Log timeLine( path_time_log, "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT starting : " ) print( cyan + "computeRoughness() : " + endC + "Début du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") if debug >= 3: print(bold + green + "computeRoughness() : Variables dans la fonction" + endC) print(cyan + "computeRoughness() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "computeRoughness() : " + endC + "mnh_input : " + str(mnh_input) + endC) print(cyan + "computeRoughness() : " + endC + "vector_grid_input : " + str(vector_grid_input) + endC) print(cyan + "computeRoughness() : " + endC + "vector_grid_output : " + str(vector_grid_output) + endC) print(cyan + "computeRoughness() : " + endC + "class_label_dico : " + str(class_label_dico) + endC) print(cyan + "computeRoughness() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "computeRoughness() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "computeRoughness() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "computeRoughness() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "computeRoughness() : " + endC + "overwrite : " + str(overwrite) + endC) # Test si le vecteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(vector_grid_output) if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé print(cyan + "computeRoughness() : " + bold + yellow + "Le calcul de Roughness par OCS et MNT a déjà eu lieu." + endC + "\n") print(cyan + "computeRoughness() : " + bold + yellow + "Grid vector output : " + vector_grid_output + " already exists and will not be created again." + endC) else: if check: try: removeVectorFile(vector_grid_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée ############################################ ### Préparation générale des traitements ### ############################################ # Récuperation de la projection de l'image epsg_proj = getProjectionImage(classif_input) if epsg_proj == 0: epsg_proj = epsg # Liste des classes #key_class_label_list = list(class_label_dico.keys()) # Préparation des fichiers temporaires temp_path = os.path.dirname(vector_grid_output) + os.sep + "TEMP_HRE" # Nettoyage du repertoire temporaire si il existe if os.path.exists(temp_path): shutil.rmtree(temp_path) os.makedirs(temp_path) buit_height_temp = temp_path + os.sep + "hauteur_bati_temp" + extension_raster buit_height = temp_path + os.sep + "hauteur_bati" + extension_raster ############################## ### Calcul de l'indicateur ### ############################## # Récupération de la hauteur du bati #code_bati = [c for c,v in class_label_dico.items() if v=="bati"][0] code_bati = list(class_label_dico.keys())[list( class_label_dico.values()).index("bati")] command = "otbcli_BandMath -il %s %s -out %s float -exp 'im1b1==%s ? im2b1 : 0'" % ( classif_input, mnh_input, buit_height_temp, str(code_bati)) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "computeRoughness() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata 0 -of %s %s %s" % ( str(epsg_proj), format_raster, buit_height_temp, buit_height) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "computeRoughness() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Récupération de la hauteur moyenne du bati de chaque maille statisticsVectorRaster( buit_height, vector_grid_input, vector_grid_output, 1, False, False, True, ["min", "max", "median", "sum", "std", "unique", "range"], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Renomer le champ 'mean' en FIELD_NAME_HRE renameFieldsVector(vector_grid_output, ['mean'], [FIELD_NAME_HRE], format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: if os.path.exists(temp_path): shutil.rmtree(temp_path) print( cyan + "computeRoughness() : " + endC + "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT." + endC + "\n") timeLine( path_time_log, "Fin du calcul de l'indicateur Height of Roughness Elements par OCS et MNT ending : " ) return
def skyViewFactor(grid_input, grid_output, mns_input, classif_input, class_build_list, dim_grid_x, dim_grid_y, svf_radius, svf_method, svf_dlevel, svf_ndirs, epsg, no_data_value, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): print(bold + yellow + "Début du calcul de l'indicateur Sky View Factor." + endC + "\n") timeLine(path_time_log, "Début du calcul de l'indicateur Sky View Factor : ") if debug >= 3: print(bold + green + "skyViewFactor() : Variables dans la fonction" + endC) print(cyan + "skyViewFactor() : " + endC + "grid_input : " + str(grid_input) + endC) print(cyan + "skyViewFactor() : " + endC + "grid_output : " + str(grid_output) + endC) print(cyan + "skyViewFactor() : " + endC + "mns_input : " + str(mns_input) + endC) print(cyan + "skyViewFactor() : " + endC + "class_build_list : " + str(class_build_list) + endC) print(cyan + "skyViewFactor() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "skyViewFactor() : " + endC + "dim_grid_x : " + str(dim_grid_x) + endC) print(cyan + "skyViewFactor() : " + endC + "dim_grid_y : " + str(dim_grid_y) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_radius : " + str(svf_radius) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_method : " + str(svf_method) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_dlevel : " + str(svf_dlevel) + endC) print(cyan + "skyViewFactor() : " + endC + "svf_ndirs : " + str(svf_ndirs) + endC) print(cyan + "skyViewFactor() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "skyViewFactor() : " + endC + "no_data_value : " + str(no_data_value) + endC) print(cyan + "skyViewFactor() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "skyViewFactor() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "skyViewFactor() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "skyViewFactor() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "skyViewFactor() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "skyViewFactor() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "skyViewFactor() : " + endC + "overwrite : " + str(overwrite) + endC) # Constantes liées aux fichiers SKY_VIEW_FIELD = 'SkyView' BASE_FILE_TILE = 'tile_' BASE_FILE_POLY = 'poly_' SUFFIX_VECTOR_BUFF = '_buff' SUFFIX_VECTOR_TEMP = '_temp' # Constantes liées à l'arborescence FOLDER_SHP = 'SHP' FOLDER_SGRD = 'SGRD' FOLDER_TIF = 'TIF' SUB_FOLDER_DEM = 'DEM' SUB_FOLDER_SVF = 'SVF' SUB_SUB_FOLDER_BUF = 'BUF' if not os.path.exists(grid_output) or overwrite: ############################################ ### Préparation générale des traitements ### ############################################ if os.path.exists(grid_output): removeVectorFile(grid_output) temp_path = os.path.dirname(grid_output) + os.sep + "SkyViewFactor" sky_view_factor_raster = temp_path + os.sep + "sky_view_factor" + extension_raster cleanTempData(temp_path) os.makedirs(temp_path + os.sep + FOLDER_SHP) os.makedirs(temp_path + os.sep + FOLDER_SGRD + os.sep + SUB_FOLDER_DEM) os.makedirs(temp_path + os.sep + FOLDER_SGRD + os.sep + SUB_FOLDER_SVF) os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM) os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF) os.makedirs(temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF) # Récupération de la résolution du raster d'entrée pixel_size_x, pixel_size_y = getPixelWidthXYImage(mns_input) print(bold + "Taille de pixel du fichier '%s' :" % (mns_input) + endC) print(" pixel_size_x = " + str(pixel_size_x)) print(" pixel_size_y = " + str(pixel_size_y) + "\n") ############################################### ### Création des fichiers emprise et grille ### ############################################### print(bold + cyan + "Création des fichiers emprise et grille :" + endC) timeLine(path_time_log, " Création des fichiers emprise et grille : ") emprise_file = temp_path + os.sep + "emprise" + extension_vector quadrillage_file = temp_path + os.sep + "quadrillage" + extension_vector # Création du fichier d'emprise createVectorMask(mns_input, emprise_file, no_data_value, format_vector) # Création du fichier grille createGridVector(emprise_file, quadrillage_file, dim_grid_x, dim_grid_y, None, overwrite, epsg, format_vector) ############################################################# ### Extraction des carreaux de découpage et bufferisation ### ############################################################# print(bold + cyan + "Extraction des carreaux de découpage :" + endC) timeLine(path_time_log, " Extraction des carreaux de découpage : ") split_tile_vector_list = splitVector(quadrillage_file, temp_path + os.sep + FOLDER_SHP, "", epsg, format_vector, extension_vector) split_tile_vector_buff_list = [] # Boucle sur les fichiers polygones quadrillage for split_tile_vector in split_tile_vector_list: repertory_temp_output = os.path.dirname(split_tile_vector) base_name = os.path.splitext( os.path.basename(split_tile_vector))[0] split_tile_buff_vector = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + extension_vector split_tile_buff_vector_temp = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + SUFFIX_VECTOR_TEMP + extension_vector # Bufferisation bufferVector(split_tile_vector, split_tile_buff_vector_temp, svf_radius, "", 1.0, 10, format_vector) # Re-découpage avec l'emprise si la taille intersecte avec l'emprise if cutVector(emprise_file, split_tile_buff_vector_temp, split_tile_buff_vector, overwrite, format_vector): split_tile_vector_buff_list.append(split_tile_buff_vector) ########################################################## ### Découpage du MNS/MNH à l'emprise de chaque carreau ### ########################################################## print(bold + cyan + "Découpage du raster en tuiles :" + endC) timeLine(path_time_log, " Découpage du raster en tuiles : ") # Boucle sur les fichiers polygones quadrillage bufferisés for i in range(len(split_tile_vector_list)): print("Traitement de la tuile " + str(int(i) + 1) + str(len(split_tile_vector_list)) + "...") split_tile_vector = split_tile_vector_list[i] repertory_temp_output = os.path.dirname(split_tile_vector) base_name = os.path.splitext( os.path.basename(split_tile_vector))[0] split_tile_buff_vector = repertory_temp_output + os.sep + base_name + SUFFIX_VECTOR_BUFF + extension_vector dem_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM + os.sep + BASE_FILE_TILE + str( i) + extension_raster if os.path.exists(split_tile_buff_vector): cutImageByVector(split_tile_buff_vector, mns_input, dem_tif_file, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) ################################################## ### Calcul du SVF pour chaque dalle du MNS/MNH ### ################################################## print(bold + cyan + "Calcul du SVF pour chaque tuile via SAGA :" + endC) timeLine(path_time_log, " Calcul du SVF pour chaque tuile via SAGA : ") svf_buf_tif_file_list = [] # Boucle sur les tuiles du raster d'entrée créées par chaque polygone quadrillage for i in range(len(split_tile_vector_list)): # Calcul de Sky View Factor par SAGA dem_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_DEM + os.sep + BASE_FILE_TILE + str( i) + extension_raster svf_buf_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF + os.sep + BASE_FILE_TILE + str( i) + extension_raster if os.path.exists(dem_tif_file): computeSkyViewFactor(dem_tif_file, svf_buf_tif_file, svf_radius, svf_method, svf_dlevel, svf_ndirs, save_results_intermediate) svf_buf_tif_file_list.append(svf_buf_tif_file) ################################################################### ### Re-découpage des tuiles du SVF avec les tuilles sans tampon ### ################################################################### print(bold + cyan + "Re-découpage des tuiles du SVF avec les tuilles sans tampon :" + endC) timeLine( path_time_log, " Re-découpage des tuiles du SVF avec les tuilles sans tampon : " ) folder_output_svf = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep # Boucle sur les tuiles du SVF bufferisées for i in range(len(split_tile_vector_list)): print("Traitement de la tuile " + str(int(i) + 1) + "/" + str(len(split_tile_vector_list)) + "...") split_tile_vector = split_tile_vector_list[i] svf_buf_tif_file = temp_path + os.sep + FOLDER_TIF + os.sep + SUB_FOLDER_SVF + os.sep + SUB_SUB_FOLDER_BUF + os.sep + BASE_FILE_TILE + str( i) + extension_raster base_name = os.path.splitext(os.path.basename(svf_buf_tif_file))[0] svf_tif_file = folder_output_svf + os.sep + base_name + extension_raster if os.path.exists(svf_buf_tif_file): cutImageByVector(split_tile_vector, svf_buf_tif_file, svf_tif_file, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) #################################################################### ### Assemblage des tuiles du SVF et calcul de l'indicateur final ### #################################################################### print( bold + cyan + "Assemblage des tuiles du SVF et calcul de l'indicateur final :" + endC) timeLine( path_time_log, " Assemblage des tuiles du SVF et calcul de l'indicateur final : " ) classif_input_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "classif_input" + SUFFIX_VECTOR_TEMP + extension_raster sky_view_factor_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + extension_raster # Issu de l'assemblage des dalles sky_view_factor_temp_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + extension_raster # Issu du redécoupage pour entrer correctement dans le BandMath sky_view_factor_temp_temp_temp = temp_path + os.sep + FOLDER_TIF + os.sep + "sky_view_factor" + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + SUFFIX_VECTOR_TEMP + extension_raster # Issu de la suppression des pixels bâti # Assemblage des tuiles du SVF créées précédemment pour ne former qu'un seul raster SVF selectAssembyImagesByHold( emprise_file, [folder_output_svf], sky_view_factor_temp, False, False, epsg, False, False, False, False, 1.0, pixel_size_x, pixel_size_y, no_data_value, "_", 2, 8, "", path_time_log, "_error", "_merge", "_clean", "_stack", format_raster, format_vector, extension_raster, extension_vector, save_results_intermediate, overwrite) # Suppression des valeurs de SVF pour les bâtiments cutImageByVector(emprise_file, classif_input, classif_input_temp, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) cutImageByVector(emprise_file, sky_view_factor_temp, sky_view_factor_temp_temp, pixel_size_x, pixel_size_y, no_data_value, epsg, format_raster, format_vector) expression = "" for id_class in class_build_list: expression += "im1b1==%s or " % (str(id_class)) expression = expression[:-4] command = "otbcli_BandMath -il %s %s -out %s float -exp '%s ? -1 : im2b1'" % ( classif_input_temp, sky_view_factor_temp_temp, sky_view_factor_temp_temp_temp, expression) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "skyViewFactor() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata %s -of %s %s %s" % ( str(epsg), str(no_data_value), format_raster, sky_view_factor_temp_temp_temp, sky_view_factor_raster) if debug >= 3: print(command) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "skyViewFactor() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise # Croisement vecteur-raster pour récupérer la moyenne de SVF par polygone du fichier maillage d'entrée col_to_delete_list = [ "min", "max", "median", "sum", "std", "unique", "range" ] statisticsVectorRaster( sky_view_factor_raster, grid_input, grid_output, 1, False, False, True, col_to_delete_list, [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite ) ## Erreur NaN pour polygones entièrement bâtis (soucis pour la suite ?) renameFieldsVector(grid_output, ['mean'], [SKY_VIEW_FIELD], format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: deleteDir(temp_path) else: print(bold + magenta + "Le calcul du Sky View Factor a déjà eu lieu." + endC + "\n") print(bold + yellow + "Fin du calcul de l'indicateur Sky View Factor." + endC + "\n") timeLine(path_time_log, "Fin du calcul de l'indicateur Sky View Factor : ") return
def occupationIndicator(classif_input, mnh_input, vector_grid_input, vector_grid_output, class_label_dico, epsg, path_time_log, format_raster='GTiff', format_vector='ESRI Shapefile', extension_raster=".tif", extension_vector=".shp", save_results_intermediate=False, overwrite=True): # Mise à jour du Log starting_event = "occupationIndicator() : Calcul de l'indicateur occupation du sol/hauteur de végétation starting : " timeLine(path_time_log, starting_event) print( bold + green + "Début du calcul de l'indicateur 'occupation du sol/hauteur de végétation'." + endC + "\n") if debug >= 3: print(bold + green + "occupationIndicator() : Variables dans la fonction" + endC) print(cyan + "occupationIndicator() : " + endC + "classif_input : " + str(classif_input) + endC) print(cyan + "occupationIndicator() : " + endC + "mnh_input : " + str(mnh_input) + endC) print(cyan + "occupationIndicator() : " + endC + "vector_grid_input : " + str(vector_grid_input) + endC) print(cyan + "occupationIndicator() : " + endC + "vector_grid_output : " + str(vector_grid_output) + endC) print(cyan + "occupationIndicator() : " + endC + "class_label_dico : " + str(class_label_dico) + endC) print(cyan + "occupationIndicator() : " + endC + "epsg : " + str(epsg) + endC) print(cyan + "occupationIndicator() : " + endC + "path_time_log : " + str(path_time_log) + endC) print(cyan + "occupationIndicator() : " + endC + "format_raster : " + str(format_raster) + endC) print(cyan + "occupationIndicator() : " + endC + "format_vector : " + str(format_vector) + endC) print(cyan + "occupationIndicator() : " + endC + "extension_raster : " + str(extension_raster) + endC) print(cyan + "occupationIndicator() : " + endC + "extension_vector : " + str(extension_vector) + endC) print(cyan + "occupationIndicator() : " + endC + "save_results_intermediate : " + str(save_results_intermediate) + endC) print(cyan + "occupationIndicator() : " + endC + "overwrite : " + str(overwrite) + endC) # Constante FIELD_OCS_NAME = 'class_OCS' FIELD_OCS_TYPE = ogr.OFTInteger FIELD_MAJORITY_NAME = 'majority' # Test si le vecteur de sortie existe déjà et si il doit être écrasés check = os.path.isfile(vector_grid_output) if check and not overwrite: # Si le fichier de sortie existent deja et que overwrite n'est pas activé print( bold + yellow + "Le calcul de l'indicateur occupation du sol/hauteur de végétation a déjà eu lieu. \n" + endC) print(bold + yellow + "Grid vector output : " + vector_grid_output + " already exists and will not be created again." + endC) else: if check: try: removeVectorFile(vector_grid_output) except Exception: pass # si le fichier n'existe pas, il ne peut pas être supprimé : cette étape est ignorée ############################################ ### Préparation générale des traitements ### ############################################ # Récuperation de la projection de l'image epsg_proj = getProjectionImage(classif_input) if epsg_proj == 0: epsg_proj = epsg # Liste des classes key_class_label_list = list(class_label_dico.keys()) # Préparation des fichiers temporaires temp_path = os.path.dirname(vector_grid_output) + os.sep + "TEMP_OCS" # Nettoyage du repertoire temporaire si il existe if os.path.exists(temp_path): shutil.rmtree(temp_path) os.makedirs(temp_path) tempOCS = temp_path + os.sep + "occupation_du_sol" + extension_vector tempHveg = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation" + extension_vector temp_class0 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class0" + extension_vector temp_class1 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class1" + extension_vector temp_class2 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class2" + extension_vector temp_class3 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class3" + extension_vector temp_class4 = temp_path + os.sep + "occupation_du_sol_hauteur_de_vegetation_class4" + extension_vector vegetation_height_temp = temp_path + os.sep + "hauteur_vegetation_temp" + extension_raster vegetation_height = temp_path + os.sep + "hauteur_vegetation" + extension_raster ############################## ### Calcul de l'indicateur ### ############################## # Récupération de l'occupation du sol de chaque maille statisticsVectorRaster(classif_input, vector_grid_input, tempOCS, 1, True, True, False, [], [], class_label_dico, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Récupération de la hauteur moyenne et la hauteur max de la végétation de chaque maille command = "otbcli_BandMath -il %s %s -out %s float -exp 'im1b1==%s ? im2b1 : 0'" % ( classif_input, mnh_input, vegetation_height_temp, str(key_class_label_list[4])) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "occupationIndicator() : " + bold + red + "!!! Une erreur c'est produite au cours de la commande otbcli_BandMath : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise command = "gdal_translate -a_srs EPSG:%s -a_nodata 0 -of %s %s %s" % ( str(epsg_proj), format_raster, vegetation_height_temp, vegetation_height) exit_code = os.system(command) if exit_code != 0: print(command) print( cyan + "occupationIndicator() : " + bold + red + "!!! Une erreur c'est produite au cours de la comande : gdal_translate : " + command + ". Voir message d'erreur." + endC, file=sys.stderr) raise statisticsVectorRaster(vegetation_height, tempOCS, tempHveg, 1, False, False, True, [], [], {}, path_time_log, True, format_vector, save_results_intermediate, overwrite) # Définir le nom des champs temp_class_list = [] list_class_str = "" for class_str in key_class_label_list: list_class_str += "%s, " % (str(class_label_dico[class_str])) built_str = class_label_dico[key_class_label_list[0]] road_str = class_label_dico[key_class_label_list[1]] water_str = class_label_dico[key_class_label_list[2]] baresoil_str = class_label_dico[key_class_label_list[3]] vegetation_str = class_label_dico[key_class_label_list[4]] vegetation_height_medium_str = "H_moy_" + vegetation_str[0:3] vegetation_height_max_str = "H_max_" + vegetation_str[0:3] if debug >= 3: print("built_str = " + built_str) print("road_str = " + road_str) print("water_str = " + water_str) print("baresoil_str = " + baresoil_str) print("vegetation_str = " + vegetation_str) print("vegetation_height_medium_str = " + vegetation_height_medium_str) print("vegetation_height_max_str = " + vegetation_height_max_str) column = "'ID, majority, minority, %s%s, %s, %s'" % ( list_class_str, vegetation_height_max_str, vegetation_height_medium_str, FIELD_OCS_NAME) # Ajout d'un champ renvoyant la classe d'OCS attribué à chaque polygone et renomer le champ 'mean' renameFieldsVector(tempHveg, ['max'], [vegetation_height_max_str], format_vector) renameFieldsVector(tempHveg, ['mean'], [vegetation_height_medium_str], format_vector) addNewFieldVector(tempHveg, FIELD_OCS_NAME, FIELD_OCS_TYPE, 0, None, None, format_vector) # Attribution de la classe 0 => classe majoritaire de bâti ou route ou eau #expression = "(" + built_str + " >= " + baresoil_str + " AND " + built_str + " >= " + vegetation_str + ") OR (" + road_str + " >= " + baresoil_str + " AND " + road_str + " >= " + vegetation_str + ") OR (" + water_str + " >= " + baresoil_str + " AND " + water_str + " >= " + vegetation_str + ")" expression = "(" + FIELD_MAJORITY_NAME + " = '" + built_str + "') OR (" + FIELD_MAJORITY_NAME + " = '" + road_str + "') OR (" + FIELD_MAJORITY_NAME + " = '" + water_str + "')" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class0, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class0, FIELD_OCS_NAME, 0, format_vector) temp_class_list.append(temp_class0) # Attribution de la classe 1 => classe majoritaire de sol nu #expression = "(" + baresoil_str + " > " + built_str + " AND " + baresoil_str + " > " + road_str + " AND " + baresoil_str + " > " + water_str + " AND " + baresoil_str + " >= " + vegetation_str + ")" expression = "(" + FIELD_MAJORITY_NAME + " = '" + baresoil_str + "')" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class1, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class1, FIELD_OCS_NAME, 1, format_vector) temp_class_list.append(temp_class1) # Attribution de la classe 2 => classe majoritaire de végétation avec Hauteur inferieur à 1 #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " < 1)" expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " < 1)" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class2, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class2, FIELD_OCS_NAME, 2, format_vector) temp_class_list.append(temp_class2) # Attribution de la classe 3 => classe majoritaire de végétation avec Hauteur entre 1 et 5 #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " >= 1 AND " + vegetation_height_medium_str + " < 5)" expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " >= 1 AND " + vegetation_height_medium_str + " < 5)" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class3, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class3, FIELD_OCS_NAME, 3, format_vector) temp_class_list.append(temp_class3) # Attribution de la classe 4 => classe majoritaire de végétation avec Hauteur > 5 #expression = "(" + vegetation_str + " > " + built_str + " AND " + vegetation_str + " > " + road_str + " AND " + vegetation_str + " > " + water_str + " AND " + vegetation_str + " > " + baresoil_str + ") AND (" + vegetation_height_medium_str + " >= 5)" expression = "(" + FIELD_MAJORITY_NAME + " = '" + vegetation_str + "') AND (" + vegetation_height_medium_str + " >= 5)" if debug >= 3: print(expression) ret = filterSelectDataVector(tempHveg, temp_class4, column, expression, format_vector) if not ret: raise NameError( cyan + "occupationIndicator() : " + bold + red + "Attention problème lors du filtrage des BD vecteurs l'expression SQL %s est incorrecte" % (expression) + endC) updateFieldVector(temp_class4, FIELD_OCS_NAME, 4, format_vector) temp_class_list.append(temp_class4) fusionVectors(temp_class_list, vector_grid_output, format_vector) ########################################## ### Nettoyage des fichiers temporaires ### ########################################## if not save_results_intermediate: if os.path.exists(temp_path): shutil.rmtree(temp_path) # Mise à jour du Log print( bold + green + "Fin du calcul de l'indicateur 'occupation du sol/hauteur de végétation'." + endC + "\n") ending_event = "occupationIndicator() : Calcul de l'indicateur occupation du sol/hauteur de végétation ending : " timeLine(path_time_log, ending_event) return