diff --git a/R_old/_disable_autoload.R b/R_old/_disable_autoload.R deleted file mode 100644 index a8c9436..0000000 --- a/R_old/_disable_autoload.R +++ /dev/null @@ -1,3 +0,0 @@ -# Disabling shiny autoload - -# See ?shiny::loadSupport for more information diff --git a/R_old/app_config.R b/R_old/app_config.R deleted file mode 100644 index b8b463d..0000000 --- a/R_old/app_config.R +++ /dev/null @@ -1,44 +0,0 @@ -#' Access files in the current app -#' -#' NOTE: If you manually change your package name in the DESCRIPTION, -#' don't forget to change it here too, and in the config file. -#' For a safer name change mechanism, use the `golem::set_golem_name()` function. -#' -#' @param ... character vectors, specifying subdirectory and file(s) -#' within your package. The default, none, returns the root of the app. -#' -#' @noRd -app_sys <- function(...) { - system.file(..., package = "mapdoapp") -} - - -#' Read App Config -#' -#' @param value Value to retrieve from the config file. -#' @param config GOLEM_CONFIG_ACTIVE value. If unset, R_CONFIG_ACTIVE. -#' If unset, "default". -#' @param use_parent Logical, scan the parent directory for config file. -#' @param file Location of the config file -#' -#' @noRd -get_golem_config <- function( - value, - config = Sys.getenv( - "GOLEM_CONFIG_ACTIVE", - Sys.getenv( - "R_CONFIG_ACTIVE", - "default" - ) - ), - use_parent = TRUE, - # Modify this if your config file is somewhere else - file = app_sys("golem-config.yml") -) { - config::get( - value = value, - config = config, - file = file, - use_parent = use_parent - ) -} diff --git a/R_old/app_server.R b/R_old/app_server.R deleted file mode 100644 index 33a105d..0000000 --- a/R_old/app_server.R +++ /dev/null @@ -1,102 +0,0 @@ -#' The application server-side -#' -#' @param input,output,session Internal parameters for {shiny}. -#' DO NOT REMOVE. -#' @import shiny -#' @importFrom DBI dbDisconnect -#' -#' -#' @noRd -app_server <- function(input, output, session) { - - # track session - track_session(session = session) - - ### R_VAL #### - r_val <- reactiveValues( - - tab_open1 = NULL, # descriptor of the opened tab on right side - tab_open2 = NULL, # descriptor of the opened tab below - - # UI - selection_text = "", # description text indicating basin, region, axis - - # map - map_proxy = NULL, - leaflet_hover_measure = NULL, # metric y-value to add vertical line on longitudinal profile - visualization = "classes", - - selected_metric = "talweg_elevation_min", # select main metric column name - - # data hydrography - bassins = NULL, - bassin_name = NULL, - regions_in_bassin = NULL, - region_click = NULL, - region_clicked = FALSE, # boolean stating whether first region was clicked - region_name = NULL, - selected_region_feature = NULL, - network_region_axis = NULL, - network_region = NULL, - axis_name = NULL, - axis_click = NULL, - axis_clicked = FALSE, # boolean stating whether first axis was clicked - dgo_axis = NULL, - axis_start_end = NULL, - data_dgo_clicked = NULL, - data_section = NULL, - - manual_classes_table = NULL, # manual classification table - - # classified networks - network_region_classified = NULL, # classified dgos of selected region - dgo_axis_classified = NULL, # classified dgos of selected axis - merged_networks_classified = NULL, # merged classified networks of region and axis, with additional scale-variable to distinguish them - - # selected class from proposed classes - classes_proposed_selected = NULL, - - # metric info - selected_metric_title = NULL, - selected_metric_type = NULL, - selected_metric_info = NULL, - - # data external - roe_region = NULL, # ROE data in selected region - roe_axis = NULL, # ROE data in selected axis - hydro_sites_region = NULL, - - # styling of wms-layer - sld_body = NULL, - - # longitudinal plot - plot_long_proxy = NULL -, - # others variables - opacity = list(clickable = 0.01, not_clickable = 0.10) # opacity value to inform the user about available bassins and regions - - ) - - ### DB connection #### - con <- db_con() - - ### Server activation #### - # main servers - mod_mapdo_app_server("mapdo_app_1", con, r_val) - mod_documentation_server("documentation_1") - - # tabs - mod_classification_proposed_server("classification_proposed_1", r_val) - mod_classification_manual_server("classification_manual_1", con, r_val) - mod_metric_overview_server("metric_overview_1", r_val) - mod_profil_long_server("profil_long_1", r_val) - mod_profil_transverse_server("profil_transverse_1", r_val) - mod_classes_distribution_server("classes_distribution_1", r_val) - - ### DB disconnect when closing session #### - onStop(function() { - if (!is.null(con)) { - DBI::dbDisconnect(con) - } - }) -} diff --git a/R_old/app_ui.R b/R_old/app_ui.R deleted file mode 100644 index bbd9c64..0000000 --- a/R_old/app_ui.R +++ /dev/null @@ -1,47 +0,0 @@ -#' The application User-Interface -#' -#' @param request Internal parameter for `{shiny}`. -#' DO NOT REMOVE. -#' @import shiny -#' @importFrom bslib bs_theme -#' @noRd -app_ui <- function(request){ - navbarPage( - theme = bs_theme(version = 5, bootswatch = "simplex"), - title = - img(src = "www/logos_mapdo_evs_ofb.png"), - tabPanel("Mapd'O App", - mod_mapdo_app_ui("mapdo_app_1") - ), - tabPanel("Documentation", - icon = icon("info"), - mod_documentation_ui("documentation_1") - ) - ) -} - - -#' Add external Resources to the Application -#' -#' This function is internally used to add external -#' resources inside the Shiny application. -#' -#' @import shiny -#' @importFrom golem add_resource_path activate_js favicon bundle_resources -#' @noRd -golem_add_external_resources <- function() { - add_resource_path( - "www", - app_sys("app/www") - ) - - tags$head( - favicon(ext = "png"), - bundle_resources( - path = app_sys("app/www"), - app_title = "mapdoapp" - ) - # Add here other external resources - # for example, you can add shinyalert::useShinyalert() - ) -} diff --git a/R_old/doc_bassin_hydrographique.R b/R_old/doc_bassin_hydrographique.R deleted file mode 100644 index 071e72a..0000000 --- a/R_old/doc_bassin_hydrographique.R +++ /dev/null @@ -1,17 +0,0 @@ -#' bassin_hydrographique -#' -#' Description. -#' -#' @format A data frame with 1 rows and 8 variables: -#' \describe{ -#' \item{ gid }{ numeric } -#' \item{ cdbh }{ character } -#' \item{ lbbh }{ character } -#' \item{ numcircadm }{ character } -#' \item{ projcoordo }{ character } -#' \item{ click }{ logical } -#' \item{ opacity }{ numeric } -#' \item{ geom }{ sfc_MULTIPOLYGON,sfc } -#' } -#' @source Source -"bassin_hydrographique" diff --git a/R_old/doc_network_axis.R b/R_old/doc_network_axis.R deleted file mode 100644 index ac4787f..0000000 --- a/R_old/doc_network_axis.R +++ /dev/null @@ -1,14 +0,0 @@ -#' network_axis -#' -#' Description. -#' -#' @format A data frame with 69 rows and 5 variables: -#' \describe{ -#' \item{ fid }{ integer64 } -#' \item{ axis }{ integer64 } -#' \item{ toponyme }{ character } -#' \item{ gid_region }{ integer } -#' \item{ geom }{ sfc_MULTILINESTRING,sfc } -#' } -#' @source Source -"network_axis" diff --git a/R_old/doc_network_dgo.R b/R_old/doc_network_dgo.R deleted file mode 100644 index d722c68..0000000 --- a/R_old/doc_network_dgo.R +++ /dev/null @@ -1,55 +0,0 @@ -#' network_dgo -#' -#' Description. -#' -#' @format A data frame with 573 rows and 46 variables: -#' \describe{ -#' \item{ fid }{ integer } -#' \item{ axis }{ numeric } -#' \item{ measure }{ integer } -#' \item{ toponyme }{ character } -#' \item{ strahler }{ integer } -#' \item{ talweg_elevation_min }{ numeric } -#' \item{ active_channel_width }{ numeric } -#' \item{ natural_corridor_width }{ numeric } -#' \item{ connected_corridor_width }{ numeric } -#' \item{ valley_bottom_width }{ numeric } -#' \item{ talweg_slope }{ numeric } -#' \item{ floodplain_slope }{ numeric } -#' \item{ water_channel }{ numeric } -#' \item{ gravel_bars }{ numeric } -#' \item{ natural_open }{ numeric } -#' \item{ forest }{ numeric } -#' \item{ grassland }{ numeric } -#' \item{ crops }{ numeric } -#' \item{ diffuse_urban }{ numeric } -#' \item{ dense_urban }{ numeric } -#' \item{ infrastructures }{ numeric } -#' \item{ active_channel }{ numeric } -#' \item{ riparian_corridor }{ numeric } -#' \item{ semi_natural }{ numeric } -#' \item{ reversible }{ numeric } -#' \item{ disconnected }{ numeric } -#' \item{ built_environment }{ numeric } -#' \item{ water_channel_pc }{ numeric } -#' \item{ gravel_bars_pc }{ numeric } -#' \item{ natural_open_pc }{ numeric } -#' \item{ forest_pc }{ numeric } -#' \item{ grassland_pc }{ numeric } -#' \item{ crops_pc }{ numeric } -#' \item{ diffuse_urban_pc }{ numeric } -#' \item{ dense_urban_pc }{ numeric } -#' \item{ infrastructures_pc }{ numeric } -#' \item{ active_channel_pc }{ numeric } -#' \item{ riparian_corridor_pc }{ numeric } -#' \item{ semi_natural_pc }{ numeric } -#' \item{ reversible_pc }{ numeric } -#' \item{ disconnected_pc }{ numeric } -#' \item{ built_environment_pc }{ numeric } -#' \item{ sum_area }{ numeric } -#' \item{ idx_confinement }{ numeric } -#' \item{ gid_region }{ integer } -#' \item{ geom }{ sfc_MULTILINESTRING,sfc } -#' } -#' @source Source -"network_dgo" diff --git a/R_old/doc_region_hydrographique.R b/R_old/doc_region_hydrographique.R deleted file mode 100644 index 6c6c90f..0000000 --- a/R_old/doc_region_hydrographique.R +++ /dev/null @@ -1,16 +0,0 @@ -#' region_hydrographique -#' -#' Description. -#' -#' @format A data frame with 1 rows and 7 variables: -#' \describe{ -#' \item{ gid }{ numeric } -#' \item{ cdregionhy }{ character } -#' \item{ lbregionhy }{ character } -#' \item{ cdbh }{ character } -#' \item{ click }{ logical } -#' \item{ opacity }{ numeric } -#' \item{ geom }{ sfc_MULTIPOLYGON,sfc } -#' } -#' @source Source -"region_hydrographique" diff --git a/R_old/fct_conn.R b/R_old/fct_conn.R deleted file mode 100644 index fbebf3e..0000000 --- a/R_old/fct_conn.R +++ /dev/null @@ -1,19 +0,0 @@ -#' Connection to postgresql database -#' -#' @importFrom DBI dbConnect -#' @importFrom RPostgres Postgres -#' -#' @return connection -#' @export -#' -#' @examples -#' db_connection <- db_con() -db_con <- function(){ - con <- DBI::dbConnect(RPostgres::Postgres(), - host = Sys.getenv("DBMAPDO_HOST"), - port = Sys.getenv("DBMAPDO_PORT"), - dbname = Sys.getenv("DBMAPDO_NAME"), - user = Sys.getenv("DBMAPDO_USER"), - password = Sys.getenv("DBMAPDO_PASS")) - return(con) -} diff --git a/R_old/fct_cr_profile.R b/R_old/fct_cr_profile.R deleted file mode 100644 index 493ab9a..0000000 --- a/R_old/fct_cr_profile.R +++ /dev/null @@ -1,76 +0,0 @@ -#' Create an empty cross section plot. -#' -#' This function generates an empty cross section plot using the 'plot_ly' -#' function from the 'plotly' package. -#' -#' @return An empty longitudinal profile plot with a specified title. -#' -#' @importFrom plotly plot_ly layout -#' -#' @examples -#' # Create an empty longitudinal profile plot -#' empty_plot <- lg_profile_empty() -#' empty_plot -#' -#' @export -cr_profile_empty <- function() { - temp <- data.frame() - plot <- plot_ly(data = temp, source = "plot_pg") %>% - layout( - title = list( - text = "Sélectionnez un cours d'eau et un tronçon sur la carte pour afficher la section", - y = 0.80, # y title position - x = 0.3, # x title position - font = list(size = 15) - ), - xaxis = list( - zeroline = FALSE - ), - yaxis = list( - zeroline = FALSE - )) - return(plot) -} - -#' Create a cross section plot for selected DGO data. -#' -#' @param data data.frame elevation profiles from selected dgo. -#' @param axis_toponyme text axis toponyme name. -#' -#' @importFrom plotly plot_ly layout -#' -#' @return plotly cross section plot. -#' @export -cr_profile_main <- function(data, axis_toponyme){ - section <- plot_ly(data = data, x = ~distance, y = ~profile, type = 'scatter', - yaxis = 'y1', key = data$id, # the "id" column for hover text - mode = 'lines+markers', fill = 'tozeroy', fillcolor = '#B0B0B0', - line = list(color = '#2C2C2C'), marker = list(opacity=0), - name = "elevation", - source = "T") %>% - layout(yaxis = list(title = "Elévation (m)", - range = c(min(data$profile, na.rm = TRUE), max(data$profile, na.rm = TRUE))), - xaxis = list(title = "Distance au talweg (m)"), - margin = list(l = 50, r = 30, t = 70, b = 70), - title= "Profil transversal médian", - hovermode = "x unified", - annotations = list( - list( - text = "Rive gauche", x = 0, y = 1.1, - xref = "paper", yref = "paper", showarrow = FALSE, - font = list(size = 14, weight = "bold") - ), - list( - text = "Rive droite", x = 1, y = 1.1, - xref = "paper", yref = "paper", showarrow = FALSE, - font = list(size = 14, weight = "bold") - ), - list( - text = axis_toponyme, x = 1, y = -0.18, - xref = "paper", yref = "paper", showarrow = FALSE, - font = list(size = 14, weight = "bold") - ) - ) - ) - return(section) -} diff --git a/R_old/fct_data.R b/R_old/fct_data.R deleted file mode 100644 index 953d139..0000000 --- a/R_old/fct_data.R +++ /dev/null @@ -1,790 +0,0 @@ -#' Get Hydrographic Basins -#' -#' This function retrieves hydrographic basins. -#' -#' @param opacity list that contain numeric values clickable and not_clickable to inform the user the non available features. -#' @param con PqConnection to Postgresql database. -#' -#' @return sf data frame containing information about hydrographic basins. -#' -#' @examples -#' con <- db_con() -#' opacity = list(clickable = 0.01, -#' not_clickable = 0.10) -#' -#' data <- data_get_bassins(opacity = opacity, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom dplyr mutate if_else -#' -#' @export -data_get_bassins <- function(opacity, con) { - query <- "SELECT * FROM bassin_hydrographique" - data <- sf::st_read(dsn = con, query = query) %>% - mutate(click = if_else(display == TRUE, TRUE, FALSE)) %>% - mutate(opacity = if_else(display == TRUE, opacity$clickable, opacity$not_clickable)) - return(data) -} - - -#' Get all the hydrological regions in a Hydrographic Basin -#' -#' This function retrieves regions within a specified hydrographic basin based on its ID. -#' -#' @param selected_bassin_id text ID of the selected hydrographic basin. -#' @param opacity list that contain numeric values clickable and not_clickable to inform the user the non available features. -#' @param con PqConnection to Postgresql database. -#' -#' @return A df data frame containing regions within the specified hydrographic basin. -#' -#' @examples -#' con <- db_con() -#' opacity = list(clickable = 0.01, -#' not_clickable = 0.10) -#' data <- data_get_regions_in_bassin(selected_bassin_id = "06", -#' opacity = opacity, -#' con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom dplyr mutate if_else -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_regions_in_bassin <- function(selected_bassin_id, opacity, con) { - sql <- "SELECT * FROM region_hydrographique WHERE cdbh LIKE ?selected_bassin_id" - query <- sqlInterpolate(con, sql, selected_bassin_id = selected_bassin_id) - data <- sf::st_read(dsn = con, query = query) %>% - mutate(click = if_else(display == TRUE, TRUE, FALSE)) %>% - mutate(opacity = if_else(display == TRUE, opacity$clickable, opacity$not_clickable)) - return(data) -} - - -#' Get hydrological region selected by user -#' -#' This function retrieves hydrographical data for a specified region based on its ID. -#' -#' @param region_click_id The ID of the selected region. -#' @param con PqConnection to Postgresql database. -#' -#' @return A sf data frame containing hydrographical data for the specified region. -#' -#' @examples -#' con <- db_con() -#' data <- data_get_region(region_click_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_region <- function(region_click_id, con) { - sql <- "SELECT * FROM region_hydrographique - WHERE gid = ?region_click_id" - query <- sqlInterpolate(con, sql, region_click_id = region_click_id) - data <- sf::st_read(dsn = con, query = query) - return(data) -} - -#' Get all Network Metrics Data for a Specific region -#' -#' This function retrieves data about network metrics for a specific region based on its ID. -#' -#' @param selected_region_id The ID of the selected region -#' @param con PqConnection to Postgresql database. -#' -#' @return A sf data frame containing information about network metrics for the specified region -#' -#' @examples -#' con <- db_con() -#' network_metrics_data <- data_get_network_axis(selected_region_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom dplyr arrange -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_network_region <- function(selected_region_id, con) { - - sql <- " - SELECT - network_metrics.fid, axis, measure, toponyme, strahler, talweg_elevation_min, - active_channel_width, natural_corridor_width, - connected_corridor_width, valley_bottom_width, talweg_slope, floodplain_slope, - water_channel, gravel_bars, natural_open, forest, grassland, crops, - diffuse_urban, dense_urban, infrastructures, active_channel, riparian_corridor, - semi_natural, reversible, disconnected, built_environment, - water_channel_pc, gravel_bars_pc, natural_open_pc, forest_pc, grassland_pc, crops_pc, - diffuse_urban_pc, dense_urban_pc, infrastructures_pc, active_channel_pc, - riparian_corridor_pc, semi_natural_pc, reversible_pc, disconnected_pc, - built_environment_pc, sum_area, idx_confinement, gid_region, network_metrics.geom - FROM network_metrics - WHERE gid_region = ?selected_region_id" - query <- sqlInterpolate(con, sql, selected_region_id = selected_region_id) - - data <- sf::st_read(dsn = con, query = query) %>% - dplyr::arrange(measure) #%>% - # na.omit() - - return(data) -} - - -#' Get Minimum and Maximum Strahler Values for a Selected Region -#' -#' This function retrieves the minimum and maximum values of the Strahler metric for a specified region. -#' -#' @param selected_region_id The ID of the selected region. -#' @param con PqConnection to Postgresql database. -#' -#' @return A data frame containing two columns: 'min' and 'max', representing the minimum and maximum Strahler values for the specified region. -#' -#' @examples -#' con <- db_con() -#' data <- data_get_min_max_strahler(selected_region_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom DBI dbGetQuery -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_min_max_strahler <- function(selected_region_id, con) { - sql <- "SELECT - MIN(strahler) AS min, - MAX(strahler) AS max - FROM network_metrics - WHERE gid_region = ?selected_region_id" - query <- sqlInterpolate(con, sql, selected_region_id = selected_region_id) - - data <- DBI::dbGetQuery(conn = con, statement = query) - - return(data) -} - - -#' Get Minimum and Maximum Metric Values for a Selected Region -#' -#' This function retrieves the minimum and maximum values of a selected metric for a specified region -#' -#' @param selected_region_id The ID of the selected region. -#' @param selected_metric The name of the selected metric. -#' @param con PqConnection to Postgresql database. -#' -#' @return A data frame containing two columns: 'min' and 'max', representing the minimum and maximum values of the selected metric for the specified region. -#' -#' @examples -#' con <- db_con() -#' data <- data_get_min_max_metric(selected_region_id = 11, -#' selected_metric = "active_channel_width", -#' con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom DBI dbGetQuery sqlInterpolate dbQuoteIdentifier SQL -#' -#' @export -data_get_min_max_metric <- function(selected_region_id, selected_metric, con) { - sql <- " - SELECT - ROUND(MIN(?selected_metric)::numeric, 1) AS min, - ROUND(MAX(?selected_metric)::numeric, 1) AS max - FROM network_metrics - WHERE gid_region = ?selected_region_id" - - query <- sqlInterpolate(conn = con, sql, - selected_metric = DBI::dbQuoteIdentifier(con, selected_metric), - selected_region_id = DBI::SQL(selected_region_id) - ) - - data <- DBI::dbGetQuery(conn = con, statement = query) - - return(data) -} - -#' Get Referentiel des Obstacles aux Ecoulement Data for a Region -#' -#' This function retrieves data about Referentiel des Obstacles aux Ecoulement (ROE) within a specified region based on its ID. -#' -#' @param selected_region_id The ID of the selected region. -#' @param con PqConnection to Postgresql database. -#' -#' @return A sf data frame containing information about ROE within the specified region. -#' -#' @examples -#' con <- db_con() -#' roe_data <- data_get_roe_in_region(selected_region_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_roe_in_region <- function(selected_region_id, con) { - sql <- " - SELECT - roe.gid, axis, distance_axis, nomprincip, lbtypeouvr, lbhautchut, gid_region, roe.geom - FROM roe - WHERE gid_region = ?selected_region_id - AND (roe.cdetouvrag LIKE '2') - AND (roe.stobstecou LIKE 'Validé')" - query <- sqlInterpolate(con, sql, selected_region_id = selected_region_id) - - data <- sf::st_read(dsn = con, query = query) - return(data) -} - - -#' Get Network Axis Data for a Region -#' -#' This function retrieves data about the network axis within a specified region based on its ID. -#' -#' @param selected_region_id The ID of the selected region. -#' @param con PqConnection to Postgresql database. -#' -#' @return A sf data frame containing information about the network axis within the specified region. -#' -#' @examples -#' con <- db_con() -#' axis_data <- data_get_axis(selected_region_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_axis <- function(selected_region_id, con) { - sql <- " - SELECT - network_axis.fid, axis, toponyme, gid_region, network_axis.geom - FROM network_axis - WHERE gid_region = ?selected_region_id" - query <- sqlInterpolate(con, sql, selected_region_id = selected_region_id) - - data <- sf::st_read(dsn = con, query = query) - return(data) -} - - -#' Get Network Metrics Data for a Specific Network Axis -#' -#' This function retrieves data about network metrics for a specific network axis based on its ID. -#' -#' @param selected_axis_id The ID of the selected network axis. -#' @param con PqConnection to Postgresql database. -#' -#' @return A sf data frame containing information about network metrics for the specified network axis. -#' -#' @examples -#' con <- db_con() -#' network_metrics_data <- data_get_network_axis(selected_axis_id = 2000796122, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom dplyr arrange -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_network_axis <- function(selected_axis_id, con) { - - sql <- " - SELECT - network_metrics.fid, axis, measure, toponyme, strahler, talweg_elevation_min, - active_channel_width, natural_corridor_width, - connected_corridor_width, valley_bottom_width, talweg_slope, floodplain_slope, - water_channel, gravel_bars, natural_open, forest, grassland, crops, - diffuse_urban, dense_urban, infrastructures, active_channel, riparian_corridor, - semi_natural, reversible, disconnected, built_environment, - water_channel_pc, gravel_bars_pc, natural_open_pc, forest_pc, grassland_pc, crops_pc, - diffuse_urban_pc, dense_urban_pc, infrastructures_pc, active_channel_pc, - riparian_corridor_pc, semi_natural_pc, reversible_pc, disconnected_pc, - built_environment_pc, sum_area, idx_confinement, gid_region, network_metrics.geom - FROM network_metrics - WHERE axis = ?selected_axis_id" - query <- sqlInterpolate(con, sql, selected_axis_id = selected_axis_id) - - data <- sf::st_read(dsn = con, query = query) %>% - dplyr::arrange(measure) #%>% - # na.omit() - - return(data) -} - - -#' Get the start and end coordinates of a spatial object's axis -#' -#' This function takes a spatial object with a LINESTRING geometry and returns -#' a data frame containing the start and end coordinates of the axis. -#' -#' @param dgo_axis A spatial sf object with a LINESTRING geometry representing an axis. -#' -#' @return A data frame with two rows, where the first row contains the start -#' coordinates (x and y) and the second row contains the end coordinates (x and y). -#' -#' @importFrom sf st_coordinates st_cast st_sf st_linestring -#' @importFrom utils tail head -#' -#' @examples -#' library(sf) -#' line_coords <- matrix(c(0, 0, 1, 1), ncol = 2) -#' # Create an sf object with the LINESTRING -#' line_sf <- st_sf(geometry = st_sfc(st_linestring(line_coords))) -#' df <- data_get_axis_start_end(line_sf) -#' -#' @export -data_get_axis_start_end <- function(dgo_axis) { - - # Extract the start and end points of the axis - axis_point_start <- st_coordinates(head(st_cast(tail(dgo_axis, n = 1), "POINT")$geom, n = 1)) - axis_point_end <- st_coordinates(tail(st_cast(head(dgo_axis, n = 1), "POINT")$geom, n = 1)) - - # Combine the coordinates into a data frame - axis_start_end <- data.frame(rbind(axis_point_start, axis_point_end)) - - return(axis_start_end) -} - -#' Get Network DGO Data in a Region -#' -#' This function retrieves data about the network DGO with the metrics within a specified region based on its ID. -#' -#' @param selected_region_id The ID of the selected region. -#' @param con PqConnection to Postgresql database. -#' -#' @return A sf data frame containing information about the network axis within the specified region. -#' -#' @examples -#' con <- db_con() -#' axis_data <- data_get_dgo_in_region(selected_region_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_dgo_in_region <- function(selected_region_id, con){ - sql <- " - SELECT - network_metrics.fid, axis, measure, toponyme, strahler, talweg_elevation_min, - active_channel_width, natural_corridor_width, - connected_corridor_width, valley_bottom_width, talweg_slope, floodplain_slope, - water_channel, gravel_bars, natural_open, forest, grassland, crops, - diffuse_urban, dense_urban, infrastructures, active_channel, riparian_corridor, - semi_natural, reversible, disconnected, built_environment, - water_channel_pc, gravel_bars_pc, natural_open_pc, forest_pc, grassland_pc, crops_pc, - diffuse_urban_pc, dense_urban_pc, infrastructures_pc, active_channel_pc, - riparian_corridor_pc, semi_natural_pc, reversible_pc, disconnected_pc, - built_environment_pc, sum_area, idx_confinement, gid_region, network_metrics.geom - FROM network_metrics - WHERE gid_region = ?selected_region_id" - query <- sqlInterpolate(con, sql, selected_region_id = selected_region_id) - - data <- sf::st_read(dsn = con, query = query) - return(data) -} - -#' Get hydrometric sites. -#' -#' This function retrieves data about the hydrometric sites from Hubeau. -#' -#' @param selected_region_id The ID of the selected region. -#' @param con PqConnection to Postgresql database. -#' -#' @return sf data frame containing information about the hydrometric sites within the specified region. -#' -#' @examples -#' con <- db_con() -#' hydro_sites <- data_get_hydro_sites(selected_region_id = 11, con = con) -#' DBI::dbDisconnect(con) -#' -#' @importFrom sf st_read -#' @importFrom DBI sqlInterpolate -#' -#' @export -data_get_hydro_sites <- function(selected_region_id, con){ - - sql <- " - SELECT - code_site, libelle_site, url_site, geom - FROM hydro_sites - WHERE gid_region = ?selected_region_id" - query <- sqlInterpolate(con, sql, selected_region_id = selected_region_id) - - data <- sf::st_read(dsn = con, query = query) - - return(data) -} - -#' Get elevation profiles data from selected dgo fid. -#' -#' @param selected_dgo_fid integer selected dgo fid. -#' @param con PqConnection to Postgresql database. -#' -#' @importFrom DBI dbGetQuery sqlInterpolate -#' @importFrom dplyr arrange mutate -#' -#' @return data.frame -#' @export -#' -#' @examples -#' con <- db_con() -#' data_get_elevation_profiles(selected_dgo_fid = 95, con = con) -#' DBI::dbDisconnect(con) -data_get_elevation_profiles <- function(selected_dgo_fid, con){ - - sql <- " - SELECT - id, hydro_swaths_gid, axis, measure_medial_axis, distance, profile - FROM elevation_profiles - WHERE hydro_swaths_gid = ?selected_dgo_fid" - query <- sqlInterpolate(con, sql, selected_dgo_fid = selected_dgo_fid) - - data <- DBI::dbGetQuery(conn = con, statement = query) %>% - arrange(distance) %>% - mutate(profile = round(profile, digits = 2)) - return(data) -} - - -#' Create initial dataframe for 1-variable classification, to be displayed on the UI table -#' -#' @param axis_data sf-object of an axis, containing all dgos inside the axis -#' @param variable_name name of variable for which the classification should be undertaken -#' @param no_classes number of classes to be generated -#' @param quantile size of quantile which provides value-range of classification -#' -#' @return dataframe with 4 columns: class (name of each class, here automatically set from A-Z), -#' variable (variable chosen for classification), greaterthan (values defining the threshold of each class), -#' and color (defining the coloring for the map) -#' -#' @importFrom RColorBrewer brewer.pal -#' -#' @examples -#'df <- create_df_input( -#' axis_data = network_dgo, -#' variable_name = input$variable, -#' no_classes = input$no_classes, -#' quantile = input$quantile -#' ) -#' -create_df_input <- function(axis_data, variable_name, no_classes = 4, quantile = 95){ - - # Set upper and lower boundaries of quantile interval - q_low <- (1 - quantile / 100) / 2 - q_high <- 1 - q_low - - # Calculate quantile values (min, max) and steps - q_values <- quantile(axis_data[[variable_name]], probs = c(q_low, q_high), na.rm = TRUE) - q_min <- q_values[1] - q_max <- q_values[2] - q_steps <- (q_max - q_min) / (no_classes) - - # Create class thresholds - classes <- seq(q_min, q_max, by = q_steps) - - # Ensure the first threshold is 0 and last is deleted - classes <- c(0, classes[2:no_classes]) - - # Create reversed RdBu color palette - color_palette <- if (no_classes == 2) { - c("#2166AC", "#B2182B") - } else { - rev(brewer.pal(no_classes, "RdBu")) - } - - # Create dataframe - df <- data.frame( - class = LETTERS[1:no_classes], - variable = variable_name, - greaterthan = round(classes, 2), - color = color_palette, - stringsAsFactors = FALSE - ) - - return(df) -} - - -#' Assign classes to network dgos -#' -#' @param data dataframe or sf object which contains dgos of axis or region -#' @param classes df containing columns variables, greater_thans, class_names, colors which define the classification of the network -#' -#' @return classified dataframe/sf object with additional variables: class_name and color -#' @importFrom rlang parse_exprs -#' @importFrom dplyr mutate case_when left_join join_by -#' @importFrom sf st_as_sf -#' -#' @examples -#' classified_network <- network_dgo %>% -#' assign_classes(variables = as.character(r_val$grouping_table_data$variable), -#' greater_thans = r_val$grouping_table_data$greaterthan, -#' class_names = r_val$grouping_table_data$class) -#' -assign_classes_manual <- function(data, classes) { - - variables <- as.character(classes$variable) - greater_thans <- classes$greaterthan - class_names <- classes$class - colors <- classes %>% select(class, color) - - df <- - data %>% - mutate( - class_name = case_when( - !!!parse_exprs(paste0(variables, ' >= ', greater_thans, ' ~ "', class_names, '"') - ) - ) - ) %>% - left_join(colors, by = join_by(class_name == class)) - - return(df) -} - -#' Assign classes to network dgos -#' -#' @param data dataframe or sf object containing all dgos of an axis or region -#' @param proposed_class string indicating the type of classification which should be applied to the data -#' -#' @return classified dataframe/sf object with additional variables: class_name and colors -#' @importFrom rlang parse_exprs -#' @importFrom dplyr mutate case_when left_join join_by rowwise ungroup c_across select -#' @importFrom sf st_as_sf st_drop_geometry -#' -#' @examples -#' classified_network <- network_dgo %>% -#' assign_classes(proposed_class = "class_strahler") -#' -assign_classes_proposed <- function(data, proposed_class) { - - # Function to safely get color by class_name - get_color <- function(class_name, colors_df) { - if (class_name == "unvalid") { - return("#f8f8ff") - } else if (class_name %in% names(colors_df)) { - return(colors_df[[class_name]]) - } else { - return("#f8f8ff") # Fallback color - } - } - - data <- data %>% sf::st_drop_geometry() - - - # strahler ---------------------------------------------------------------- - if (proposed_class == "class_strahler") { - colors_strahler <- colors_classes_proposed$class_strahler - - df <- data %>% - rowwise() %>% - mutate( - class_name = - case_when( - is.na(strahler) ~ "unvalid", - strahler == 1 ~ names(colors_strahler)[[1]], - strahler == 2 ~ names(colors_strahler)[[2]], - strahler == 3 ~ names(colors_strahler)[[3]], - strahler == 4 ~ names(colors_strahler)[[4]], - strahler == 5 ~ names(colors_strahler)[[5]], - strahler == 6 ~ names(colors_strahler)[[6]] - )) %>% - mutate( - color = get_color(class_name, colors_strahler) - ) %>% - ungroup() # Ungroup after row-wise operation - } - - # topography -------------------------------------------------------------- - else if (proposed_class == "class_topographie") { - - colors_topo <- colors_classes_proposed$class_topographie - - df <- data %>% - rowwise() %>% - mutate( - class_name = - case_when( - (is.na(talweg_elevation_min) | is.na(talweg_slope)) ~ "unvalid", - (talweg_elevation_min >= 1000 & talweg_slope >= 0.05) ~ names(colors_topo)[[4]], - (talweg_elevation_min >= 1000 & talweg_slope < 0.05) ~ names(colors_topo)[[1]], - (talweg_elevation_min >= 300 & talweg_slope >= 0.05) ~ names(colors_topo)[[5]], - (talweg_elevation_min >= 300 & talweg_slope < 0.05) ~ names(colors_topo)[[2]], - (talweg_elevation_min >= -50 & talweg_slope >= 0.05) ~ names(colors_topo)[[6]], - (talweg_elevation_min >= -50 & talweg_slope < 0.05) ~ names(colors_topo)[[3]], - )) %>% - mutate( - color = get_color(class_name, colors_topo) - ) %>% - ungroup() - } - - # dominant lu class ------------------------------------------------------- - else if (proposed_class == "class_lu_dominante") { - - # variables among which to select the one with greatest value - colors_dom <- colors_classes_proposed$class_lu_dominante - - # Function to safely get the max metric and its corresponding color - get_max_metric <- function(...) { - values <- c(...) - max_idx <- which.max(values) - if (all(is.na(values))) { - return("unvalid") - } else { - return(names(colors_dom)[max_idx]) - } - } - - # Main processing - df <- data %>% - rowwise() %>% - mutate( - metric_max = get_max_metric(forest_pc, grassland_pc, crops_pc, built_environment_pc) - ) %>% - mutate( - color = get_color(metric_max, colors_dom) - ) %>% - ungroup() %>% - mutate( - class_name = case_when( - metric_max == "forest_pc" ~ "Forêt", - metric_max == "grassland_pc" ~ "Prairies", - metric_max == "crops_pc" ~ "Cultures", - metric_max == "built_environment_pc" ~ "Espace construits", - .default = "unvalid" - ) - ) %>% - select(!metric_max) # Remove metric_max column - - } - - # urban lu ---------------------------------------------------------------- - else if (proposed_class == "class_urban") { - colors_urban <- colors_classes_proposed$class_urban - - df <- data %>% - rowwise() %>% - mutate(class_name = - case_when( - is.na(built_environment_pc) ~ "unvalid", - built_environment_pc >= 70 ~ names(colors_urban)[[1]], - built_environment_pc >= 40 ~ names(colors_urban)[[2]], - built_environment_pc >= 10 ~ names(colors_urban)[[3]], - built_environment_pc >= 0 ~ names(colors_urban)[[4]], - )) %>% - mutate( - color = get_color(class_name, colors_urban) - ) %>% - ungroup() # Ungroup after row-wise operation - - } - - # agricultural lu --------------------------------------------------------- - else if (proposed_class == "class_agriculture") { - colors_agriculture <- colors_classes_proposed$class_agriculture - - df <- data %>% - rowwise() %>% - mutate(class_name = - case_when( - is.na(crops_pc) ~ "unvalid", - crops_pc >= 70 ~ names(colors_agriculture)[[1]], - crops_pc >= 40 ~ names(colors_agriculture)[[2]], - crops_pc >= 10 ~ names(colors_agriculture)[[3]], - crops_pc >= 0 ~ names(colors_agriculture)[[4]], - )) %>% - mutate( - color = get_color(class_name, colors_agriculture) - ) %>% - ungroup() # Ungroup after row-wise operation - - } - - # natural landuse --------------------------------------------------------- - else if (proposed_class == "class_nature") { - colors_nature <- colors_classes_proposed$class_nature - - df <- data %>% - rowwise() %>% - mutate( - class_name = - case_when( - (is.na(natural_open_pc) | is.na(forest_pc) | is.na(grassland_pc)) ~ "unvalid", - (natural_open_pc + forest_pc + grassland_pc >= 70) ~ names(colors_nature)[[1]], - (natural_open_pc + forest_pc + grassland_pc >= 40) ~ names(colors_nature)[[2]], - (natural_open_pc + forest_pc + grassland_pc >= 10) ~ names(colors_nature)[[3]], - (natural_open_pc + forest_pc + grassland_pc >= 0) ~ names(colors_nature)[[4]], - )) %>% - mutate( - color = get_color(class_name, colors_nature) - ) %>% - ungroup() # Ungroup after row-wise operation - } - - # gravel bars ------------------------------------------------------------- - else if (proposed_class == "class_gravel") { - colors_gravel <- colors_classes_proposed$class_gravel - - df <- data %>% - rowwise() %>% - mutate( - class_name = - case_when( - (is.na(gravel_bars) | is.na(water_channel)) ~ "unvalid", - (gravel_bars/(water_channel+0.00001) >= 0.5) ~ names(colors_gravel)[[1]], - (gravel_bars/(water_channel+0.00001) > 0) ~ names(colors_gravel)[[2]], - (gravel_bars/(water_channel+0.00001) == 0) ~ names(colors_gravel)[[3]] - )) %>% - mutate( - color = get_color(class_name, colors_gravel) - ) %>% - ungroup() # Ungroup after row-wise operation - - } - - # Confinement ------------------------------------------------------------- - else if (proposed_class == "class_confinement") { - colors_confinement <- colors_classes_proposed$class_confinement - - df <- data %>% - rowwise() %>% - mutate( - class_name = - case_when( - (is.na(idx_confinement)) ~ "unvalid", - idx_confinement >= 0.7 ~ names(colors_confinement)[[1]], - idx_confinement >= 0.4 ~ names(colors_confinement)[[2]], - idx_confinement >= 0.1 ~ names(colors_confinement)[[3]], - idx_confinement >= 0 ~ names(colors_confinement)[[4]] - )) %>% - mutate( - color = get_color(class_name, colors_confinement) - ) %>% - ungroup() # Ungroup after row-wise operation - - } - - # Habitat ----------------------------------------------------------------- - else if (proposed_class == "class_habitat") { - colors_habitat <- colors_classes_proposed$class_habitat - - df <- data %>% - rowwise() %>% - mutate( - class_name = - case_when( - (is.na(riparian_corridor_pc) | is.na(semi_natural_pc)) ~ "unvalid", - (riparian_corridor_pc+semi_natural_pc >= 70) ~ names(colors_habitat)[[1]], - (riparian_corridor_pc+semi_natural_pc >= 40) ~ names(colors_habitat)[[2]], - (riparian_corridor_pc+semi_natural_pc >= 10) ~ names(colors_habitat)[[3]], - (riparian_corridor_pc+semi_natural_pc >= 0) ~ names(colors_habitat)[[4]] - )) %>% - mutate( - color = get_color(class_name, colors_habitat) - ) %>% - ungroup() # Ungroup after row-wise operation - } - - return(df) -} diff --git a/R_old/fct_lg_profile.R b/R_old/fct_lg_profile.R deleted file mode 100644 index c5876c2..0000000 --- a/R_old/fct_lg_profile.R +++ /dev/null @@ -1,342 +0,0 @@ -#' Create an empty longitudinal profile plot. -#' -#' This function generates an empty longitudinal profile plot using the 'plot_ly' -#' function from the 'plotly' package. -#' -#' @return An empty longitudinal profile plot with a specified title. -#' -#' @importFrom plotly plot_ly layout -#' -#' @examples -#' # Create an empty longitudinal profile plot -#' empty_plot <- lg_profile_empty() -#' empty_plot -#' -#' @export -lg_profile_empty <- function() { - temp <- data.frame() - plot <- plot_ly(data = temp, source = "plot_pg", type = 'scatter', mode = 'lines') %>% - layout( - title = list( - text = "Sélectionnez un cours d'eau sur la carte pour afficher le graphique", - y = 0.80, # y title position - x = 0.3, # x title position - font = list(size = 15) - ), - xaxis = list( - zeroline = FALSE - ), - yaxis = list( - zeroline = FALSE - )) - return(plot) -} - - -#' Create a vertical dashed line annotation for longitudinal profile plots -#' -#' This function generates a vertical dashed line annotation for longitudinal profile -#' plots using the 'plotly' package. -#' -#' @param x The x-coordinate where the vertical line should be positioned. -#' @param color The color of the vertical dashed line (default is "green"). -#' -#' @return A list object representing a vertical dashed line annotation. -#' -#' @examples -#' # see lg_profile_main() function to use it in a plotly graph -#' # Create a vertical dashed line annotation at x = 10 with a red color -#' vertical_line_annotation <- lg_vertical_line(x = 10, color = "red") -#' -#' @export -lg_vertical_line <- function(x = 0, color = "purple") { - list( - type = "line", - y0 = 0, - y1 = 1, - yref = "paper", - x0 = x, - x1 = x, - line = list(color = color, dash="dot") - ) -} - -#' Create the ROE vertical lines for plotly shapes -#' -#' @param roe_distance_axis vector ROE distance on axis. -#' -#' @return list of each vertical lines -#' @export -lg_roe_vertical_line <- function(roe_distance_axis){ - shapes_list <- lapply(roe_distance_axis, function(x) { - lg_vertical_line(x = x/1000, color = "#323232") - }) - return (shapes_list) -} - -#' plotly xaxis layout. -#' -#' @param data data.frame dgo from axis. -#' -#' @return list -#' @export -lg_xaxis_layout <- function(data){ - xaxis <- list( - title = 'Distance depuis l\'exutoire (km)', - range = c(0, max(data$measure)), - zeroline = FALSE) - return(xaxis) -} - -#' plotly yaxis layout. -#' -#' @param y_label text name of the metric plotted. -#' @param y_label_category text metric category name. -#' -#' @return list -#' @export -lg_yaxis_layout <- function(y_label_category, y_label){ - yaxis <- list( - title = paste0(y_label_category, " - ", y_label), - side = 'left', - zeroline = FALSE - ) - return(yaxis) -} - -#' plotly annotations layout. -#' -#' @param data data.frame dgo from axis. -#' -#' @return list -#' @export -lg_annotations_layout <- function(data){ - annotations = list( - text = unique(data$toponyme), - x = 1, # x-coordinate (0 to 1, where 0 is left and 1 is right) - y = -0.18, # y-coordinate (0 to 1, where 0 is bottom and 1 is top) - xref = "paper", # "paper" to specify coordinates relative to the entire plot - yref = "paper", - showarrow = FALSE, # Don't show the arrow - font = list( - # family = "Open Sans", - size = 14, - # color = "black" - weight = "bold" - ) - ) - return(annotations) -} - -#' plotly add trace. -#' -#' @param data data frame containing the selected axis data. -#' @param y text metric to be plotted on the y-axis. -#' @param y_label text name of the metric plotted. -#' @param yaxis text axis id. -#' -#' @return list -#' @export -lg_add_trace <- function(data, y, y_label, yaxis = 'y1'){ - trace <- list( - x = data$measure, - y = y, - key = data$fid, # the "id" column for hover text - type = 'scatter', - mode = 'lines', - line = list(color = "#7209b7"), - name = y_label, - yaxis = yaxis - ) - return(trace) -} - -#' Create a longitudinal profile plot for selected axis data. -#' -#' This function generates a longitudinal profile plot using the 'plot_ly' -#' function from the 'plotly' package. It allows you to visualize a specific -#' metric along the selected axis. -#' -#' @param data data frame containing the selected axis data. -#' @param y text metric to be plotted on the y-axis. -#' @param y_label text name of the metric plotted. -#' @param y_label_category text metric category name. -#' -#' @return plotly A longitudinal profile plot with the specified metric. -#' -#' @importFrom plotly plot_ly layout -#' -#' @examples -#' # Create a longitudinal profile plot for active channel width -#' selected_axis_df <- as.data.frame(network_dgo) -# profile_plot <- lg_profile_main(data = selected_axis_df, y = "active_channel_width", -# y_label = "Chenal actif", -# y_label_category = "Largeurs") -# profile_plot -#' -#' @export -lg_profile_main <- function(data, y, y_label, y_label_category) { - - plot <- plot_ly(x = data$measure, y = y, yaxis = 'y1', - key = data$fid, # the "id" column for hover text - type = 'scatter', mode = 'lines', name = y_label, - source = 'L', line = list(color = "#22223b")) %>% - layout( - xaxis = lg_xaxis_layout(data), - yaxis = lg_yaxis_layout(y_label_category, y_label), - # river name - annotations = lg_annotations_layout(data), - showlegend = TRUE, - legend = list(orientation = 'h'), - hovermode = "x unified", - # shapes = list(shapes = NULL), - margin = list(t = 20, b = 10, l = 50, r = 80) # create space for the second y-axis title - ) - return(plot) -} - -#' Generate list to update main plot in plotlyProxy -#' -#' This function generates a list to update the main axe in existing plotly graph with plotlyProxy. -#' -#' @param data A data frame containing the data to be plotted. -#' @param y The name of the y-axis variable to plot. -#' @param y_label The label for the y-axis. -#' @param y_label_category The category label for the y-axis. -#' -#' @return A list containing trace and layout lists to plot with plotlyProxy. -#' -#' @details -#' This function generates a main profile update plot with the specified data and axis labels. -# The plot is returned as a list containing both the trace and layout information. -# The trace contains x and y data for the plot, while the layout specifies the y-axis title. -# -#' @examples -#' \dontrun{ -#' data <- data.frame( -#' measure = 1:10, -#' selected_metric = rnorm(10, mean = 1) -#' ) -#' output$scatter_plot <- renderPlotly({ -#' plot_ly(data, x = ~measure, y = ~selected_metric, type = 'scatter', mode = 'line') -#' }) -#' data_updated <- data.frame( -#' measure = 1:10, -#' selected_metric = rnorm(10, mean = 1) -#' ) -#' selected_metric_name <- "my metric" -#' select_metric_category <- "my metric category" -#' update_main_axe <- -#' lg_profile_update_main( -#' data = data_updated, -#' y = data_updated[[selected_metric]], -#' y_label = selected_metric_name, -#' y_label_category = r_val$select_metric_category -#' ) -#' plotlyProxy("scatter_plot") %>% -#' plotlyProxyInvoke("deleteTraces", 0) %>% -#' plotlyProxyInvoke("addTraces", update_main_axe$trace, 0) %>% -#' plotlyProxyInvoke("relayout", update_main_axe$layout) -#' } -#' -#' @export -lg_profile_update_main <- function(data, y, y_label, y_label_category){ - - proxy_trace <- lg_add_trace(data, y, y_label, yaxis = 'y1') - - proxy_layout <- list( - xaxis = lg_xaxis_layout(data), - yaxis = lg_yaxis_layout(y_label_category, y_label), - # put all the annotation options to replace the river name - annotations = lg_annotations_layout(data) - ) - proxy <- list("trace" = proxy_trace, - "layout" = proxy_layout) - return(proxy) -} - -#' Create a dual-axis longitudinal profile plot for selected axis data -#' -#' This function generates a dual-axis longitudinal profile plot using the 'plot_ly' -#' function from the 'plotly' package. It allows you to visualize two different -#' metrics along the selected axis. -#' -#' @param data A data frame containing the selected axis data. -#' @param y The primary metric to be plotted on the left y-axis. -#' @param y_label The name of the metric plotted. -#' @param y_label_category The metric category name. -#' -#' @return A dual-axis longitudinal profile plot with the specified metrics. -#' -#' @examples -#' \dontrun{ -#' # like lg_profile_update_main function, see example in documentation -#'} -#' -#' @export -lg_profile_second <- function(data, y, y_label, y_label_category){ - - proxy_trace <- lg_add_trace(data, y, y_label, yaxis = 'y2') - - proxy_layout <- list( - yaxis2 = list( - title = list(text = paste0( y_label_category, " - ", - y_label) - ), - overlaying = 'y', - side = 'right', - showgrid = FALSE, # Hide the gridlines for the second y-axis - zeroline = FALSE, - showline = FALSE # Hide the axis line for the second y-axis - ) - ) - proxy <- list("trace" = proxy_trace, - "layout" = proxy_layout) - return(proxy) -} - - - -#' Create background-layout of classes for longitudinal profile -#' -#' @param classified_axis -#' -#' @return list ready to be used for plotly::layout()-function -create_classes_background <- function(classified_axis) { - - # Create empty list to store shapes in - shapes <- list() - - for (i in 1:(nrow(classified_axis) - 1)) { - - # set x-axis limits - start <- classified_axis$measure[i] - if (!is.na(classified_axis$measure[i + 1])) { - end <- classified_axis$measure[i + 1] - } else { - end <- start + 200 - } - - # set color - color <- classified_axis$color[i] - - # create unique shape for each step - shapes <- append(shapes, list( - list( - type = "rect", - fillcolor = color, - line = list(color = color, width = 0), - opacity = 0.4, - x0 = start, - x1 = end, - xref = "x", - y0 = 0, - y1 = 1, - yref = "paper", - layer = "below" - ) - )) - } - - return(shapes) -} diff --git a/R_old/fct_map.R b/R_old/fct_map.R deleted file mode 100644 index c4da200..0000000 --- a/R_old/fct_map.R +++ /dev/null @@ -1,955 +0,0 @@ -#' Initialize a Leaflet Map with hydrological Bassins -#' -#' This function initializes a Leaflet map with bassins data and various map layers. -#' -#' @param bassins_data A hydrological bassins sf data frame. -#' @param id_logo_ign_remonterletemps id of the IGN remonter le temps image. -#' -#' @return A Leaflet map object with basemaps, scale and layer control. -#' -#' @examples -#' map <- map_init_bassins(bassins_data = bassin_hydrographique, -#' id_logo_ign_remonterletemps = "logo_ign_remonterletemps") -#' map -#' -#' @importFrom leaflet leaflet setView addPolygons addScaleBar addLayersControl addControl -#' @importFrom leaflet layersControlOptions addProviderTiles scaleBarOptions providers leafletOptions -#' @importFrom leaflet.extras addSearchOSM searchOptions addFullscreenControl gpsOptions addControlGPS -#' @importFrom htmltools htmlEscape -#' @importFrom shiny tags -#' -#' @export -map_init_bassins <- function(bassins_data, id_logo_ign_remonterletemps) { - - # Build the BRGM legend URL - # legend_url <- modify_url("http://mapsref.brgm.fr/legendes/geoservices/Geologie1000_legende.jpg") - - leaflet() %>% - setView(lng = 2.468697, lat = 46.603354, zoom = 5) %>% - addPolygons(data = bassins_data, - layerId = ~cdbh, - fillColor = "black", - fillOpacity = ~opacity, - weight = 2, - color = "black", - opacity = 0.20, - highlightOptions = highlightOptions( - fillColor = "black", - fillOpacity = 0.5), - label = ~htmlEscape(lbbh), - options = pathOptions(clickable = ~click), - group = params_map_group()[["bassin"]] - ) %>% - addScaleBar(position = "bottomleft", - scaleBarOptions(metric = TRUE, imperial = FALSE)) %>% - addProviderTiles(providers$CartoDB.Positron) %>% - addSearchOSM(options = leaflet.extras::searchOptions(hideMarkerOnCollapse = TRUE)) %>% - addControlGPS(options = leaflet.extras::gpsOptions( - position = "topleft", - activate = FALSE, - autoCenter = FALSE, - maxZoom = NULL, - setView = FALSE - )) %>% - addFullscreenControl(pseudoFullscreen = TRUE) %>% - map_add_basemaps() %>% - addLayersControl( - baseGroups = c("CartoDB Positron", unlist(sapply(params_wms(), function(x) if (x$basemap) x$name else NULL), use.names = FALSE)), - options = layersControlOptions(collapsed = TRUE) - ) %>% - addControl( - className = "img_div_ign_remonterletemps", - position = "topleft", - html = tags$a(href = "javascript:void(0);", - tags$img( - id = id_logo_ign_remonterletemps, - src = "www/logo_ign_remonterletemps.jpg", - width = 50, height = 50, - title="Vers le site IGN remonterletemps")) - ) %>% - map_background(wms_params = params_wms()$background) -} - -#' Add hydrological Regions in a Bassin to an existing Leaflet Map -#' -#' This function adds regions within a bassin to an existing Leaflet map. -#' -#' @param map An existing Leaflet map to which regions will be added. -#' @param bassin_click A vector containing information about the clicked bassin. -#' @param regions_data A sf data.frame containing information about regions within the bassin. -#' @param bassins_data A sf data.frame with bassins data. -#' -#' @return An updated Leaflet map with regions added. -#' -#' @importFrom leaflet setView -#' @importFrom leaflet clearGroup -#' @importFrom leaflet addPolygons -#' @importFrom htmltools htmlEscape -#' -#' @examples -#' library(leaflet) -#' library(dplyr) -#' library(sf) -#' # Create init bassin map -#' my_map <- map_init_bassins(bassins_data = bassin_hydrographique, -#' id_logo_ign_remonterletemps = "logo_ign_remonterletemps") -#' -#' # simulate bassin selected -#' selected_bassin <- bassin_hydrographique -#' -#' # get centroid coordinate (in shiny see leaflet mapid_shape_click) -#' centre <- sf::st_centroid(selected_bassin) -#' centre_coord <- as.data.frame(st_coordinates(centre)) %>% -#' rename("lng" = X, -#' "lat" = Y) -#' # map region -#' map <- map_add_regions_in_bassin(map = my_map, -#' bassins_data = bassin_hydrographique, -#' bassin_click = centre_coord, -#' regions_data = region_hydrographique) -#' map -#' -#' @export -map_add_regions_in_bassin <- function(map, bassins_data, - bassin_click = bassin_click, - regions_data = region_hydro) { - map %>% - setView(lng = bassin_click$lng , lat = bassin_click$lat, zoom = 5.5) %>% - clearGroup(params_map_group()[["bassin"]]) %>% - addPolygons(data = bassins_data, - layerId = ~cdbh, - fillColor = "black", - fillOpacity = ~opacity, - weight = 2, - color = "black", - opacity = 0.20, - highlightOptions = highlightOptions( - fillColor = "#000000", - fillOpacity = 0.5), - label = ~htmlEscape(lbbh), - options = pathOptions(clickable = ~click), - group = params_map_group()[["bassin"]] - ) %>% - addPolygons(data = regions_data, - layerId = ~gid, - smoothFactor = 2, - fillColor = "black", - fillOpacity = ~opacity, - weight = 2, - color = "black", - highlightOptions = highlightOptions( - fillColor = "#a8d1ff", - fillOpacity = 0.5), - label = ~htmlEscape(lbregionhy), - options = pathOptions(clickable = ~click), - group = params_map_group()[["region"]] - ) -} - - -#' Update Leaflet Map for a Clicked Region -#' -#' This function updates an existing Leaflet map when a region is clicked, displaying the region and overlayers. -#' -#' @param map An existing Leaflet map to be updated. -#' @param region_click A vector containing information about the clicked region. -#' @param selected_region_feature A sf data frame containing information about the selected region feature. -#' @param regions_data A sf data.frame with the hydrographic regions of the bassin selected. -#' @param roe_region sf data.frame ROE in selected region. -#' @param hydro_sites_region sf data.frame hydrometric sites in selected region. -#' -#' @return An updated Leaflet map with relevant layers and information displayed. -#' -#' @importFrom leaflet setView layersControlOptions addPolygons addCircleMarkers addLayersControl hideGroup -#' @importFrom htmltools tags -#' -#' @examples -#' library(leaflet) -#' library(dplyr) -#' library(sf) -#' # Create init bassin map -#' map_bassin <- map_init_bassins(bassins_data = bassin_hydrographique, -#' id_logo_ign_remonterletemps = "logo_ign_remonterletemps") -#' -#' # simulate bassin selected -#' selected_bassin <- bassin_hydrographique -#' -#' # get centroid coordinate (in shiny see leaflet mapid_shape_click) -#' centre <- sf::st_centroid(selected_bassin) -#' centre_coord <- as.data.frame(st_coordinates(centre)) %>% -#' rename("lng" = X, -#' "lat" = Y) -#' -#' # map region -#' map_region <- map_add_regions_in_bassin(map = map_bassin, -#' bassins_data = bassin_hydrographique, -#' bassin_click = centre_coord, -#' regions_data = region_hydrographique) -#' # simulate selected region -#' selected_region <- region_hydrographique -#' -#' # get centroid coordinate (in shiny see leaflet mapid_shape_click) -#' centre_region <- sf::st_centroid(selected_bassin) -#' centre_region_coord <- as.data.frame(st_coordinates(centre_region)) %>% -#' rename("lng" = X, -#' "lat" = Y) -#' centre_region_coord$id <- 11 -#' -#'con <- db_con() -#' # get ROE in region -#' roe_region <- data_get_roe_in_region(centre_region_coord$id, con = con) -#' # get hydro sites in region -#' hydro_sites_region <- data_get_hydro_sites(centre_region_coord$id, con = con) -#' DBI::dbDisconnect(con) -#' -#' # map the element in the region clicked -#' map <- map_region_clicked(map = map_region, -#' region_click = centre_region_coord, -#' selected_region_feature = selected_region, -#' regions_data = region_hydrographique, -#' roe_region = roe_region, -#' hydro_sites_region = hydro_sites_region) -#' map -#' -#' @export -map_region_clicked <- function(map, - region_click, - selected_region_feature, - regions_data, - roe_region, - hydro_sites_region) { - map %>% - setView(lng = region_click$lng , lat = region_click$lat, zoom = 6.5) %>% - clearGroup(c(params_map_group()[["region"]], - params_map_group()[["roe"]], - params_map_group()[["hydro_sites"]], - params_map_group()[["dgo_axis"]], - params_map_group()[["dgo"]], - params_map_group()[["axis_start_end"]], - params_map_group()[["background"]], - unlist(sapply(params_wms(), function(x) if (x$overlayer) x$name else NULL), use.names = FALSE))) %>% - # restyle the regions - addPolygons(data = regions_data, - layerId = ~gid, - fillColor = "black", - fillOpacity = ~opacity, - weight = 2, - color = "black", - highlightOptions = highlightOptions( - fillColor = "#a8d1ff", - fillOpacity = 0.5), - label = ~htmlEscape(lbregionhy), - options = pathOptions(clickable = ~click), - group = params_map_group()[["region"]] - ) %>% - # add ROE overlayers from PostgreSQL - addCircleMarkers(data = roe_region, - radius = 4.5, - weight = 0.5, - opacity = 0.9, - color = "#D0D0D0", - fillColor = "#323232", - fillOpacity = 0.9, - popup = ~nomprincip, - group = params_map_group()[["roe"]] - ) %>% - # ROE layer hidden by default - hideGroup(params_map_group()[["roe"]]) %>% - addCircleMarkers(data = hydro_sites_region, - radius = 4.5, - weight = 0.5, - opacity = 0.9, - color = "#E5F6FF", - fillColor = "#33B1FF", - fillOpacity = 0.9, - popup = ~paste0("", libelle_site, ""), - group = params_map_group()[["hydro_sites"]] - ) %>% - # Hydrometric sites layer hidden by default - hideGroup(params_map_group()[["hydro_sites"]]) %>% - # add WMS overlayers - map_add_wms_overlayers() %>% - addLayersControl( - baseGroups = c("CartoDB Positron", unlist(sapply(params_wms(), function(x) if (x$basemap) x$name else NULL), use.names = FALSE)), - options = layersControlOptions(collapsed = TRUE), - overlayGroups = c(params_map_group()[["roe"]], - params_map_group()[["hydro_sites"]], - unlist(sapply(params_wms(), function(x) if (x$overlayer) x$name else NULL), use.names = FALSE)) - ) %>% - map_background(wms_params = params_wms()$background, - cql_filter = paste0("gid_region <>", selected_region_feature[["gid"]])) -} - -#' Map WMS metric -#' -#' This function adds WMS tiles with metric data to an existing Leaflet map, allowing for customization of style and filtering. -#' -#' @param map An existing Leaflet map to which WMS tiles will be added. -#' @param wms_params A list of WMS parameters. -#' @param cql_filter A CQL filter to apply to the WMS request. -#' @param sld_body A custom SLD (Styled Layer Descriptor) body for symbology customization. -#' -#' @return An updated Leaflet map with WMS tiles containing metric data added. -#' -#' @importFrom leaflet addWMSTiles WMSTileOptions -#' -#' @examples -#' \dontrun{ -#' # Used in map_metric() function, see full example in map_metric() documentation -#' } -#' -#' @export -map_wms_metric <-function(map, wms_params = params_wms()$metric, - cql_filter = "", sld_body = "") { - map %>% - addWMSTiles( - baseUrl = wms_params$url, - layers = wms_params$layer, - attribution = wms_params$attribution, - options = WMSTileOptions( - format = wms_params$format, - request = "GetMap", - transparent = TRUE, - styles = wms_params$style, - cql_filter = cql_filter, - sld_body = sld_body, - zIndex = 90 - ), - group = params_map_group()[["metric"]] - ) -} - -#' Map WMS class -#' -#' This function adds WMS tiles with a proposed style to an existing Leaflet map, allowing for customization of style and filtering. -#' -#' @param map An existing Leaflet map to which WMS tiles will be added. -#' @param wms_params A list of WMS parameters. -#' @param cql_filter A CQL filter to apply to the WMS request. -#' @param style character string specifying the name of the sld-styling to apply to the layer which is saved on geoserver -#' @param sld_body A custom SLD (Styled Layer Descriptor) body for symbology customization. -#' -#' @return An updated Leaflet map with WMS tiles containing classes data added. -#' -#' @importFrom leaflet addWMSTiles WMSTileOptions -#' -#' @examples -#' \dontrun{ -#' # Used in map_metric() function, see full example in map_metric() documentation -#' } -#' -#' @export -map_wms_class <- function(map, wms_params = params_wms()$class, - cql_filter = "", style = "", opacity = 1) { - map %>% - addWMSTiles( - baseUrl = wms_params$url, - layers = wms_params$layer, - attribution = wms_params$attribution, - options = WMSTileOptions( - format = wms_params$format, - request = "GetMap", - transparent = TRUE, - styles = style, - cql_filter = cql_filter, - opacity = opacity, - zIndex = 90 - ), - group = params_map_group()[["class"]] - ) -} - -#' Map WMS background with Strahler styling -#' -#' @param map An existing Leaflet map to which WMS tiles will be added. -#' @param wms_params A list of WMS parameters. -#' @param cql_filter A CQL filter to apply to the WMS request. -#' -#' @return An updated Leaflet map with WMS tiles of the Strahler-styled network added. -#' -#' @examples -#' map %>% -#' map_background(wms_params = params_wms()$background, cql_filter = "gid_region <> 11") -map_background <- function(map, wms_params, cql_filter = "") { - - map %>% - addWMSTiles( - baseUrl = wms_params$url, - layers = wms_params$layer, - attribution = wms_params$attribution, - options = WMSTileOptions( - format = wms_params$format, - request = "GetMap", - transparent = TRUE, - styles = wms_params$style, - cql_filter = cql_filter, - opacity = 0.7, - zIndex = 90 - ), - group = params_map_group()[["background"]] - ) -} - -#' Add Axis Data to an Existing Leaflet Map -#' -#' This function adds axis data as polylines to an existing Leaflet map. -#' -#' @param map An existing Leaflet map to which axis data will be added. -#' @param data_axis A sf data frame containing axis data. -#' -#' @return An updated Leaflet map with axis data added. -#' -#' @examples -#' \dontrun{ -#' # Used in map_metric() function, see full example in map_metric() documentation -#' } -#' -#' @importFrom leaflet addPolylines -#' -#' @export -map_axis <- function(map, data_axis) { - map %>% - addPolylines(data = data_axis, - layerId = ~axis, - weight = 5, - color = "#ffffff00", - opacity = 1, - label = ~toponyme, - highlightOptions = highlightOptions( - color = "red", - bringToFront = TRUE - ), - group = params_map_group()[["axis"]] - ) -} - - -#' Add a metric layer with custom symbology to a map. -#' -#' This function adds a metric layer with custom symbology to a leaflet map. It allows you to specify custom parameters for the Web Map Service (WMS) request, apply a CQL (Common Query Language) filter, and provide a custom SLD (Styled Layer Descriptor) body for styling the layer. Additionally, you can specify the data axis to display on the map. -#' -#' @param map A leaflet map object to which the metric layer will be added. -#' @param wms_params A list containing WMS parameters for the metric layer. If not provided, default parameters are retrieved using the \code{\link{params_wms}} function. -#' @param cql_filter A character string representing a CQL filter to apply to the metric layer. -#' @param sld_body A character string representing the SLD (Styled Layer Descriptor) body for custom styling of the metric layer. -#' @param data_axis A data axis to display on the map. -#' -#' @return A leaflet map object with the metric layer added. -#' -#' @examples -#' library(leaflet) -#' library(dplyr) -#' library(sf) -#' # Create init bassin map -#' map_bassin <- map_init_bassins(bassins_data = bassin_hydrographique, -#' id_logo_ign_remonterletemps = "logo_ign_remonterletemps") -#' -#' # simulate bassin selected -#' selected_bassin <- bassin_hydrographique -#' -#' # get centroid coordinate (in shiny see leaflet mapid_shape_click) -#' centre <- sf::st_centroid(selected_bassin) -#' centre_coord <- as.data.frame(st_coordinates(centre)) %>% -#' rename("lng" = X, -#' "lat" = Y) -#' -#' # map region -#' map_region <- map_add_regions_in_bassin(map = map_bassin, -#' bassins_data = bassin_hydrographique, -#' bassin_click = centre_coord, -#' regions_data = region_hydrographique) -#' -#' # simulate selected region -#' selected_region <- region_hydrographique -#' -#' # get centroid coordinate (in shiny see leaflet mapid_shape_click) -#' centre_region <- sf::st_centroid(selected_bassin) -#' centre_region_coord <- as.data.frame(st_coordinates(centre_region)) %>% -#' rename("lng" = X, -#' "lat" = Y) -#' centre_region_coord$id <- 11 -#' -#' con = db_con() -#' # get ROE in region -#' roe_region <- data_get_roe_in_region(centre_region_coord$id, con = con) -#' # get hydro sites in region -#' hydro_sites_region <- data_get_hydro_sites(centre_region_coord$id, con = con) -#' -#' -#' # map the element in the region clicked -#' map <- map_region_clicked(map = map_region, -#' region_click = centre_region_coord, -#' selected_region_feature = selected_region, -#' regions_data = region_hydrographique, -#' roe_region = roe_region, -#' hydro_sites_region = hydro_sites_region) -#' map -#' -#' # build geoserver WMS filter -#' cql_filter=paste0("gid_region=", selected_region[["gid"]]) -#' -#' # build geoserver SLD symbology -#' sld_body <- sld_get_style(breaks = sld_get_quantile_metric( -#' selected_region_id = selected_region[["gid"]], -#' selected_metric = "active_channel_width", -#' con = con), -#' colors = sld_get_quantile_colors( -#' quantile_breaks = sld_get_quantile_metric( -#' selected_region_id = selected_region[["gid"]], -#' selected_metric = "active_channel_width", -#' con = con)), -#' metric = "active_channel_width") -#'DBI::dbDisconnect(con) -#' -#' # Network axis by region -#' network_region_axis <- network_axis %>% -#' filter(gid_region == selected_region[["gid"]]) -#' -#' # Add metric with quantile symbology -#' # wms_params = params_wms()$metric_basic with sld_body = NULL for default blue style$ -#' map_metric <- map_metric(map = map, -#' wms_params = params_wms()$metric, -#' cql_filter = cql_filter, -#' sld_body = sld_body, -#' data_axis = network_region_axis) -#' map_metric -#' -#' @importFrom leaflet leaflet addTiles setView clearGroup addWMSTiles -#' @importFrom leaflet.extras addWMSLegend -#' -#' @export -map_metric <- function(map, wms_params = params_wms()$metric, - cql_filter = "", sld_body = "", data_axis) { - map %>% - clearGroup(params_map_group()[["axis"]]) %>% - clearGroup(params_map_group()[["metric"]]) %>% - clearGroup(params_map_group()[["class"]]) %>% - # add metric with custom symbology - map_wms_metric(wms_params = wms_params, - cql_filter = cql_filter, sld_body = sld_body) %>% - # add transparent axis - map_axis(data_axis = data_axis) %>% - addWMSLegend(uri = map_legend_metric(sld_body = sld_body), - position = "bottomright", - layerId = "legend_metric") -} - -#' Add a classified layer with proposed symbology to map -#' -#' This function adds the network layer with one of the proposed symbologys to a leaflet map. -#' It allows to specify custom parameters for the Web Map Service (WMS) request, apply a CQL (Common Query Language) filter, -#' and select a proposed SLD (Styled Layer Descriptor) body for styling the layer. Additionally, the data axis can be specified -#' to display on the map. -#' -#' @param map A leaflet map object to which the network layer will be added. -#' @param wms_params A list containing WMS parameters for the network layer. If not provided, default parameters are retrieved using the \code{\link{params_wms}} function. -#' @param cql_filter A character string representing a CQL filter to apply to the layer. -#' @param sld_body A character string representing the SLD (Styled Layer Descriptor) body for custom styling of the legend -#' @param style character string specifying the name of the sld-styling to apply to the layer which is saved on geoserver -#' @param data_axis A data axis to display on the map. -#' -#' @return A leaflet map object with the network layer added. -#' -#' @importFrom leaflet leaflet addTiles setView clearGroup addWMSTiles -#' @importFrom leaflet.extras addWMSLegend -#' -#' @export -map_class <- function(map, wms_params = params_wms()$class, - cql_filter = "", sld_body = "", style = "", data_axis) { - map %>% - clearGroup(params_map_group()[["axis"]]) %>% - clearGroup(params_map_group()[["metric"]]) %>% - clearGroup(params_map_group()[["class"]]) %>% - # add metric with custom symbology - map_wms_class(wms_params = wms_params, - cql_filter = cql_filter, style = style) %>% - # add transparent axis - map_axis(data_axis = data_axis) %>% - addWMSLegend(uri = map_legend_metric(sld_body = sld_body), - position = "bottomright", - layerId = "legend_metric") -} - -#' Add DGO axis to a Leaflet map -#' -#' This function adds DGO axis to a Leaflet map with the option to highlight selected axes. -#' -#' @param map A Leaflet map object. -#' @param selected_axis A data frame containing selected axe to be displayed. -#' @param region_axis A data frame containing region-specific axes to be displayed. -#' @param main_metric text with the main selected metric name. -#' @param second_metric text with the second axis selected metric name. -#' -#' @return A modified Leaflet map object with DGO axes added. -#' -#' @importFrom leaflet clearGroup addPolylines highlightOptions pathOptions -#' @importFrom htmltools HTML -#' -#' @examples -#' # Create a basic Leaflet map -#' library(leaflet) -#' library(dplyr) -#' -#' my_map <- leaflet() %>% -#' setView(lng = 4.968697, lat = 45.103354, zoom = 8) %>% -#' addProviderTiles(providers$CartoDB.Positron) -#' -#' # Define selected and region-specific axes data frames -#' selected_axes <- network_axis %>% filter(axis == 5) -#' region_axes <- network_axis -#' -#' # Add DGO axes to the map -#' my_map <- map_dgo_axis(my_map, selected_axes, region_axes, -#' main_metric = "active_channel_width", second_metric = "talweg_slope") -#' my_map -#' -#' @export -map_dgo_axis <- function(map, selected_axis, region_axis, main_metric, second_metric) { - - # create HTML conditional tooltip labels - tooltip_label <- lapply(paste0(' ', selected_axis$toponyme, '
', - ' ', round(selected_axis$measure, 2), ' km depuis l\'exutoire', ' '), - htmltools::HTML) - - map %>% - clearGroup(params_map_group()$dgo_axis) %>% - clearGroup(params_map_group()$axis) %>% - clearGroup(params_map_group()$dgo) %>% - map_axis(data_axis = region_axis) %>% - addPolylines( - data = selected_axis, - layerId = ~fid, - weight = 5, - color = "#ffffff00", - label = tooltip_label, - opacity = 1, - highlightOptions = highlightOptions( - opacity = 1, - color = "red" - ), - options = pathOptions(zIndex = 100), - group = params_map_group()$dgo_axis - ) -} - -#' Highlight DGO clicked for cross section. -#' -#' @param map A Leaflet map object. -#' @param selected_dgo sf dgo clicked. -#' -#' @importFrom leaflet clearGroup addPolylines pathOptions -#' -#' @return Leaflet map -#' @export -map_dgo_cross_section <- function(map, selected_dgo){ - map %>% - clearGroup(params_map_group()$dgo) %>% - addPolylines( - data = selected_dgo, - layerId = ~fid, - weight = 8, - color = "purple", - opacity = 1, - group = params_map_group()$dgo, - options = pathOptions(zIndex = 90) - ) - return(map) -} - - -#' Add start and end markers to a leaflet map -#' -#' This function adds start and end markers to a Leaflet map based on the provided -#' start and end coordinates. -#' -#' @param map A Leaflet map object created using the 'leaflet' package. -#' @param axis_start_end A data frame containing start and end coordinates with -#' columns 'X' for longitude and 'Y' for latitude. -#' @param region_axis A data frame containing region-specific axes to be displayed. -#' -#' @return A Leaflet map object with start and end markers added. -#' -#' @importFrom leaflet addMarkers clearGroup makeIcon pathOptions -#' @importFrom dplyr filter -#' -#' @examples -#' library(leaflet) -#' library(dplyr) -#' -#' # Create a simple Leaflet map -#' my_map <- leaflet() %>% -#' setView(lng = 4.968697, lat = 45.103354, zoom = 8) %>% -#' addProviderTiles(providers$CartoDB.Positron) -#' -#' # Create a data frame with start and end coordinates -#' coordinates_df <- data_get_axis_start_end(network_axis %>% -#' filter(fid == 5)) -#' -#' # Add start and end markers to the map -#' my_map <- map_axis_start_end(my_map, axis_start_end = coordinates_df, -#' region_axis = network_axis) -#' my_map -#' -#' @export -map_axis_start_end <- function(map, axis_start_end, region_axis) { - - # Define the start and end icon - start_end_icon <- makeIcon( - iconUrl = system.file("pin-sharp.png", package = "mapdoapp"), - iconWidth = 24, - iconHeight = 24, - iconAnchorX = 16, - iconAnchorY = 24 - ) - - # Clear the previous group of markers and add new markers to the map - map %>% - clearGroup(params_map_group()$axis_start_end) %>% - clearGroup(params_map_group()$axis_opacity) %>% - addMarkers( - lng = axis_start_end$X, - lat = axis_start_end$Y, - options = pathOptions(interactive = FALSE), - icon = start_end_icon, - group = params_map_group()$axis_start_end - ) %>% - addPolylines(data = region_axis, - layerId = ~axis, - weight = 5, - color = "white", - opacity = 0.4, - options = pathOptions(interactive = FALSE, - zIndex = 100), - group = params_map_group()$axis_opacity - ) -} - - -#' Add Basemap Layers to an Existing Leaflet Map -#' -#' This function adds basemap layers to an existing Leaflet map. -#' -#' @param map An existing Leaflet map to which basemap layers will be added. -#' -#' @return An updated Leaflet map with basemap layers added. -#' -#' @examples -#' \dontrun{ -#' # Used in map_init_bassins() function, its use is in the function -#' } -#' -#' @importFrom leaflet addWMSTiles addTiles tileOptions -#' -#' @export -map_add_basemaps <- function(map) { - for (i in params_wms()) { - if (i$basemap == TRUE){ - if ((i$name == "Occupation du sol") || (i$name == "Géologie")){ - map <- map %>% - addWMSTiles( - baseUrl = i$url, - layers = i$layer, - attribution = i$attribution, - options = WMSTileOptions( - format = i$format, - transparent = TRUE, - opacity = 0.6, - styles = i$style, - ), - group = i$name - ) - } else { - map <- map %>% - addTiles( - urlTemplate = i$url, - options = tileOptions( - attribution = i$attribution, - transparent = TRUE, - opacity = 0.7, - format = i$format, - style = i$style - ), - group = i$name - ) - } - - } - } - return(map) -} - - -#' Add Overlayer Layers to an Existing Leaflet Map -#' -#' This function adds overlayer layers to an existing Leaflet map. -#' -#' @param map An existing Leaflet map to which overlayer layers will be added. -#' -#' @return An updated Leaflet map with overlayer layers added. -#' -#' @examples -#' \dontrun{ -#' # Used in map_region_clicked() function, its use is in the function -#' } -#' -#' @importFrom leaflet addWMSTiles hideGroup -#' -#' @export -map_add_wms_overlayers <- function(map) { - for (i in params_wms()) { - if (i$overlayer == TRUE){ - map <- map %>% - addWMSTiles( - baseUrl = i$url, - layerId = i$name, - layers = i$layer, - attribution = i$attribution, - options = WMSTileOptions( - format = i$format, - transparent = TRUE - ), - group = i$name - ) %>% - hideGroup(i$name) - } - } - return(map) -} - - -#' Generate and display a legend for a map layer using a provided SLD (Styled Layer Descriptor) body. -#' -#' This function constructs a legend for a map layer by sending a GetLegendGraphic request to a WMS (Web Map Service) server. -#' -#' @param sld_body A character string containing the SLD (Styled Layer Descriptor) body that defines the map layer's styling. -#' -#' @return An HTML img tag representing the legend for the specified map layer. -#' -#' @importFrom httr modify_url -#' @importFrom htmltools tags -#' -#' @examples -#' con <- db_con() -#' # Define an SLD body for a map layer -#' sld_body <- sld_get_style(breaks = sld_get_quantile_metric( -#' selected_region_id = 11, -#' selected_metric = "active_channel_width", -#' con = con), -#' colors = sld_get_quantile_colors( -#' quantile_breaks = sld_get_quantile_metric( -#' selected_region_id = 11, -#' selected_metric = "active_channel_width", -#' con = con)), -#' metric = "active_channel_width") -#' DBI::dbDisconnect(con) -#' -#' # Generate and display the legend for the map layer -#' legend <- map_legend_metric(sld_body) -#' -#' @export -map_legend_metric <- function(sld_body){ - - # Construct the query parameters for legend - query_params <- list( - REQUEST = "GetLegendGraphic", - VERSION = params_wms()$metric$version, - FORMAT = params_wms()$metric$format, - SLD_BODY = sld_body, - LAYER = params_wms()$metric$layer - ) - - # Build the legend URL - legend_url <- modify_url(params_wms()$metric$url, query = query_params) - - return(legend_url) -} - - -#' Generate and display a legend for a WMS (Web Map Service) layer overlay using specified WMS parameters. -#' -#' This function constructs a legend for a WMS layer overlay by sending a GetLegendGraphic request to a WMS server. -#' -#' @param wms_params A list containing the following parameters for the WMS layer overlay: -#' \itemize{ -#' \item \code{language} (character): The language to use for the legend. -#' \item \code{version} (character): The version of the WMS service. -#' \item \code{service} (character): The WMS service type (e.g., "WMS"). -#' \item \code{sld_version} (character): The SLD (Styled Layer Descriptor) version. -#' \item \code{layer} (character): The name of the WMS layer for which the legend is generated. -#' \item \code{format} (character): The desired format of the legend image (e.g., "image/png"). -#' \item \code{style} (character): The style to use for rendering the legend. -#' \item \code{url} (character): The URL of the WMS server. -#' } -#' -#' @return An HTML div element containing an img tag representing the legend for the specified WMS layer overlay. -#' -#' @importFrom httr modify_url -#' @importFrom htmltools div -#' @importFrom htmltools img -#' -#' @examples -#' # Define WMS parameters for a layer overlay like -#' wms_params <- params_wms()$inondation -#' -#' # Generate and display the legend for the WMS layer overlay -#' legend <- map_legend_wms_overlayer(wms_params) -#' print(legend) -#' -#' @export -map_legend_wms_overlayer <- function(wms_params){ - - # Construct the query parameters for legend - query_params <- list( - LANGUAGE = wms_params$language, - VERSION = wms_params$version, - SERVICE = wms_params$service, - REQUEST = "GetLegendGraphic", - SLD_VERSION = wms_params$sld_version, - LAYER = wms_params$layer, - FORMAT = wms_params$format, - STYLE = wms_params$style - ) - - # Build the legend URL - legend_url <- modify_url(wms_params$url, query = query_params) - - return(legend_url) -} - - -#' Generate a legend entry for a vector overlay layer. -#' -#' This function generates an HTML representation of a legend entry for a vector overlay layer. The legend entry consists of a colored circle with a label indicating the layer's name. -#' -#' @param layer_label A character string representing the label or name of the vector overlay layer. -#' @param color text the legend marker color. -#' -#' @return An HTML div element representing the legend entry for the vector overlay layer. -#' -#' @examples -#' # Create a legend entry for a vector overlay layer -#' legend_entry <- map_legend_vector_overlayer(layer_label = "ROE", color = "blue") -#' print(legend_entry) -#' -#' @importFrom htmltools div span -#' @importFrom glue glue -#' -#' @export -map_legend_vector_overlayer <- function(layer_label, color){ - - div( - style = "display: flex; align-items: center;", - div( - style = glue::glue("background-color: {color}; - border-radius: 50%; width: 10px; - height: 10px; margin-top: 3px;"), - "" - ), - span( - style = "margin-left: 5px; font-size: 0.8rem;", - layer_label - ) # span - ) # div -} - - diff --git a/R_old/fct_params.R b/R_old/fct_params.R deleted file mode 100644 index e22e8f9..0000000 --- a/R_old/fct_params.R +++ /dev/null @@ -1,523 +0,0 @@ -#' Define Web Map Service (WMS) parameters for different map layers and basemaps. -#' -#' This function defines a set of WMS parameters for various map layers and basemaps. The parameters include information such as the layer name, URL of the WMS server, version, format, style, and more. These parameters are organized into a list, making it easy to configure and access them for map display and legend generation. -#' -#' @return A list containing WMS parameters for different map layers and basemaps. -#' -#' @examples -#' # Retrieve WMS parameters for a specific map layer -#' wms_params <- params_wms() -#' metric_wms_params <- wms_params$metric -#' -#' # Access specific WMS parameters -#' metric_name <- metric_wms_params$name -#' metric_url <- metric_wms_params$url -#' -#' @export -params_wms <- function(){ - wms <- list(metric = list(name = "Métrique", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.0.0", - sld_version = "", - layer = "mapdo:network_metrics", - format = "image/png", - sld = "", - style = "", # no style, sld_body define style and legend - attribution = "CNRS - EVS", - basemap = FALSE, - overlayer = FALSE), - class = list(name = "Style Fluvial", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.1.0", - sld_version = "", - layer = "mapdo:network_metrics", - format = "image/png", - sld = "", - style = "", # no style, will be defined depending on selection - attribution = "CNRS - EVS", - basemap = FALSE, - overlayer = FALSE), - background = list(name = "Background", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.1.0", - sld_version = "", - layer = "mapdo:network_metrics", - format = "image/png", - sld = "", - style = "mapdo:classes_proposed_strahler", - attribution = "CNRS - EVS", - basemap = FALSE, - overlayer = FALSE), - carteign = list(name = "Plan IGN", - url = 'https://data.geopf.fr/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER=GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', - language = "", - service = "WMTS", - version = "", - sld_version = "", - layer = "GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2", - format = "image/png", - sld = "", - style = "normal", - attribution = "IGN-F/Géoportail", - basemap = TRUE, - overlayer = FALSE), - ortho = list(name = "Satellite IGN", - url = 'https://data.geopf.fr/wmts?REQUEST=GetTile&SERVICE=WMTS&VERSION=1.0.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}', - language = "", - service = "WMTS", - version = "", - sld_version = "", - layer = "HR.ORTHOIMAGERY.ORTHOPHOTOS", - format = "image/jpeg", - sld = "", - style = "normal", - attribution = "IGN-F/Géoportail", - basemap = TRUE, - overlayer = FALSE), - # elevation = list(name = "Elévation IGN", - # url = 'https://data.geopf.fr/wms-r?REQUEST=GetTile&SERVICE=WMS&VERSION=1.3.0&STYLE={style}&TILEMATRIXSET=PM&FORMAT={format}&LAYER=ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES&tilePixelRatio=0', - # language = "", - # service = "WMS", - # version = "", - # sld_version = "", - # layer = "ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES", - # format = "image/jpeg", - # sld = "", - # style = "normal", - # attribution = "IGN-F/Géoportail", - # basemap = TRUE, - # overlayer = FALSE), - landuse = list(name = "Occupation du sol", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.0.0", - sld_version = "", - layer = "mapdo:mapdo_landuse_1m", - format = "image/png", - sld = "", - style = "mapdo:MAPDO landuse", - attribution = "CNRS - EVS", - basemap = TRUE, - overlayer = FALSE), - geologie = list(name = "Géologie", - url = "http://geoservices.brgm.fr/geologie", - language = "", - service = "WMS", - version = "", - sld_version = "", - layer = "GEOLOGIE", - format = "image/png", - sld = "", - style = "", - attribution = "BRGM", - basemap = TRUE, - overlayer = FALSE), - detrend_dem = list(name = "MNT détendancé", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.0.0", - sld_version = "", - layer = " mapdo:mapdo_nearest_height_hillshade_1m ", - format = "image/png", - sld = "", - style = "", - attribution = "CNRS - EVS", - basemap = FALSE, - overlayer = TRUE), - valley_bottom = list(name = "Fond de vallée", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.0.0", - sld_version = "", - layer = "mapdo:mapdo_valley_bottom_1m", - format = "image/png", - sld = "", - style = "mapdo:MAPDO valley bottom", - attribution = "CNRS - EVS", - basemap = FALSE, - overlayer = TRUE), - continuity = list(name = "Continuité latérale", - url = Sys.getenv("GEOSERVER"), - language = "", - service = "WMS", - version = "1.0.0", - sld_version = "", - layer = "mapdo:mapdo_continuity_1m", - format = "image/png", - sld = "", - style = "mapdo:MAPDO continuity", - attribution = "CNRS - EVS", - basemap = FALSE, - overlayer = TRUE), - inondation = list(name = "Zone inondable débordement centenale", - url = "https://georisques.gouv.fr/services", - language = "fre", - service = "WMS", - version = "1.3.0", - sld_version = "1.1.0", - layer = "ALEA_SYNT_01_02MOY_FXX", - format = "image/png", - sld = "", - style = "inspire_common:DEFAULT", - attribution = "Georisques", - basemap = FALSE, - overlayer = TRUE), - ouvrage_protection = list(name = "Ouvrage protection inondation", - url = "https://georisques.gouv.fr/services", - language = "fre", - service = "WMS", - version = "1.3.0", - sld_version = "1.1.0", - layer = "OUV_PROTECTION_FXX", - format = "image/png", - sld = "", - style = "inspire_common:DEFAULT", - attribution = "Georisques", - basemap = FALSE, - overlayer = TRUE) - ) - return(wms) -} - - -#' Get Parameters for Map Layer Groups -#' -#' This function returns a list of parameters representing different map layer groups. -#' -#' @return A list of parameters including names for groups such as "BASSIN," "REGION," "SELECT_REGION," "METRIC," "AXIS," "LEGEND," and "ROE". -#' -#' @examples -#' # all group available -#' map_group_params <- params_map_group() -#' # get specific group name -#' map_metric_group <- params_map_group()$metric -#' map_selected_region_group <- params_map_group()$select_region -#' -#' @export -params_map_group <- function(){ - params <- list( - bassin = "BASSIN", - region = "REGION", - select_region = "SELECT_REGION", - metric = "METRIC", - class = "CLASS", - background = "BACKGROUND", - axis = "AXIS", - dgo_axis = "DGOAXIS", - dgo = "DGO", - axis_start_end = "AXIS_START_END", - axis_opacity = "AXIS_OPACITY", - legend = "LEGEND", - roe = "ROE", - hydro_sites = "Site hydrométrique", - light = "LIGHT", - inondation = params_wms()$inondation$name, - ouvrage_protection = params_wms()$ouvrage_protection$name, - landuse = params_wms()$landuse$name, - continuity = params_wms()$continuity$name, - valley_bottom = params_wms()$valley_bottom$name, - detrend_dem = params_wms()$detrend_dem$name, - carteign = params_wms()$carteign$name, - ortho = params_wms()$ortho$name, - elevation = params_wms()$elevation$name, - geologie = params_wms()$geologie$name - ) - - return(params) -} - -#' get nested list-object with all variables for Metric-selection in selectInput()-Elements -#' -#' @importFrom dplyr filter pull -#' -#' @return list-object with first level the names of metric types and second levels the corresponding metrics for each type -#' -#' @examples -#' params_get_metric_choices() -params_get_metric_choices <- function(){ - # get parameters and create empty list object - metric_info <- params_metrics() - input <- list() - - # loop through all types and store metric names - for (type in unique(metric_info$metric_type_title)) { - input[type] <- list( - metric_info |> - dplyr::filter(metric_type_title == type) |> - dplyr::pull(metric_name) |> - setNames( - metric_info |> - dplyr::filter(metric_type_title == type) |> - dplyr::pull(metric_title) - ) - ) - } - return(input) -} - -#' Get Metric parameters -#' -#' This function returns a nested list of metrics, their names and titles used for plots as well as their description. -#' Can for example be used for the creation of a selectInput of metrics. -#' -#' @importFrom tibble tibble -#' -#' @return A table of all metrics and corresponding info -#' -#' @examples -#' metric_choices <- params_metrics() -#' -#' @export -params_metrics <- function(){ - - metric_info <- tibble( - metric_name = c("talweg_elevation_min", "active_channel_width", "natural_corridor_width", "connected_corridor_width", - "valley_bottom_width", "talweg_slope", "floodplain_slope", "water_channel_pc", "gravel_bars_pc", - "natural_open_pc", "forest_pc", "grassland_pc", "crops_pc", "diffuse_urban_pc", "dense_urban_pc", - "infrastructures_pc", "water_channel", "gravel_bars", "natural_open", "forest", "grassland", "crops", - "diffuse_urban", "dense_urban", "infrastructures", "active_channel_pc", "riparian_corridor_pc", - "semi_natural_pc", "reversible_pc", "disconnected_pc", "built_environment_pc", "active_channel", - "riparian_corridor", "semi_natural", "reversible", "disconnected", "built_environment", - "idx_confinement"), - metric_type_title = c("Elévation (m)", "Largeurs (m)", "Largeurs (m)", "Largeurs (m)", "Largeurs (m)", "Pentes (%)", - "Pentes (%)", "Occupation du sol (%)", "Occupation du sol (%)", "Occupation du sol (%)", - "Occupation du sol (%)", "Occupation du sol (%)", "Occupation du sol (%)", "Occupation du sol (%)", - "Occupation du sol (%)", "Occupation du sol (%)", "Occupation du sol (ha)", "Occupation du sol (ha)", - "Occupation du sol (ha)", "Occupation du sol (ha)", "Occupation du sol (ha)", "Occupation du sol (ha)", - "Occupation du sol (ha)", "Occupation du sol (ha)", "Occupation du sol (ha)", "Continuité latérale (%)", - "Continuité latérale (%)", "Continuité latérale (%)", "Continuité latérale (%)", "Continuité latérale (%)", - "Continuité latérale (%)", "Continuité latérale (ha)", "Continuité latérale (ha)", "Continuité latérale (ha)", - "Continuité latérale (ha)", "Continuité latérale (ha)", "Continuité latérale (ha)", "Indice"), - metric_title = c("Elévation (m)", "Chenal actif (m)", "Corridor naturel (m)", "Corridor connecté (m)", - "Fond de vallée (m)", "Pente talweg (%)", "Pente fond de vallée (%)", "Surface en eau (%)", - "Banc sédimentaire (%)", "Espace naturel ouvert (%)", "Forêt (%)", "Prairie permanente (%)", - "Culture (%)", "Périurbain (%)", "Urbain dense (%)", "Infrastructure de transport (%)", "Surface en eau (ha)", - "Banc sédimentaire (ha)", "Espace naturel ouvert (ha)", "Forêt (ha)", "Prairie permanente (ha)", - "Culture (ha)", "Périurbain (ha)", "Urbain dense (ha)", "Infrastructure de transport (ha)", - "Bande active (%)", "Corridor naturel (%)", "Corridor semi-naturel (%)", "Espace de réversibilité (%)", - "Espace déconnecté (%)", "Espace artificialisé (%)", "Bande active (ha)", "Corridor naturel (ha)", - "Corridor semi-naturel (ha)", "Espace de réversibilité (ha)", "Espace déconnecté (ha)", - "Espace artificialisé (ha)", "Indice de confinement"), - metric_description = c("Elévation minimale du talweg.", "Surface en eau et bancs sédimentaires.", - "Surface en eau, bancs sédimentaires et végétation rivulaire connectée.", - "Surface en eau, bancs sédimentaires, végétation rivulaire connectée et surfaces agricoles connectées.", - "Fond de vallée déterminé par seuil de pente et d'élévation.", "Pente moyenne du talweg.", - "Pente moyenne du fond de vallée.", "Surface en eau définie par la BD TOPO® de l'IGN. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Surface des eaux intermittentes de la BD TOPO® de l'IGN. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone de végétation ouverte telles que les forêts ouvertes, les haies ou bandes ligneuses. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone de végétation fermée. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Parcelle de prairie permanente définie dans le RPG®. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone de culture rassemblant les grandes cultures, l'arboriculture et les vignes. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone d'habitation diffus proche de la zone d'habitation de la BD TOPO®. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone continue de l'espace bâti dense ou artificialisée. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Infrastructure routière et ferroviaire. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Surface en eau définie par la BD TOPO® de l'IGN. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Surface des eaux intermittentes de la BD TOPO® de l'IGN. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone de végétation ouverte telles que les forêts ouvertes, les haies ou bandes ligneuses. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone de végétation fermée. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Parcelle de prairie permanente définie dans le RPG®. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone de culture rassemblant les grandes cultures, l'arboriculture et les vignes. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone d'habitation diffus proche de la zone d'habitation de la BD TOPO®. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone continue de l'espace bâti dense ou artificialisée. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Infrastructure routière et ferroviaire. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Les surfaces en eau et les bancs sédimentaires connectés. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Le chenal actif avec la végétation ouverte et fermée connectée. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Le corridor naturel avec les prairies permanentes connectées. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Le corridor semi-naturel avec les cultures connectées. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Espace non urbanisé déconnecté du corridor fluvial par des infrastructures ou du bâti. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone bâti, dense ou peu dense, et les infrastructures de transport. La surface est exprimée en pourcentage du fond de vallée découpée à partir des tronçons de 200m du réseau hydrographique.", - "Les surfaces en eau et les bancs sédimentaires connectés. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Le chenal actif avec la végétation ouverte et fermée connectée. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Le corridor naturel avec les prairies permanentes connectées. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Le corridor semi-naturel avec les cultures connectées. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Espace non urbanisé déconnecté du corridor fluvial par des infrastructures ou du bâti. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Zone bâti, dense ou peu dense, et les infrastructures de transport. La surface est exprimée en hectares découpée à partir des tronçons de 200m du réseau hydrographique.", - "Ratio de la largeur de la bande active sur la largeur du fond de vallée. Il permet d'estimer si le cours d'eau est contraint par la topographie. Plus l'indice est faible plus le cours d'eau a d'espace potentiel pour s'élargir.") - ) - return(metric_info) -} - - -#' Get names and description for proposed classifications -#' -#' @importFrom tibble tibble -#' -#' @return tibble with names of classes and their descriptions -#' @export -#' -params_classes <- function() { - - df <- tibble( - class_title = c( - "Nombre de Strahler", - "Topographie", - "Utilisation dominante des sols", - "Pression urbaine", - "Pression agricole", - "Utilisation naturelle des sols", - "Présence de bancs sédimentaires", - "Confinement de la bande active", - "Connectivité des habitats riverains" - ), - description = c( - # strahler - "Répresent la complexité du réseaux hydrographique. Le nombre de Strahler est de 1 pour tout cours d'eau entre sa source et sa première confluence et mont avec chaque confluence.", - # topographie - "Classification simple basée sur la pente et la hauteur du cours de la rivière : - - plaines de basse altitude (> 0 m & < 0.5 % pente) - - plaines de moyenne altitude (> 300 m & < 0.5 % pente) - - plaines de montagne (> 1000 m & < 0.5 % pente) - - pentes de basse altitude (> 0 m & > 0.5 % pente) - - pentes de moyenne altitude (> 300 m & > 0.5 % pente) - - pentes de montagne (> 1000 m & > 0.5 % pente) - ", - # dominant land use - "Indique la classe d'utilisation des sols la plus dominante dans la zone du fond de vallée de chaque segment de cours d'eau : - - Forêt - - Prairies - - Cultures - - Espaces construits (zones urbaines et infrastructures) - ", - # urban areas - "Indique le degré de couverture urbaine du fond de vallée du segment : - - fortement urbanisé (> 70 % zones construites) - - urbanisé (> 40 % zones construites) - - modérément urbanisé (> 10 % zones construites) - - Presque pas/pas urbanisé (< 10 % zones construites)", - # agriculture - "indique la part de l'utilisation des terres agricoles dans la zone du fond de vallée de chaque segment de cours d'eau - - Forte impact agricole (> 70 % cultures) - - Impact agricole élevé (> 40 % cultures) - - Impact agricole modéré (> 10 % cultures) - - Presque pas/pas d'impact agricole (< 10 % cultures)", - # natural - "indique la part de l'occupation naturelle des sols dans la zone du fond de vallée de chaque tronçon fluvial : - - Très forte utilisation naturelle (> 70 % espaces naturels) - - Forte utilisation naturelle (> 40 % espaces naturels) - - Utilisation naturelle modérée (> 10 % espaces naturels) - - Presque pas/pas naturelle (< 10 % espaces naturels)", - # gravel bars - "la présence de bancs sédimentaires. Basé sur le ratio entre la surface des sédiments et la surface du chenal actif, qui se compose des surfaces de sédiments et d'eau : - - Absent (pas des bancs sédimentaires) - - occasionnel (bancs sédimentaires < 50 % du chenal actif) - - fréquent (bancs sédimentaires >= 50 % du chenal actif)", - # confinement - "Indique le dégrée du confinement du chenal actif. Basé sur le ratio entre la largeur du chenal actif et la largeur du fond de la vallée. - - espace abondant (chenal actif > 70 % du fond de la vallée) - - modérement espace (chenal actif > 40 % du fond de la vallée) - - confiné (chenal actif > 10 % du fond de la vallée) - - très confiné (chenal actif < 10 % du fond de la vallée)", - # habitat connectivity - "Indique la présence d'un corridor riverain naturel. Basé sur ratio de la surface du corridor connecté (comprenant le chenal actif, le corridor naturel et les corridors semi-naturels) et le fond de la vallée : - - très bien connecté (>= 70 %) - - bien connecté (>= 40 %) - - moyen connecté (>= 10 % ) - - faible / absente (< 10 %)" - ), - class_name = c( - "class_strahler", - "class_topographie", - "class_lu_dominante", - "class_urban", - "class_agriculture", - "class_nature", - "class_gravel", - "class_confinement", - "class_habitat" - ), - sld_style = c( - "classes_proposed_strahler", - "classes_proposed_topographie", - "classes_proposed_lu_dominante", - "classes_proposed_urban", - "classes_proposed_agriculture", - "classes_proposed_nature", - "classes_proposed_gravel", - "classes_proposed_confinement", - "classes_proposed_habitat" - ) - ) %>% - # join sld styles - left_join(sld_get_fluvialstyles(), by = join_by(class_name)) - - return(df) -} - -#' Get classes names and colors for proposed classifications -#' -#' @return list with classes names and colors, identifiable by each classification-name -#' -#' @examples -#' params_classes_colors()$class_habitat -params_classes_colors <- function() { - - df <- list() - # STRAHLER - df$class_strahler <- c("#64b5f6", "#1e88e5", "#1976d2", "#1565c0", "#0d47a1", "#0a2472") %>% - setNames(c(1,2,3,4,5,6)) - - # TOPOGRAPHY - df$class_topographie <- c( "#bb3e03", "#e9d8a6", "#a3b18a", - "#780000","#ee9b00", "#3a5a40") %>% - setNames( - c("Plaines de montagne", - "Plaines de moyenne altitude", - "Plaines de basse altitude", - "Pentes de montagne", - "Pentes de moyenne altitude", - "Pentes de basse altitude") - ) - - # LU DOMINANT - df$class_lu_dominante <- c("#2d6a4f", "#99d98c", "#ffdd00", "#ba181b") %>% - setNames(c("forest_pc", "grassland_pc", "crops_pc", "built_environment_pc")) - - # URBAN - df$class_urban <- c("#6a040f", "#dc2f02", "#ffdd00", "#74c69d") %>% - setNames( - c("fortement urbanisé", "urbanisé", "modérément urbanisé", "Presque pas/pas urbanisé") - ) - - # AGRICULTURE - df$class_agriculture <- c("#6a040f", "#dc2f02", "#ffdd00", "#74c69d") %>% - setNames( - c("Forte impact agricole", "Impact agricole élevé", - "Impact agricole modéré", "Presque pas/pas d'impact agricole") - ) - - # NATURE - df$class_nature <- c("#081c15", "#2d6a4f", "#74c69d", "#d8f3dc") %>% - setNames( - c("Très forte utilisation naturelle", "Forte utilisation naturelle", - "Utilisation naturelle modérée", "Presque pas/pas naturelle") - ) - - # GRAVEL BARS - df$class_gravel <- c("#603808", "#e7bc91", "#0077b6") %>% - setNames( - c("abundant", "moyennement présente", "absent") - ) - - # CONFINEMENT - df$class_confinement <- c("#2d6a4f", "#99d98c", "#ffdd00", "#ba181b") %>% - setNames( - c("espace abondant", "modérement espace", "confiné", "très confiné") - ) - - # HABITAT CONNECTIVITY - df$class_habitat <- c("#2d6a4f", "#99d98c", "#ffdd00", "#ba181b") %>% - setNames( - c("très bien connecté", "bien connecté", "moyen connecté", "faible / absente") - ) - - return(df) -} diff --git a/R_old/fct_plots.R b/R_old/fct_plots.R deleted file mode 100644 index 435990c..0000000 --- a/R_old/fct_plots.R +++ /dev/null @@ -1,280 +0,0 @@ -#' Combine classified regional network and axis network in one frame -#' -#' @param data_region sf-df with all dgos of selected region -#' @param data_axis sf-df with all dgos of selected axis -#' @param var variable for which classification was undertaken -#' @param classes binary stating whether networks contain classes which should be selected as well -#' -#' @importFrom dplyr mutate add_row select -#' @importFrom sf st_drop_geometry -#' @importFrom stats na.omit -#' -#' @return merged df with regional and axis dgos, identifiable by factor-variable "scale" -#' -#' @examples -#' merge_regional_axis_dfs(data_classified, -#' data_classified %>% filter(toponyme == "l'Isère"), -#' "forest_pc") -merge_regional_axis_dfs <- function(data_region, data_axis, var, classes = FALSE){ - - # check if axis data exist - if (is.null(data_axis)) { - df <- - data_region %>% - mutate(scale = as.factor("Region")) %>% - sf::st_drop_geometry() - } - else { - df <- - data_region %>% - mutate(scale = as.factor("Region")) %>% - add_row( - data_axis %>% - mutate(scale = as.factor("Axe fluvial")) - ) %>% - sf::st_drop_geometry() - } - - - if (classes == TRUE) { - df <- df %>% - select(fid, class_name, color, scale, {{var}}) %>% - na.omit() - } else { - df <- df %>% - select(fid, scale, {{var}}) %>% - na.omit() - } - - return(df) -} - - -#' create dataframe of color-classes and values -#' -#' @param data classified network with corresponding colors for each class -#' -#' @importFrom dplyr select -#' @importFrom tibble deframe -#' @importFrom sf st_drop_geometry -#' -#' @return color vector -#' -#' @examples -#' get_colors_char_df(network) -get_colors_char_df <- function(data){ - df <- - data %>% - sf::st_drop_geometry() %>% # remove geometry if sf-object - dplyr::select(class_name, color) %>% - unique() %>% - tibble::deframe() - - return(df) -} - - -#' Create interactive stacked barplots of class-distribution for region and axis -#' -#' @param data classified network data with entries for regional and axis dgos -#' @param colors color vector -#' -#' @importFrom dplyr count group_by mutate ungroup -#' @importFrom plotly plot_ly layout event_register -#' -#' @return interactive stacked barplot with class distribution in % for each scale-group (region and axis) -#' -#' @examples -#' create_plotly_barplot(data_plots) -create_plotly_barplot <- function(data){ - - # create color-vector - colors <- get_colors_char_df(data) - - # create summary df - data_plots_summarized <- data %>% - count(class_name, scale) %>% - group_by(scale) %>% - mutate(share = round((n / sum(n) * 100), 2)) %>% - ungroup() - - - # Create the stacked bar plot - plot <- - plotly::plot_ly(data = data_plots_summarized, - x = ~scale, - y = ~share, - color = ~class_name, - colors = colors, - type = 'bar', - text = ~paste0("Classe ", class_name, ": ", share, " % \n (", n, " tronçons)"), - hoverinfo = 'text', - marker = list(line = list(color = 'white', width = 2)), - source = 'B' - ) %>% - plotly::layout( - barmode = 'stack', - bargap = 0.5, - title = "Proportion de classes", - xaxis = list(title = "", showgrid = F), - yaxis = list(title = "Pourcentage", showgrid = T, showticklabels = T), - showlegend = FALSE - ) - - return(plot) -} - -#' Create interactive violinplots for a specific variable for region and axis -#' -#' @param data classified network data with entries for regional and axis dgos -#' @param var variable based on which the violinplots should be created -#' -#' @importFrom plotly plot_ly layout event_register -#' @importFrom stats as.formula -#' -#' @return plotly interactive violinplots for each scale-group (region and axis) -#' -#' @examples -#' violinplot_plotly <- create_plotly_violinplot(data_plots, "forest_pc") -create_plotly_violinplot <- function(data, var, var_title){ - - plot <- plotly::plot_ly(data = data, - x = ~scale, - y = as.formula(paste0("~`", var, "`")), - type = 'violin', - meanline = list(visible = TRUE), - points = 'all', - jitter = 0.1, - color = I("black"), - alpha = 0.1, - scalemode = 'width', - marker = list(size = 1, color = "black"), - spanmode = "hard", - hoverinfo = 'y', - source = 'V') %>% - plotly::layout( - xaxis = list(title = "", showgrid = FALSE, - categoryorder = "array", categoryarray = c('Région', 'Axe')), - yaxis = list(title = var_title, side = 'left'), - showlegend = FALSE - ) - - return(plot) -} - - -#' Create a Biplot with Linear Regression and Statistical Annotations -#' -#' This function creates a biplot using the `echarts4r` library that displays a scatterplot -#' of two metrics from a given dataframe, fits a linear regression line, and shows key -#' statistical measures (correlation, R², p-value) in a floating text box. -#' -#' @param df A data frame containing the metrics to be plotted. -#' @param metric_x A string specifying the name of the x-axis metric (column in the dataframe). -#' @param metric_y A string specifying the name of the y-axis metric (column in the dataframe). -#' -#' @importFrom echarts4r e_charts_ e_scatter_ e_line e_axis_labels e_x_axis e_y_axis e_legend e_tooltip e_text_g e_toolbox_feature e_show_loading e_visual_map_ -#' @return An `echarts4r` plot object showing the biplot, regression line, and statistical annotations. -#' @examples -#' create_analysis_biplot_echarts(df = mtcars, metric_x = "mpg", metric_y = "wt") -#' @export -create_analysis_biplot_echarts <- function(df, metric_x, metric_y, classes = FALSE, lm = FALSE) { - - browser() - - # Get metric titles - metric_x_title <- globals$metrics_params |> filter(metric_name == metric_x) |> pull(metric_title) - metric_y_title <- globals$metrics_params |> filter(metric_name == metric_y) |> pull(metric_title) - - # removing any rows with missing values (NA) - data <- df %>% na.omit() - - if (lm) { - # Compute linear regression - lm_model <- lm(data[[metric_y]] ~ data[[metric_x]], data = data) - data$lm <- predict(lm_model) - - # Compute correlation, R², and p-value - correlation <- cor.test(data[[metric_x]], data[[metric_y]]) - r_value <- round(correlation$estimate, 2) - p_value <- round(correlation$p.value, 4) - r_squared <- round(r_value^2, 2) - - # Extract the coefficients for the linear model and create the equation - coefficients <- coef(lm_model) - intercept <- round(coefficients[1], 2) # Intercept (b) - slope <- round(coefficients[2], 2) # Slope (m) - - # Format the formula as "y = mx + b" - formula_text <- sprintf("y = %sx + %s", slope, intercept) - - linear_dependency_text <- sprintf("%s, R = %s, R² = %s, p-value = %s", - formula_text, r_value, r_squared, p_value) - } - - # Create the biplot using echarts4r with either z-metric selected or not - if (classes) { - - # proposition by chatgpt - plot <- data %>% - group_by(class_name) %>% # Group by color to create separate series - e_charts_(metric_x) %>% # Initialize the plot and specify the x-axis metric - # Add scatter series for each color group - e_scatter_(metric_y, bind = "measure", symbol_size = 6) %>% - e_color(color = rev(unique(unname(data$color)))) - - } - - else { - plot <- data %>% - e_charts_(metric_x) %>% # Initialize the plot and specify the x-axis metric - e_scatter_(metric_y, bind = "measure", symbol_size = 6, itemStyle = list(color = "#1b263b"), legend = FALSE) # Add scatter plot with points - } - - # Add axis labels and tooltips - plot <- plot %>% - e_axis_labels(x = metric_x_title, y = metric_y_title) %>% # Set axis labels using metric titles - e_x_axis(nameLocation = "middle", nameGap = 30) %>% # Center the x-axis title and move it below the axis - e_y_axis(nameLocation = "middle", nameGap = 50) %>% # Center the y-axis title and move it to the left - # Configure tooltips that display data points info on hover - e_tooltip( - trigger = "item", - formatter = htmlwidgets::JS( - sprintf("function(params) { - return('%s: ' + params.value[0].toFixed(2) + '
' + - '%s: ' + params.value[1].toFixed(2) + '
' + - 'Position: ' + params.name + ' km' - ); - }", metric_x_title, metric_y_title) - ) - ) %>% - #Add toolbox features (e.g., zooming, saving the plot) - e_toolbox_feature(feature = c("dataZoom", "saveAsImage")) %>% - # Show a loading animation while the plot is rendered - e_show_loading() - - - # add lm elements to plot - if (lm) { - plot <- plot %>% - e_line(lm, name = "Modèle linéaire", lineStyle = list(color = "red"), symbol = 'none') %>% # Add the linear regression line - e_legend(show = TRUE, itemStyle = list(color = "transparent")) %>% # Show legend (transparent) - # Add a floating text box with the statistical summary (R, R², p-value) - e_text_g( - left = "10%", # Position text horizontally - top = "9%", # Position text vertically - style = list( - text = linear_dependency_text, # Display correlation text - fontSize = 12, # Font size for the text - z = 1000, # Set z-index to bring the text to the foreground - backgroundColor = "#ffccd5", # Set background color of the text box - borderRadius = 5, # Add rounded corners to the text box - padding = 5 # Add padding around the text within the box - ) - ) - } - - - - return(plot) -} diff --git a/R_old/fct_sld_style.R b/R_old/fct_sld_style.R deleted file mode 100644 index 578c202..0000000 --- a/R_old/fct_sld_style.R +++ /dev/null @@ -1,1344 +0,0 @@ -#' Get Quantile Metrics for a Selected Region -#' -#' This function calculates quantile metrics (Q1, Q2, Q3, Q4, Q5) for a selected metric within a specified region. -#' -#' @param selected_region_id The ID of the selected region. -#' @param selected_metric The name of the selected metric. -#' @param con PqConnection to Postgresql database. -#' -#' @return A numeric vector containing quantile metrics (Q1, Q2, Q3, Q4, Q5) for the selected metric within the specified region. -#' -#' @examples -#' con <- db_con() -#' # get quantiles from active_channel_width metric -#' quantile_metrics <- sld_get_quantile_metric(selected_region_id = 11, -#' selected_metric = "active_channel_width", -#' con = con) -#' quantile_metrics -#' DBI::dbDisconnect(con) -#' -#' @importFrom DBI dbGetQuery sqlInterpolate dbQuoteIdentifier SQL -#' -#' @export -sld_get_quantile_metric <- function(selected_region_id, selected_metric, con) { - sql <- " - SELECT - ROUND(percentile_cont(0) WITHIN GROUP (ORDER BY ?selected_metric ASC)::numeric, 1) AS q1, - ROUND(percentile_cont(0.25) WITHIN GROUP (ORDER BY ?selected_metric ASC)::numeric, 1) AS q2, - ROUND(percentile_cont(0.50) WITHIN GROUP (ORDER BY ?selected_metric ASC)::numeric, 1) AS q3, - ROUND(percentile_cont(0.75) WITHIN GROUP (ORDER BY ?selected_metric ASC)::numeric, 1) AS q4, - ROUND(percentile_cont(1) WITHIN GROUP (ORDER BY ?selected_metric ASC)::numeric, 1) AS q5 - FROM public.network_metrics - WHERE gid_region = ?selected_region_id" - - query <- sqlInterpolate(con, sql, - selected_metric = DBI::dbQuoteIdentifier(con, selected_metric), - selected_region_id = DBI::SQL(selected_region_id)) - - data <- DBI::dbGetQuery(conn = con, statement = query) - vector <- c(data$q1, data$q2, data$q3, data$q3, data$q4, data$q5) - - return(vector) -} - - -#' Get Quantile Colors -#' -#' This function generates a color palette based on quantile breaks for data mapping. -#' -#' @param quantile_breaks A numeric vector containing quantile breaks. -#' -#' @return A character vector of colors generated based on quantile breaks. -#' -#' @importFrom grDevices colorRampPalette -#' -#' @examples -#' con <- db_con() -#' # get quantiles from active_channel_width metric -#' quantile_metrics <- sld_get_quantile_metric(selected_region_id = 11, -#' selected_metric = "active_channel_width", -#' con = con) -#' DBI::dbDisconnect(con) -#' # get color from quantile -#' quantile_colors <- sld_get_quantile_colors(quantile_breaks = quantile_metrics) -#' quantile_colors -#' -#' @export -sld_get_quantile_colors <- function(quantile_breaks) { - colors_palette <- colorRampPalette(c("#03045e", "#90e0ef"))(length(quantile_breaks)) - return(colors_palette) -} - - -#' Get Styled Layer Descriptor (SLD) for network metric layer -#' -#' This function generates a Styled Layer Descriptor (SLD) XML for styling network metric layer based on quantile breaks colors. -#' -#' @param breaks A numeric vector containing quantile breaks. -#' @param colors A character vector of colors generated based on quantile breaks. -#' @param metric The name of the selected metric. -#' -#' @return A character string containing the SLD XML for styling data visualization. -#' -#' @examples -#' con <- db_con() -#' # get quantiles from active_channel_width metric -#' quantile_metrics <- sld_get_quantile_metric(selected_region_id = 11, -#' selected_metric = "active_channel_width", -#' con = con) -#' DBI::dbDisconnect(con) -#' -#' # get color from quantile -#' quantile_colors <- sld_get_quantile_colors(quantile_breaks = quantile_metrics) -#' # create sld style -#' sld_style <- sld_get_style(breaks = quantile_metrics, -#' colors = quantile_colors, -#' metric = "active_channel_width") -#' sld_style -#' -#' @importFrom glue glue -#' -#' @export -sld_get_style <- function(breaks, colors, metric) { - sld_begin <- glue::glue(' - - - network_metrics - - network_metrics - ') - - sld_end <- ' - - - - ' - - sld_rules <- character(0) # Initialize an empty list to store rules - - - - for (i in 1:(length(breaks))) { - if (i < length(breaks)) { - sld_rule <- glue::glue(' - - {breaks[i]} - {breaks[i+1]} - - {breaks[i]} - {breaks[i+1]} - - - - - {metric} - {breaks[i]} - - - {metric} - {breaks[i+1]} - - - - - - {colors[i]} - 2 - bevel - square - {colors[i]} - 2 - - - - ') - } else { - sld_rule <- glue::glue(' - - >= {breaks[i]} - - >= {breaks[i]} - - - - {metric} - {breaks[i]} - - - - - {colors[i]} - 2 - bevel - square - {colors[i]} - 2 - - - - ') - } - sld_rules <- c(sld_rules, sld_rule) - } - - sld <- paste0(sld_begin, paste(sld_rules, collapse = "\n"), sld_end) - return(sld) -} - - -#' Create sld style for fluvial styles layers -#' -#' @importFrom glue glue -#' @importFrom grDevices colorRampPalette -#' -#' @return Style Layer Descriptor XML code for the styling of the network wms-layer based on the fluvial styles classifications -#' -#' @usage sld_get_fluvialstyles() -#' -sld_get_fluvialstyles <- function() { - - colors_classes_pro <- params_classes_colors() - - sld_begin <- glue::glue(' - - - network_metrics - - network_metrics - ') - - sld_end <- ' - - - - ' - - - # strahler ---------------------------------------------------------------- - - colors_strahler <- colors_classes_pro$class_strahler - strahler_sld_rules <- character(0) - - for (i in 1:6) { - strahler_sld_rule <- glue::glue(' - - {i} - - {i} - - - - strahler - {i} - - - - - {colors_strahler[i]} - 2 - bevel - square - {colors_strahler[i]} - 2 - - - - ') - strahler_sld_rules <- c(strahler_sld_rules, strahler_sld_rule) - } - - sld_strahler <- paste(strahler_sld_rules, collapse = "\n") - - # Topographie ------------------------------------------------------------- - - colors_topo <- colors_classes_pro$class_topographie - - sld_topographie <- glue::glue(' - - {names(colors_topo[1])} - - {names(colors_topo[1])} - - - - - talweg_elevation_min - {1000} - - - talweg_slope - {0.05} - - - - - - {colors_topo[1]} - 2 - bevel - square - {colors_topo[1]} - 2 - - - - - {names(colors_topo[4])} - - {names(colors_topo[4])} - - - - - talweg_elevation_min - {1000} - - - talweg_slope - {0.05} - - - - - - {colors_topo[4]} - 2 - bevel - square - {colors_topo[4]} - 2 - - - - - {names(colors_topo[2])} - - {names(colors_topo[2])} - - - - - - talweg_elevation_min - {300} - - - talweg_elevation_min - {1000} - - - - talweg_slope - {0.05} - - - - - - {colors_topo[2]} - 2 - bevel - square - {colors_topo[2]} - 2 - - - - - {names(colors_topo[5])} - - {names(colors_topo[5])} - - - - - - talweg_elevation_min - {300} - - - talweg_elevation_min - {1000} - - - - talweg_slope - {0.05} - - - - - - {colors_topo[5]} - 2 - bevel - square - {colors_topo[5]} - 2 - - - - - {names(colors_topo[3])} - - {names(colors_topo[3])} - - - - - - talweg_elevation_min - {-50} - - - talweg_elevation_min - {300} - - - - talweg_slope - {0.05} - - - - - - {colors_topo[3]} - 2 - bevel - square - {colors_topo[3]} - 2 - - - - - {names(colors_topo[6])} - - {names(colors_topo[6])} - - - - - - talweg_elevation_min - {-50} - - - talweg_elevation_min - {300} - - - - talweg_slope - {0.05} - - - - - - {colors_topo[6]} - 2 - bevel - square - {colors_topo[6]} - 2 - - - - ') - - - # Dominant Land use ------------------------------------------------------- - - colors_lu_dominante <- colors_classes_pro$class_lu_dominante - - - sld_lu_dominante <- glue::glue(' - - {names(colors_lu_dominante[1])} - - {names(colors_lu_dominante[1])} - - - - - - - forest_pc - grassland_pc - - - - forest_pc - crops_pc - - - - forest_pc - built_environment_pc - - - - - - {colors_lu_dominante[[1]]} - 2 - bevel - square - {colors_lu_dominante[[1]]} - 2 - - - - - {names(colors_lu_dominante[2])} - - {names(colors_lu_dominante[2])} - - - - - - - grassland_pc - forest_pc - - - - grassland_pc - crops_pc - - - - grassland_pc - built_environment_pc - - - - - - {colors_lu_dominante[[2]]} - 2 - bevel - square - {colors_lu_dominante[[2]]} - 2 - - - - - {names(colors_lu_dominante[3])} - - {names(colors_lu_dominante[3])} - - - - - - - crops_pc - grassland_pc - - - - crops_pc - forest_pc - - - - crops_pc - built_environment_pc - - - - - - {colors_lu_dominante[[3]]} - 2 - bevel - square - {colors_lu_dominante[[3]]} - 2 - - - - - {names(colors_lu_dominante[4])} - - {names(colors_lu_dominante[4])} - - - - - - - built_environment_pc - grassland_pc - - - - built_environment_pc - crops_pc - - - - built_environment_pc - forest_pc - - - - - - {colors_lu_dominante[[4]]} - 2 - bevel - square - {colors_lu_dominante[[4]]} - 2 - - - - ') - - - # Urban landuse ----------------------------------------------------------- - - colors_urban <- colors_classes_pro$class_urban - - sld_urban <- glue::glue(' - - {names(colors_urban[1])} - - {names(colors_urban[1])} - - - - built_environment_pc - 70 - - - - - {colors_urban[[1]]} - 2 - bevel - square - {colors_urban[[1]]} - 2 - - - - - {names(colors_urban[2])} - - {names(colors_urban[2])} - - - - - built_environment_pc - {70} - - - built_environment_pc - 40 - - - - - - {colors_urban[[2]]} - 2 - bevel - square - {colors_urban[[2]]} - 2 - - - - - {names(colors_urban[3])} - - {names(colors_urban[3])} - - - - - built_environment_pc - {40} - - - built_environment_pc - 10 - - - - - - {colors_urban[[3]]} - 2 - bevel - square - {colors_urban[[3]]} - 2 - - - - - {names(colors_urban[4])} - - {names(colors_urban[4])} - - - - - built_environment_pc - {10} - - - built_environment_pc - 0 - - - - - - {colors_urban[[4]]} - 2 - bevel - square - {colors_urban[[4]]} - 2 - - - - ') - - - # Agricultural landuse ---------------------------------------------------- - - colors_agriculture <- colors_classes_pro$class_agriculture - - sld_agriculture <- glue::glue(' - - {names(colors_agriculture[1])} - - {names(colors_agriculture[1])} - - - - crops_pc - 70 - - - - - {colors_agriculture[[1]]} - 2 - bevel - square - {colors_agriculture[[1]]} - 2 - - - - - {names(colors_agriculture[2])} - - {names(colors_agriculture[2])} - - - - - crops_pc - {70} - - - crops_pc - 40 - - - - - - {colors_agriculture[[2]]} - 2 - bevel - square - {colors_agriculture[[2]]} - 2 - - - - - {names(colors_agriculture[3])} - - {names(colors_agriculture[3])} - - - - - crops_pc - {40} - - - crops_pc - 10 - - - - - - {colors_agriculture[[3]]} - 2 - bevel - square - {colors_agriculture[[3]]} - 2 - - - - - {names(colors_agriculture[4])} - - {names(colors_agriculture[4])} - - - - - crops_pc - {10} - - - crops_pc - 0 - - - - - - {colors_agriculture[[4]]} - 2 - bevel - square - {colors_agriculture[[4]]} - 2 - - - - ') - - # Natural landuse --------------------------------------------------------- - - colors_nature <- colors_classes_pro$class_nature - - sld_nature <- glue::glue(' - - {names(colors_nature[1])} - - {names(colors_nature[1])} - - - - - natural_open_pc - forest_pc - grassland_pc - - 70 - - - - - {colors_nature[[1]]} - 2 - bevel - square - {colors_nature[[1]]} - 2 - - - - - {names(colors_nature[2])} - - {names(colors_nature[2])} - - - - - - natural_open_pc - forest_pc - grassland_pc - - {70} - - - - natural_open_pc - forest_pc - grassland_pc - - 40 - - - - - - {colors_nature[[2]]} - 2 - bevel - square - {colors_nature[[2]]} - 2 - - - - - {names(colors_nature[3])} - - {names(colors_nature[3])} - - - - - - natural_open_pc - forest_pc - grassland_pc - - {40} - - - - natural_open_pc - forest_pc - grassland_pc - - 10 - - - - - - {colors_nature[[3]]} - 2 - bevel - square - {colors_nature[[3]]} - 2 - - - - - {names(colors_nature[4])} - - {names(colors_nature[4])} - - - - - - natural_open_pc - forest_pc - grassland_pc - - {10} - - - - natural_open_pc - forest_pc - grassland_pc - - 0 - - - - - - {colors_nature[[4]]} - 2 - bevel - square - {colors_nature[[4]]} - 2 - - - - ') - - # Confinement ------------------------------------------------------------- - - colors_confinement <- colors_classes_pro$class_confinement - - sld_confinement <- glue::glue(' - - {names(colors_confinement[1])} - - {names(colors_confinement[1])} - - - - idx_confinement - 0.7 - - - - - {colors_confinement[[1]]} - 2 - bevel - square - {colors_confinement[[1]]} - 2 - - - - - {names(colors_confinement[2])} - - {names(colors_confinement[2])} - - - - - idx_confinement - {0.7} - - - idx_confinement - 0.4 - - - - - - {colors_confinement[[2]]} - 2 - bevel - square - {colors_confinement[[2]]} - 2 - - - - - {names(colors_confinement[3])} - - {names(colors_confinement[3])} - - - - - idx_confinement - {0.4} - - - idx_confinement - 0.1 - - - - - - {colors_confinement[[3]]} - 2 - bevel - square - {colors_confinement[[3]]} - 2 - - - - - {names(colors_confinement[4])} - - {names(colors_confinement[4])} - - - - - idx_confinement - {0.1} - - - idx_confinement - 0 - - - - - - {colors_confinement[[4]]} - 2 - bevel - square - {colors_confinement[[4]]} - 2 - - - - ') - - - # Habitat ----------------------------------------------------------------- - - colors_habitat <- colors_classes_pro$class_habitat - - sld_habitat <- glue::glue(' - - {names(colors_habitat[1])} - - {names(colors_habitat[1])} - - - - - riparian_corridor_pc - semi_natural_pc - - 70 - - - - - {colors_habitat[[1]]} - 2 - bevel - square - {colors_habitat[[1]]} - 2 - - - - - {names(colors_habitat[2])} - - {names(colors_habitat[2])} - - - - - - riparian_corridor_pc - semi_natural_pc - - {70} - - - - riparian_corridor_pc - semi_natural_pc - - 40 - - - - - - {colors_habitat[[2]]} - 2 - bevel - square - {colors_habitat[[2]]} - 2 - - - - - {names(colors_habitat[3])} - - {names(colors_habitat[3])} - - - - - - riparian_corridor_pc - semi_natural_pc - - {40} - - - - riparian_corridor_pc - semi_natural_pc - - 10 - - - - - - {colors_habitat[[3]]} - 2 - bevel - square - {colors_habitat[[3]]} - 2 - - - - - {names(colors_habitat[4])} - - {names(colors_habitat[4])} - - - - - - riparian_corridor_pc - semi_natural_pc - - {10} - - - - riparian_corridor_pc - semi_natural_pc - - 0 - - - - - - {colors_habitat[[4]]} - 2 - bevel - square - {colors_habitat[[4]]} - 2 - - - - ') - - - # Gravel bars ------------------------------------------------------------- - - - colors_gravel <- colors_classes_pro$class_gravel - - sld_gravel <- glue::glue(' - - {names(colors_gravel[1])} - - {names(colors_gravel[1])} - - - - - gravel_bars - - water_channel - 0.00001 - - - 0.5 - - - - - {colors_gravel[[1]]} - 2 - bevel - square - {colors_gravel[[1]]} - 2 - - - - - {names(colors_gravel[2])} - - {names(colors_gravel[2])} - - - - - - gravel_bars - - water_channel - 0.00001 - - - 0.5 - - - - gravel_bars - - water_channel - 0.00001 - - - 0 - - - - - - {colors_gravel[[2]]} - 2 - bevel - square - {colors_gravel[[2]]} - 2 - - - - - {names(colors_gravel[3])} - - {names(colors_gravel[3])} - - - - - gravel_bars - - water_channel - 0.00001 - - - 0 - - - - - {colors_gravel[[3]]} - 2 - bevel - square - {colors_gravel[[3]]} - 2 - - - - ') - - - # join all together ------------------------------------------------------- - - sld_final <- tibble( - class_name = c("class_strahler", "class_topographie", "class_lu_dominante", "class_urban", "class_agriculture", - "class_nature", "class_confinement", "class_habitat", "class_gravel"), - class_sld = c(paste0(sld_begin, sld_strahler, sld_end), - # "", "", "", "" - paste0(sld_begin, sld_topographie, sld_end), - paste0(sld_begin, sld_lu_dominante, sld_end), - paste0(sld_begin, sld_urban, sld_end), - paste0(sld_begin, sld_agriculture, sld_end), - paste0(sld_begin, sld_nature, sld_end), - paste0(sld_begin, sld_confinement, sld_end), - paste0(sld_begin, sld_habitat, sld_end), - paste0(sld_begin, sld_gravel, sld_end) - ) - ) - - return(sld_final) -} diff --git a/R_old/fct_table_characteristics.R b/R_old/fct_table_characteristics.R deleted file mode 100644 index 7bec177..0000000 --- a/R_old/fct_table_characteristics.R +++ /dev/null @@ -1,331 +0,0 @@ -# example for statistics-derival from database -# SELECT -# AVG(talweg_elevation_min) AS average, -# MIN(talweg_elevation_min) AS low_outlier, -# percentile_cont(0.025) WITHIN GROUP (ORDER BY talweg_elevation_min) AS low_whisker, -# percentile_cont(0.25) WITHIN GROUP (ORDER BY talweg_elevation_min) AS q1, -# percentile_cont(0.5) WITHIN GROUP (ORDER BY talweg_elevation_min) AS median, -# percentile_cont(0.75) WITHIN GROUP (ORDER BY talweg_elevation_min) AS q2, -# percentile_cont(0.975) WITHIN GROUP (ORDER BY talweg_elevation_min) AS high_whisker, -# MAX(talweg_elevation_min) AS high_outlier -# FROM network_metrics - - - -#' convert sf to pivoted dataframe with variables as rows -#' -#' @import dplyr -#' @importFrom sf st_drop_geometry -#' -#' @param df_sf sf object with one or several dgos -#' -#' @return dataframe with metrics as rows -#' @export -#' -fct_table_pivot_sf <- function(df_sf) { - df <- df_sf %>% - sf::st_drop_geometry() %>% - na.omit() %>% - tidyr::pivot_longer(-c(fid, axis, measure, toponyme, strahler, gid_region), names_to = "metric_name", values_to = "value") %>% - dplyr::mutate(value = round(value, 2)) %>% - dplyr::group_by(metric_name) %>% - dplyr::summarize( - mean = round(mean(value), 2), - distr = list(value) - ) - - return(df) -} - -#' Merge regional, axis, and dgo dataframes together for reactable table -#' -#' @import dplyr -#' @importFrom sf st_drop_geometry -#' @importFrom tidyr pivot_longer -#' -#' @param region_pivot pivoted df from selected regional network -#' @param axis_pivot pivoted df from selected axis network -#' @param dgo_pivot pivoted df from selected dgo -#' -#' @return dataframe with metrics as rows -#' @export -#' -#' @examples -#' fct_table_create_table_df(network_dgo, network_dgo, network_dgo[1,]) -fct_table_create_table_df <- function(region_pivot, axis_pivot, dgo_pivot){ - - # region selected, but axis and dgo not - if (is.null(dgo_pivot) && is.null(axis_pivot)) { - - # merge datasets - merged <- - dplyr::left_join(params_metrics() %>% select(metric_name, metric_title), region_pivot, - by = join_by(metric_name)) %>% - dplyr::mutate(mean_axis = "", distr_axis = "", segment = "") %>% - dplyr::select(!metric_name) %>% - dplyr::relocate(metric_title, mean_region, distr_region, mean_axis, distr_axis, segment) %>% - dplyr::group_by(metric_title) - } - - # region and axis selected, but dgo not - else if (is.null(dgo_pivot) && !is.null(axis_pivot)) { - - # merge datasets - merged <- - dplyr::left_join(params_metrics() %>% select(metric_name, metric_title), region_pivot, - by = join_by(metric_name)) %>% - dplyr::left_join(axis_pivot, - by = join_by(metric_name)) %>% - dplyr::mutate(segment = "") %>% - dplyr::select(!metric_name) %>% - dplyr::relocate(metric_title, mean_region, distr_region, mean_axis, distr_axis, segment) %>% - dplyr::group_by(metric_title) - } - # region, axis, and dgo selected - else { - - # merge datasets - merged <- - dplyr::left_join(params_metrics() %>% select(metric_name, metric_title), region_pivot, - by = join_by(metric_name)) %>% - dplyr::left_join(axis_pivot, - by = join_by(metric_name), - suffix = c("_region", "_axis")) %>% - dplyr::left_join(dgo_pivot, - by = join_by(metric_name)) %>% - dplyr::select(!metric_name) %>% - dplyr::relocate(metric_title, mean_region, distr_region, mean_axis, distr_axis, segment) %>% - dplyr::group_by(metric_title) - } - - return(merged) -} - - -#' create a table to compare metric-characteristics of region, axis, and segment -#' -#' @import dplyr -#' @importFrom reactable reactable colDef -#' @importFrom sparkline sparkline -#' @importFrom tibble tibble -#' -#' @param df dataframe of merged regional, axis and dgo data -#' @param unit -#' -#' @return reactable table object -#' fct_table_create_table_df(region_sf = network_dgo, -#' axis_sf = network_dgo, -#' dgo_sf = NULL) -#' -fct_table_create_reactable <- function(df, unit, details = FALSE){ - - # filter for ha or % units - if (unit == "ha") { - data <- df %>% - dplyr::filter(metric_title %in% grep('(%)', metric_title, value = TRUE, invert = TRUE) | metric_title %in% c("Pente talweg (%)", "Pente fond de vallée (%)")) - } else if (unit == "%") { - data <- df %>% - dplyr::filter(!grepl('(ha)', metric_title)) - } - - - # convert data table and extract only values for a selected variable to create violinplots with plotly - convert_data <- function(data, i){ - data_converted <- tibble::tibble( - scale = "Axe", - values = data$distr_axis[[i]]) %>% - dplyr::add_row( - tibble::tibble( - scale = "Région", - values = data$distr_region[[i]] - ) - ) %>% - dplyr::rename(!!data$metric_title[i] := values) - - return(data_converted) - } - - if (details == TRUE) { - # create reactable table with violinplots in details - table <- reactable( - data = data, - columns = list( - metric_title = colDef(name = "Métrique", width = 180), - mean_region = colDef(name = "Région", width = 100), - distr_region = colDef(name = "", width = 80, - cell = function(value, index) { - sparkline(data$distr_region[[index]], type = "box") - }), - mean_axis = colDef(name = "Axe", width = 100), - distr_axis = colDef(name = "", width = 80, - cell = function(value, index) { - sparkline(data$distr_axis[[index]], type = "box") - }), - segment = colDef(name = "Tronçon", width = 80) - ), - # add violinplots of distribution from axis and region into details - details = function(index) { - htmltools::div( - style = "padding: 10px; margin-left: 40px; white-space: pre-wrap;", # Add text indentation - create_plotly_violinplot(convert_data(data, index), data$metric_title[index], data$metric_title[index]) - )}, - height = 420, - defaultPageSize = 9, - highlight = TRUE, # highlight rows on hover - compact = TRUE - ) - } else { - - # create reactable table without violinplots - table <- reactable( - data = data, - columns = list( - metric_title = colDef(name = "Métrique", width = 150), - mean_region = colDef(name = "Région", width = 80), - distr_region = colDef(name = "", width = 70, - cell = function(value, index) { - sparkline(data$distr_region[[index]], type = "box") - }), - mean_axis = colDef(name = "Axe", width = 80), - distr_axis = colDef(name = "", width = 70, - cell = function(value, index) { - sparkline(data$distr_axis[[index]], type = "box") - }), - segment = colDef(name = "Tronçon", width = 80) - ), - height = 400, - pagination = FALSE, - outlined = TRUE, - highlight = TRUE, # highlight rows on hover - compact = TRUE - ) - - } - - return(table) -} - - - - - - - - - - - - - - - -#' create a table to compare characteristics of region and segment -#' -#' @description A fct function -#' -#' @import dplyr -#' @importFrom reactable reactable colDef -#' @importFrom sparkline sparkline -#' @importFrom sf st_drop_geometry -#' @importFrom tidyr pivot_longer -#' #' -#' #' @return The return value, if any, from executing the function. -#' #' -#' #' @noRd -#' create_reactable_characteristics <- function(region_network, dgo){ -#' -#' # get data -#' region_df <- region_network %>% sf::st_drop_geometry() -#' # axis_df <- axis_network %>% sf::st_drop_geometry() -#' dgo_df <- dgo %>% sf::st_drop_geometry() -#' -#' # convert data -#' network_pivot <- region_df %>% -#' tidyr::pivot_longer(-c(fid, axis, measure, toponyme, strahler, gid_region), -#' names_to = "variable", values_to = "value") %>% -#' dplyr::mutate(value = round(value, 2)) %>% -#' dplyr::group_by(variable) %>% -#' dplyr::summarize( -#' region_mean = mean(value), -#' region_distr = list(value) -#' ) -#' -#' dgo_pivot <- dgo_df %>% -#' dplyr::select(-c(fid, axis, measure, toponyme, strahler, gid_region)) %>% -#' tidyr::pivot_longer(-c(), names_to = "variable", values_to = "segment") %>% -#' dplyr::mutate(segment = round(segment, 2)) -#' -#' # merge datasets -#' merged <- left_join(network_pivot, dgo_pivot, by = join_by(variable)) %>% -#' dplyr::left_join(params_metrics() %>% select(metric_name, metric_title, metric_type_title), -#' by = dplyr::join_by(variable == metric_name)) %>% -#' dplyr::select(!variable) %>% -#' dplyr::relocate(metric_type_title, metric_title, region_mean, region_distr, segment) %>% -#' # na.omit() %>% -#' dplyr::arrange(factor(metric_type_title, levels = unique(params_metrics()$metric_type_title))) %>% -#' dplyr::select(!metric_type_title) %>% -#' dplyr::group_by(metric_title) -#' -#' # create table -#' table <- reactable( -#' data = merged, -#' columns = list( -#' # metric_type_title = colDef(name = "Groupe"), -#' metric_title = colDef(name = "Métrique"), -#' region_mean = colDef( -#' name = "Région (moyenne)", -#' style = function(value, index) { -#' reactable_style_function(value, merged$segment[index]) -#' } -#' ), -#' region_distr = colDef( -#' name = "Distribution", -#' cell = function(value, index) { -#' sparkline(merged$region_distr[[index]], type = "box") -#' }), -#' segment = colDef( -#' name = "Tronçon", -#' style = function(value, index) { -#' reactable_style_function(value, merged$region_mean[index]) -#' }) -#' ), -#' # groupBy = "metric_type_title", -#' # paginateSubRows = TRUE, -#' defaultExpanded = TRUE, # categories expanded rather than closed -#' defaultPageSize = 10, # set rows per page -#' highlight = TRUE, # highlight rows on hover -#' compact = TRUE -#' ) -#' -#' return(table) -#' } - - - -#' #' Helper function to style reactable table -#' #' -#' #' @param value actual value which should be coloured -#' #' @param other_value value to which the actual value should be compared -#' #' -#' #' @return styling for reactable row -#' #' @export -#' #' -#' #' @examples -#' #' # inside reactable function: -#' #' colDef( -#' #' name = "Tronçon", -#' #' style = function(value, index) { -#' #' reactable_style_function(value, merged$region_mean[index]) -#' #' }) -#' reactable_style_function <- function(value, other_value) { -#' if (is.na(value) || is.na(other_value)) { -#' color <- "#212529" # Default color for NA values -#' } else if (value > other_value) { -#' color <- "#283618" -#' } else if (value < other_value) { -#' color <- "#780000" -#' } else { -#' color <- "#212529" -#' } -#' list(color = color, fontWeight = "bold") -#' } diff --git a/R_old/fct_table_fluvialstyles.R b/R_old/fct_table_fluvialstyles.R deleted file mode 100644 index 1645544..0000000 --- a/R_old/fct_table_fluvialstyles.R +++ /dev/null @@ -1,29 +0,0 @@ -#' table_fluvialstyles -#' -#' @description A fct function -#' -#' @importFrom reactable reactable colDef -#' @importFrom htmltools div -#' -#' @return The return value, if any, from executing the function. -#' -#' @noRd -create_table_fluvialstyles <- function(params_styles) { - - table <- reactable(params_styles, - columns = list( - class_title = colDef(name = "Style", sortable = FALSE), - description = colDef(show = FALSE), # Hide column - class_name = colDef(show = FALSE), # Hide column - class_sld = colDef(show = FALSE), # Hide column - sld_style = colDef(show = FALSE) # Hide column - ), - details = function(index) { - htmltools::div( - style = "padding: 10px; margin-left: 84px; white-space: pre-wrap;", # Add text indentation - # htmltools::strong("Details: "), - params_styles$description[index] # Display the detail column for the specific row - ) - }, selection = "single", defaultSelected = 1, onClick = "select", - highlight = TRUE) -} diff --git a/R_old/fct_track.R b/R_old/fct_track.R deleted file mode 100644 index 4a9cd12..0000000 --- a/R_old/fct_track.R +++ /dev/null @@ -1,38 +0,0 @@ -#' Track input user inputs. -#' -#' @param input reactivesValues Shiny input. -#' -#' @importFrom jsonlite toJSON -#' -#' @return message with the inputs name and value as json format. -#' @export -track_inputs <- function(input = input){ - inputs_tracked <- c("exploremap_shape_click", "strahler", "metricfilter", "metric_type", - "metric", "unit_area", "roe_profile", "profile_metric_type", - "profile_metric", "profile_unit_area", "roe_profile", - "remove_profile_axe") - - values <- list() - for (name in names(input)) { - if (grepl(paste(inputs_tracked, collapse = "|"), name)) { - values[[name]] <- input[[name]] - } - } - return(message(toJSON(list(values)))) -} - -#' Track input user session id and datetime. -#' -#' @param session reactivesValues Shiny input. -#' -#' @importFrom jsonlite toJSON -#' -#' @return message with the session info name and value as json format. -#' @export -track_session <- function(session = session){ - session_tracks <- list( - session_id = session$token, - session_time = format(Sys.time(), "%Y-%m-%d %H:%M:%OS3%z") - ) - message(toJSON(list(session_tracks))) -} diff --git a/R_old/fct_utils.R b/R_old/fct_utils.R deleted file mode 100644 index a804a88..0000000 --- a/R_old/fct_utils.R +++ /dev/null @@ -1,159 +0,0 @@ -#' Normalize a string by removing spaces, accents, and special characters. -#' -#' This function takes an input string and normalizes it by removing spaces, accents, diacritics, -#' and special characters. It then converts the string to lowercase. -#' -#' @param input_string The input string to be normalized. -#' -#' @return The normalized string with spaces, accents, and special characters removed, and in lowercase. -#' -#' @examples -#' original_string <- "Thïs is à sâmplè strîng with spèciál chàracters!" -#' normalized_string <- utils_normalize_string(original_string) -#' cat(normalized_string) # "thisisasamplestringwithspecialcharacters" -#' -#' @export -utils_normalize_string <- function(input_string) { - # Remove accents and diacritics - input_string <- chartr("ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûüÝýÑñÇç", - "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuYyNnCc", - input_string) - - # Remove spaces and special characters - input_string <- gsub("[^a-zA-Z0-9]", "", input_string) - - # Convert to lowercase - normalized_string <- tolower(input_string) - - return(normalized_string) -} - -#' Get a named vector of metric types from the params metric list. -#' -#' This function extracts metric types from a list of objects and returns a named -#' vector with metric type titles as names and metric type values as values. -#' -#' @param input_list A list of objects where each object has a 'metric_type_title' field. -#' -#' @importFrom stats setNames -#' -#' @return A named character vector with metric type titles as names and metric type values as values. -#' -#' @examples -#' metric_types <- utils_get_metric_type(params_metrics_choice()) -#' -#' @export -utils_get_metric_type <- function(input_list) { - metric_type <- setNames(names(sapply(input_list, function(x) x$metric_type_title)), sapply(input_list, function(x) x$metric_type_title)) - return(metric_type) -} - -#' Get a named vector of all the metric from the metric type from the params metric list. -#' -#' This function extracts metric names and value with metric type stored in params metric list. -#' -#' @param metric_type A character with metric type. -#' -#' @return A named character vector with all the metric names and values. -#' -#' @examples -#' metrics <- utils_get_metric_name_value("largeur") -#' -#' @export -utils_get_metric_name_value <- function(metric_type){ - metric_name <- sapply(params_metrics_choice()[[metric_type]]$metric_type_value, function(x) x$metric_title) - return(metric_name) -} - -#' Create buttons with popover for metric labels. -#' -#' This function generates a list of buttons with popovers that display additional -#' information for each metric label. -#' -#' @param metric_type A character string specifying the metric type. -#' -#' @importFrom bslib popover -#' @importFrom bsicons bs_icon -#' -#' @return A list of buttons with popovers. -#' -#' @details This function uses the `params_metrics_choice` data structure to -#' extract metric labels and corresponding popover information for the specified -#' metric type. -#' -#' @examples -#' metric_buttons <- utils_button_label_with_popover("largeur") -#' -#' @export -utils_button_label_with_popover <- function(metric_type) { - metrics <- - names(params_metrics_choice()[[metric_type]]$metric_type_value) - buttons <- list() - for (var in metrics) { - metric_title <- - params_metrics_choice()[[metric_type]]$metric_type_value[[var]]$metric_title - # popover to display - metric_popover <- - params_metrics_choice()[[metric_type]]$metric_type_value[[var]]$metric_info - bttn <- - list( - div( - # metric title to display next to the radioButton - metric_title, - style = "display: inline; align-items: center;", - # info icon with popover label - span( - style = "display: inline; align-items: center", - popover( - trigger = bs_icon("info-circle"), - metric_popover, - placement = "right", - id = "popover_metric" - ) - ) - ) - ) - - buttons <- append(buttons, bttn) - } - return(buttons) -} - -#' get IGN remonterletemps url. -#' -#' This function take longitude and latitude to build and url to go IGN remonterletemps website on the same place. -#' -#' @param lng longitude. -#' @param lat latitude. -#' @param zoom zoom level. -#' -#' @importFrom glue glue -#' -#' @return a string with url link. -#' @export -#' -#' @examples -#' utils_url_remonterletemps(lng=6.869433, lat=45.923690, zoom = 12) -utils_url_remonterletemps <- function(lng=6.869433, - lat=45.923690, - zoom = 12){ - url <- glue::glue("https://remonterletemps.ign.fr/comparer/basic?x={lng}&y={lat}&z={zoom}&layer1=GEOGRAPHICALGRIDSYSTEMS.PLANIGNV2&layer2=ORTHOIMAGERY.ORTHOPHOTOS&mode=vSlider") - return(url) -} - -#' Get a named vector of all the metric from the metric type from the params metric list. -#' -#' This function extracts metric names and value with metric type stored in params metric list. -#' -#' @param metric_type A character with metric type. -#' -#' @return A named character vector with all the metric names and values. -#' -#' @examples -#' metrics <- utils_get_metric_name_value_analysis("largeur") -#' -#' @export -utils_get_metric_name_value_analysis <- function(metric_type){ - metric_name <- sapply(params_metrics_choice_analysis()[[metric_type]]$metric_type_value, function(x) x$metric_title) - return(metric_name) -} diff --git a/R_old/globals.R b/R_old/globals.R deleted file mode 100644 index c3c59cb..0000000 --- a/R_old/globals.R +++ /dev/null @@ -1,28 +0,0 @@ -globalVariables(unique(c( - # data_get_axis: - "region_click", - # data_get_network_axis: - "measure", - # data_get_regions_in_bassin: - "bassin_click", - # data_get_roe_in_region: - "region_click", - # lg_profile_main: - "selected_axis_df", - # lg_profile_second: - "selected_axis_df", - # map_add_regions_in_bassin: - "region_hydro", - # mod_explore_server : : - "fid", "measure", "axis", "cdbh", "click", "gid", - # data_get_elevation_profiles: - "distance", "profile" -))) - -metrics_params <<- params_metrics() - -# save classes once to be able to access it directly -classes_proposed <<- params_classes() - -# save classes colors once to be able to access it directly -colors_classes_proposed <<- params_classes_colors() diff --git a/R_old/golem_utils_server.R b/R_old/golem_utils_server.R deleted file mode 100644 index 0099c19..0000000 --- a/R_old/golem_utils_server.R +++ /dev/null @@ -1,63 +0,0 @@ -#' Inverted versions of in, is.null and is.na -#' -#' @noRd -#' -#' @examples -#' 1 %not_in% 1:10 -#' not_null(NULL) -`%not_in%` <- Negate(`%in%`) - -not_null <- Negate(is.null) - -not_na <- Negate(is.na) - -#' Removes the null from a vector -#' -#' @noRd -#' -#' @example -#' drop_nulls(list(1, NULL, 2)) -drop_nulls <- function(x) { - x[!sapply(x, is.null)] -} - -#' If x is `NULL`, return y, otherwise return x -#' -#' @param x,y Two elements to test, one potentially `NULL` -#' -#' @noRd -#' -#' @examples -#' NULL %||% 1 -"%||%" <- function(x, y) { - if (is.null(x)) { - y - } else { - x - } -} - -#' If x is `NA`, return y, otherwise return x -#' -#' @param x,y Two elements to test, one potentially `NA` -#' -#' @noRd -#' -#' @examples -#' NA %|NA|% 1 -"%|NA|%" <- function(x, y) { - if (is.na(x)) { - y - } else { - x - } -} - -#' Typing reactiveValues is too long -#' -#' @inheritParams reactiveValues -#' @inheritParams reactiveValuesToList -#' -#' @noRd -rv <- function(...) shiny::reactiveValues(...) -rvtl <- function(...) shiny::reactiveValuesToList(...) diff --git a/R_old/golem_utils_ui.R b/R_old/golem_utils_ui.R deleted file mode 100644 index 5a9ee8d..0000000 --- a/R_old/golem_utils_ui.R +++ /dev/null @@ -1,405 +0,0 @@ -#' Turn an R list into an HTML list -#' -#' @param list An R list -#' @param class a class for the list -#' -#' @return an HTML list -#' @noRd -#' -#' @examples -#' list_to_li(c("a", "b")) -#' @importFrom shiny tags tagAppendAttributes tagList -list_to_li <- function(list, class = NULL) { - if (is.null(class)) { - tagList( - lapply( - list, - tags$li - ) - ) - } else { - res <- lapply( - list, - tags$li - ) - res <- lapply( - res, - function(x) { - tagAppendAttributes( - x, - class = class - ) - } - ) - tagList(res) - } -} -#' Turn an R list into corresponding HTML paragraph tags -#' -#' @param list an R list -#' @param class a class for the paragraph tags -#' -#' @return An HTML tag -#' @noRd -#' -#' @examples -#' list_to_p(c("This is the first paragraph", "this is the second paragraph")) -#' @importFrom shiny tags tagAppendAttributes tagList -#' -list_to_p <- function(list, class = NULL) { - if (is.null(class)) { - tagList( - lapply( - list, - tags$p - ) - ) - } else { - res <- lapply( - list, - tags$p - ) - res <- lapply( - res, - function(x) { - tagAppendAttributes( - x, - class = class - ) - } - ) - tagList(res) - } -} - -#' @importFrom shiny tags tagAppendAttributes tagList -named_to_li <- function(list, class = NULL) { - if (is.null(class)) { - res <- mapply( - function(x, y) { - tags$li( - HTML( - sprintf("%s: %s", y, x) - ) - ) - }, - list, - names(list), - SIMPLIFY = FALSE - ) - tagList(res) - } else { - res <- mapply( - function(x, y) { - tags$li( - HTML( - sprintf("%s: %s", y, x) - ) - ) - }, - list, - names(list), - SIMPLIFY = FALSE - ) - res <- lapply( - res, - function(x) { - tagAppendAttributes( - x, - class = class - ) - } - ) - tagList(res) - } -} - -#' Remove a tag attribute -#' -#' @param tag the tag -#' @param ... the attributes to remove -#' -#' @return a new tag -#' @noRd -#' -#' @examples -#' a <- shiny::tags$p(src = "plop", "pouet") -#' tagRemoveAttributes(a, "src") -tagRemoveAttributes <- function(tag, ...) { - attrs <- as.character(list(...)) - for (i in seq_along(attrs)) { - tag$attribs[[attrs[i]]] <- NULL - } - tag -} - -#' Hide or display a tag -#' -#' @param tag the tag -#' -#' @return a tag -#' @noRd -#' -#' @examples -#' ## Hide -#' a <- shiny::tags$p(src = "plop", "pouet") -#' undisplay(a) -#' b <- shiny::actionButton("go_filter", "go") -#' undisplay(b) -#' @importFrom shiny tagList -undisplay <- function(tag) { - # if not already hidden - if ( - !is.null(tag$attribs$style) && - !grepl("display:\\s+none", tag$attribs$style) - ) { - tag$attribs$style <- paste( - "display: none;", - tag$attribs$style - ) - } else { - tag$attribs$style <- "display: none;" - } - tag -} - -#' @importFrom shiny tagList -display <- function(tag) { - if ( - !is.null(tag$attribs$style) && - grepl("display:\\s+none", tag$attribs$style) - ) { - tag$attribs$style <- gsub( - "(\\s)*display:(\\s)*none(\\s)*(;)*(\\s)*", - "", - tag$attribs$style - ) - } - tag -} - -#' Hide an elements by calling jquery hide on it -#' -#' @param id the id of the element to hide -#' -#' @noRd -#' -#' @importFrom shiny tags -jq_hide <- function(id) { - tags$script(sprintf("$('#%s').hide()", id)) -} - -#' Add a red star at the end of the text -#' -#' Adds a red star at the end of the text -#' (for example for indicating mandatory fields). -#' -#' @param text the HTLM text to put before the red star -#' -#' @return an html element -#' @noRd -#' -#' @examples -#' with_red_star("Enter your name here") -#' @importFrom shiny tags HTML -with_red_star <- function(text) { - shiny::tags$span( - HTML( - paste0( - text, - shiny::tags$span( - style = "color:red", - "*" - ) - ) - ) - ) -} - - - -#' Repeat tags$br -#' -#' @param times the number of br to return -#' -#' @return the number of br specified in times -#' @noRd -#' -#' @examples -#' rep_br(5) -#' @importFrom shiny HTML -rep_br <- function(times = 1) { - HTML(rep("
", times = times)) -} - -#' Create an url -#' -#' @param url the URL -#' @param text the text to display -#' -#' @return an a tag -#' @noRd -#' -#' @examples -#' enurl("https://www.thinkr.fr", "ThinkR") -#' @importFrom shiny tags -enurl <- function(url, text) { - tags$a(href = url, text) -} - -#' Columns wrappers -#' -#' These are convenient wrappers around -#' `column(12, ...)`, `column(6, ...)`, `column(4, ...)`... -#' -#' @noRd -#' -#' @importFrom shiny column -col_12 <- function(...) { - column(12, ...) -} - -#' @importFrom shiny column -col_10 <- function(...) { - column(10, ...) -} - -#' @importFrom shiny column -col_8 <- function(...) { - column(8, ...) -} - -#' @importFrom shiny column -col_6 <- function(...) { - column(6, ...) -} - - -#' @importFrom shiny column -col_4 <- function(...) { - column(4, ...) -} - - -#' @importFrom shiny column -col_3 <- function(...) { - column(3, ...) -} - - -#' @importFrom shiny column -col_2 <- function(...) { - column(2, ...) -} - - -#' @importFrom shiny column -col_1 <- function(...) { - column(1, ...) -} - - - -#' Make the current tag behave like an action button -#' -#' Only works with compatible tags like button or links -#' -#' @param tag Any compatible tag. -#' @param inputId Unique id. This will host the input value to be used -#' on the server side. -#' -#' @return The modified tag with an extra id and the action button class. -#' @noRd -#' -#' @examples -#' if (interactive()) { -#' library(shiny) -#' -#' link <- a(href = "#", "My super link", style = "color: lightblue;") -#' -#' ui <- fluidPage( -#' make_action_button(link, inputId = "mylink") -#' ) -#' -#' server <- function(input, output, session) { -#' observeEvent(input$mylink, { -#' showNotification("Pouic!") -#' }) -#' } -#' -#' shinyApp(ui, server) -#' } -make_action_button <- function(tag, inputId = NULL) { - # some obvious checks - if (!inherits(tag, "shiny.tag")) stop("Must provide a shiny tag.") - if (!is.null(tag$attribs$class)) { - if (grep("action-button", tag$attribs$class)) { - stop("tag is already an action button") - } - } - if (is.null(inputId) && is.null(tag$attribs$id)) { - stop("tag does not have any id. Please use inputId to be able to - access it on the server side.") - } - - # handle id - if (!is.null(inputId)) { - if (!is.null(tag$attribs$id)) { - warning( - paste( - "tag already has an id. Please use input$", - tag$attribs$id, - "to access it from the server side. inputId will be ignored." - ) - ) - } else { - tag$attribs$id <- inputId - } - } - - # handle class - if (is.null(tag$attribs$class)) { - tag$attribs$class <- "action-button" - } else { - tag$attribs$class <- paste(tag$attribs$class, "action-button") - } - # return tag - tag -} - - -# UNCOMMENT AND USE -# -# attachment::att_amend_desc() -# -# To use this part of the UI -# -#' #' Include Content From a File -#' #' -#' #' Load rendered RMarkdown from a file and turn into HTML. -#' #' -#' #' @rdname includeRMarkdown -#' #' @export -#' #' -#' #' @importFrom rmarkdown render -#' #' @importFrom markdown markdownToHTML -#' #' @importFrom shiny HTML -#' includeRMarkdown <- function(path){ -#' -#' md <- tempfile(fileext = '.md') -#' -#' on.exit(unlink(md),add = TRUE) -#' -#' rmarkdown::render( -#' path, -#' output_format = 'md_document', -#' output_dir = tempdir(), -#' output_file = md,quiet = TRUE -#' ) -#' -#' html <- markdown::markdownToHTML(md, fragment.only = TRUE) -#' -#' Encoding(html) <- "UTF-8" -#' -#' return(HTML(html)) -#' } diff --git a/R_old/mod_classes_distribution.R b/R_old/mod_classes_distribution.R deleted file mode 100644 index 60ee260..0000000 --- a/R_old/mod_classes_distribution.R +++ /dev/null @@ -1,149 +0,0 @@ -#' classes_distribution UI Function -#' -#' @description A shiny Module. -#' -#' @import shiny -#' @importFrom shinyjs useShinyjs -#' @importFrom plotly plotlyOutput -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_classes_distribution_ui <- function(id){ - ns <- NS(id) - tagList( - useShinyjs(), - fluidRow( - style = "margin-top: 10px;", - textOutput(ns("placeholder_ui")), - column(width = 8, - plotlyOutput(ns("barplots_classes_metricUI")) - ) - ) - ) -} - -#' classes_distribution Server Functions -#' -#' @import shiny -#' @importFrom plotly renderPlotly -#' @noRd -mod_classes_distribution_server <- function(id, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - r_val_local <- reactiveValues( - barplots_classes_metric = NULL, - placeholder_text = "Sélectionnez un cours d'eau sur la carte et appliquez une classification pour afficher le graphique." - ) - - # text placeholder - output$placeholder_ui <- renderText({ - r_val_local$placeholder_text - }) - - # barplots showing distribution of classes - output$barplots_classes_metricUI <- renderPlotly({ - r_val_local$barplots_classes_metric - }) - - # listen to network changes and classify if new one is selected - observeEvent(c(r_val$network_region, r_val$classes_proposed_selected, r_val$manual_classes_table, r_val$tab_open2), { - - if (!is.null(r_val$network_region)) { - - # check if tab is open - if (r_val$tab_open2 == "Distribution des classes") { - - # classes proposed - if ((r_val$visualization == "classes") && !is.null(r_val$classes_proposed_selected)) { - - # Create classified network by adding the classes and colors - r_val$network_region_classified <- r_val$network_region %>% - na.omit() %>% - assign_classes_proposed(proposed_class = classes_proposed[r_val$classes_proposed_selected,]$class_name) - } - # classes manually selected - else if ((r_val$visualization == "manual") && !is.null(r_val$manual_classes_table)) { - - # Create classified network by adding the classes and colors - r_val$network_region_classified <- r_val$network_region %>% - na.omit() %>% - assign_classes_manual(classes = r_val$manual_classes_table) - } - - r_val$dgo_axis_classified = NULL - } - } - }) - - # listen to axis changes and classify if new one is selected - observeEvent(c(r_val$dgo_axis, r_val$classes_proposed_selected, r_val$manual_classes_table, r_val$tab_open2), { - - if (!is.null(r_val$dgo_axis)) { - - # check if tab is open - if (r_val$tab_open2 == "Distribution des classes") { - - # classes proposed - if ((r_val$visualization == "classes") && !is.null(r_val$classes_proposed_selected)){ - - # create classified axis network - r_val$dgo_axis_classified <- r_val$dgo_axis %>% - na.omit() %>% - assign_classes_proposed(proposed_class = classes_proposed[r_val$classes_proposed_selected,]$class_name) - } - # classes manually selected - else if ((r_val$visualization == "manual") && !is.null(r_val$manual_classes_table)) { - - # create classified axis network - r_val$dgo_axis_classified <- r_val$dgo_axis %>% - na.omit() %>% - assign_classes_manual(classes = r_val$manual_classes_table) - } - } - } - }) - - # classify regional and axis network and merge them - observeEvent(c(r_val$network_region_classified, r_val$dgo_axis_classified), { - - # check if tab is opend - if (r_val$tab_open2 == "Distribution des classes"){ - - # classes proposed - if (r_val$visualization == "classes") { - # merge regional and axis network in one df - r_val$merged_networks_classified <- merge_regional_axis_dfs(r_val$network_region_classified, - r_val$dgo_axis_classified, - "talweg_elevation_min", - classes = TRUE) - - } else if ((r_val$visualization == "manual") && !is.null(r_val$manual_classes_table)) { - - # merge regional and axis network in one df - r_val$merged_networks_classified <- merge_regional_axis_dfs(r_val$network_region_classified, - r_val$dgo_axis_classified, - r_val$manual_classes_table$variable[1], - classes = TRUE) - } - } - }) - - # create barplots of classes distribution - observeEvent(r_val$merged_networks_classified, { - if (!is.null(r_val$merged_networks_classified)) { - r_val_local$barplots_classes_metric <- create_plotly_barplot(r_val$merged_networks_classified) - r_val_local$placeholder_text = NULL - } else { - r_val_local$placeholder_text = "Sélectionnez une région sur la carte et appliquez une classification pour afficher le graphique." - r_val_local$barplots_classes_metric = NULL - } - }) - - - }) -} - diff --git a/R_old/mod_classification_manual.R b/R_old/mod_classification_manual.R deleted file mode 100644 index b2a3d27..0000000 --- a/R_old/mod_classification_manual.R +++ /dev/null @@ -1,364 +0,0 @@ - -# UI ---------------------------------------------------------------------- - -#' classification_manual UI Function -#' -#' @description A shiny Module. -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @import shiny -#' @importFrom bslib accordion accordion_panel -#' @importFrom shinyjs useShinyjs -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_classification_manual_ui <- function(id){ - ns <- NS(id) - tagList( - golem_add_external_resources(), - useShinyjs(), - fluidRow( - style = "margin-top: 10px;", - textOutput(ns("metric_placeholder_descriptionUI")) - ), - fluidRow( - uiOutput(ns("metric_selectUI")) - ), - fluidRow( - uiOutput(ns("classificationUI")) - ) - ) -} - - -# SERVER ------------------------------------------------------------------ - -#' classification_manual Server Functions -#' -#' @import shiny -#' @importFrom htmltools HTML div img -#' @importFrom dplyr filter mutate if_else pull bind_cols arrange add_row -#' @importFrom tibble tibble -#' @importFrom bslib sidebar page_sidebar -#' @importFrom leaflet removeControl clearGroup -#' @importFrom leaflet.extras addWMSLegend -#' @importFrom shinyjs onclick runjs -#' @importFrom colourpicker colourInput -#' @noRd -mod_classification_manual_server <- function(id, con, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - - ### REACTIVES #### - r_val_local <- reactiveValues( - metric_placeholder_description = "Cliquez sur une région hydrographique pour afficher la classification de métriques. ", - ui_metric = NULL, # metric selection element - - # classification - classification_ui = NULL, # UI placeholder - scale_selectUI = NULL, # scale selection element - initial_classes_table = NULL, # datainput for table - - reactableUI = NULL # reactable table - ) - - ### OUTPUTS #### - output$metric_placeholder_descriptionUI <- renderText({ - r_val_local$metric_placeholder_description - }) - - # metric select input - output$metric_selectUI <- renderUI({ - if (!is.null(r_val_local$ui_metric)) { - div( - style = "display: flex; align-items: center; margin-left: 20px", - r_val_local$ui_metric, - span( - style = "display: flex; margin-left: 10px; margin-top: -10px", - popover( - trigger = bsicons::bs_icon("info-circle"), - "", - placement = "right", - id = ns("popover_metric") - ) - ) - ) - } - }) - - # classification UI enabling creation of different classes based on selected metric - output$classificationUI <- renderUI({ - r_val_local$classification_ui - }) - - # classification UI enabling creation of different classes based on selected metric - output$scale_select_UI <- renderUI({ - r_val_local$scale_selectUI - }) - - # reactable table of classes - output$reactable_classes <- renderUI({ - r_val_local$reactableUI - }) - - - ### EVENTS #### - - # update infobutton when metric selected changes for the first and second metric - observe({ - if (!is.null(input$metric)) { - update_popover("popover_metric", - HTML(metrics_params %>% - filter(metric_name == input$metric) %>% - pull(metric_description))) - } - }) - - #### region clicked first time #### - observeEvent(c(r_val$region_clicked, r_val$tab_open1), { - - if ((r_val$region_clicked == TRUE) && - # check if tab is open - (r_val$tab_open1 == "Classification manuelle")) { - - # remove placeholder text - r_val_local$metric_placeholder_description = NULL - - # create elements of manual grouping pane - r_val_local$ui_metric = selectInput(ns("metric"), NULL, - choices = params_get_metric_choices(), - selected = params_get_metric_choices()[1], - width = "100%") - - # create classification UI - r_val_local$classification_ui <- fluidPage( - fluidRow( - page_sidebar( - sidebar = sidebar( - fluidRow( - column(width = 7, - numericInput(inputId = ns("man_grouping_quantile"), - "Quantile [%]", value = 95, min = 0, max = 100) - ), - column(width = 5, - numericInput(inputId = ns("man_grouping_no_classes"), - "Classes", value = 4, min = 2, max = 10, step = 1) - ), - uiOutput(ns("scale_select_UI")), - actionButton(inputId = ns("recalculate_classes_button"), "Recalculer classes") - ), open = "closed", width = 220, position = "right" - ), - uiOutput(ns("reactable_classes")), - actionButton(inputId = ns("apply_to_map_button"), "Ajouter à la carte") - )) - ) - - # create classes-table to initialize classes UI - r_val_local$initial_classes_table = create_df_input( - axis_data = r_val$network_region, - variable_name = params_get_metric_choices()[[1]], - no_classes = 4, - quantile = 95 - ) - } - - }) - - #### region selected #### - observeEvent(c(r_val$region_click, r_val$tab_open1), { - - if (r_val$tab_open1 == "Classification manuelle") { - - # change scale selection UI - r_val_local$scale_selectUI = radioButtons(ns("man_grouping_scale_select"), - "Base de classification", - c("Région"), - selected = "Région", - inline = TRUE) - } - }) - - #### axis clicked first time #### - observe({ - - if ((r_val$axis_clicked == TRUE) && (r_val$tab_open1 == "Classification manuelle")){ - - # change scale selection UI - r_val_local$scale_selectUI = radioButtons(ns("man_grouping_scale_select"), - "Base de classification", - c("Région", "Axe fluvial"), - selected = "Région", - inline = TRUE) - } - }) - - #### metric change / re-calculation clicked #### - observeEvent(c(r_val$region_clicked, r_val$tab_open1), { - - if (r_val$tab_open1 == "Classification manuelle") { - - # check for valid selected metric - if (!is.null(input$metric) && - !is.null(r_val$network_region) && - (r_val$region_clicked == TRUE)) { - - # create classes-table - r_val_local$initial_classes_table = create_df_input( - axis_data = r_val$network_region, - variable_name = input$metric, - no_classes = input$man_grouping_no_classes, - quantile = input$man_grouping_quantile - ) - } - } - }) - - #### changes affecting classes #### - observeEvent(c(input$metric, r_val$network_region, input$recalculate_classes_button), { - - if (r_val$tab_open1 == "Classification manuelle") { - if (!is.null(input$metric) && - !is.null(input$man_grouping_scale_select)) { - - # region selected - if (input$man_grouping_scale_select == "Région" && - !is.null(r_val$network_region)) { - - # create classes-table - r_val_local$initial_classes_table = create_df_input( - axis_data = r_val$network_region, - variable_name = input$metric, - no_classes = input$man_grouping_no_classes, - quantile = input$man_grouping_quantile - ) - } - # axis selected - else if (input$man_grouping_scale_select == "Axe fluvial" && - !is.null(r_val$dgo_axis) ) { - - # create classes-table - r_val_local$initial_classes_table = create_df_input( - axis_data = r_val$dgo_axis, - variable_name = input$metric, - no_classes = input$man_grouping_no_classes, - quantile = input$man_grouping_quantile - ) - } - } - # when scale selection not created - else if (!is.null(input$metric) && - is.null(input$man_grouping_scale_select) && - !is.null(r_val$network_region)) { - - # create classes-table - r_val_local$initial_classes_table = create_df_input( - axis_data = r_val$network_region, - variable_name = input$metric, - no_classes = 4, - quantile = 95 - ) - } - } - - }) - - - #### UI classes creation #### - # update input fields for classification when setting the variables in the UI - observeEvent(r_val_local$initial_classes_table, { - - if (!is.null(r_val_local$initial_classes_table)) { - - # create classes UI - r_val_local$reactableUI = - renderUI({ - # Start with a list to collect UI elements - ui_elements <- list() - - # Add the first row of inputs - ui_elements[[1]] <- fluidRow( - column(width = 5, textInput(ns("class1"), label = "Classe", value = r_val_local$initial_classes_table$class[1])), - column(width = 3, colourInput(ns("color1"), label = "Couleur", - value = r_val_local$initial_classes_table$color[1], - showColour = "background", closeOnClick = TRUE)), - column(width = 4, numericInput(ns("greaterthan1"), label = "supérieur à", value = r_val_local$initial_classes_table$greaterthan[1])) - ) - - # Loop through the remaining rows and add inputs - for (row in 2:nrow(r_val_local$initial_classes_table)) { - ui_elements[[row]] <- fluidRow( - column(width = 5, textInput(ns(paste0("class", row)), label = NULL, value = r_val_local$initial_classes_table$class[row])), - column(width = 3, colourInput(ns(paste0("color", row)), label = NULL, - value = r_val_local$initial_classes_table$color[row], - showColour = "background", closeOnClick = TRUE)), - column(width = 4, numericInput(ns(paste0("greaterthan", row)), label = NULL, value = r_val_local$initial_classes_table$greaterthan[row])) - ) - } - - # Return the list of UI elements wrapped in tagList - do.call(tagList, ui_elements) - }) - } - }) - - #### apply-to-map button clicked #### - observeEvent(input$apply_to_map_button,{ - - r_val$visualization = "manual" - }) - - #### visualisation switched to manual #### - observeEvent(c(r_val$visualization, r_val$region_click, input$apply_to_map_button), { - - if (r_val$visualization == "manual") { - - # create classes table from input - # Initialize an empty tibble - r_val$manual_classes_table <- tibble(variable = character(), class = character(), greaterthan = numeric(), color = character()) - - # Add rows to the tibble looping through number of classes - if (!is.null(input$man_grouping_no_classes)) { - for (row in 1:input$man_grouping_no_classes) { - r_val$manual_classes_table <- r_val$manual_classes_table %>% - add_row(variable = input$metric, - class = input[[paste0("class", row)]], - greaterthan = input[[paste0("greaterthan", row)]], - color = input[[paste0("color", row)]]) - } - } else { - for (row in 1:4) { - r_val$manual_classes_table <- r_val$manual_classes_table %>% - add_row(variable = input$metric, - class = input[[paste0("class", row)]], - greaterthan = input[[paste0("greaterthan", row)]], - color = input[[paste0("color", row)]]) - } - } - - - # sort classes - classes <- r_val$manual_classes_table %>% - dplyr::arrange(greaterthan) %>% - dplyr::mutate(greaterthan = round(greaterthan, 2)) - - # build SLD symbology - r_val$sld_body = sld_get_style( - breaks = classes$greaterthan, - colors = classes$color, - metric = classes$variable[1] - ) - - # add classified network to map - r_val$map_proxy %>% - map_metric(wms_params = params_wms()$metric, - cql_filter = paste0("gid_region=",r_val$selected_region_feature[["gid"]]), - sld_body = r_val$sld_body, - data_axis = r_val$network_region_axis) - } - - }) - }) -} diff --git a/R_old/mod_classification_proposed - Copie.R b/R_old/mod_classification_proposed - Copie.R deleted file mode 100644 index 07e801c..0000000 --- a/R_old/mod_classification_proposed - Copie.R +++ /dev/null @@ -1,103 +0,0 @@ -#' classification_proposed UI Function -#' -#' @description A shiny Module. -#' -#' @import shiny -#' @importFrom shinyjs useShinyjs -#' @importFrom reactable reactableOutput -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_classification_proposed_ui <- function(id){ - ns <- NS(id) - tagList( - useShinyjs(), - fluidRow( - style = "margin-top: 10px;", - textOutput(ns("placeholder_ui")), - reactableOutput(ns("table"), width = "100%") - ) - ) -} - -#' classification_proposed Server Functions -#' -#' @import shiny -#' @importFrom reactable renderReactable getReactableState updateReactable -#' -#' @noRd -mod_classification_proposed_server <- function(id, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - r_val_local <- reactiveValues( - classes_tbl = NULL, - table = NULL, - placeholder_text = "Sélectionnez une région hydrographique sur la carte pour afficher la classification.", - selected = NULL - ) - - # text placeholder - output$placeholder_ui <- renderText({ - r_val_local$placeholder_text - }) - - output$table <- renderReactable( - r_val_local$table - ) - - # build table when region first time clicked - observeEvent(r_val$region_clicked, { - - if (!is.null(r_val$region_click)) { - r_val_local$placeholder_text = NULL - r_val_local$table = create_table_fluvialstyles(classes_proposed) - } - }) - - # create table output and add classification to map when region changed or other variable selected - observeEvent(c(input$table__reactable__selected, r_val$region_click), { - - # get actual selected classification from table - selected <- getReactableState("table", "selected") - - # check if row is actually selected - if (!is.null(selected)) { - - # create map styling based on selected classification - r_val$sld_body = classes_proposed[selected,]$class_sld - - # add styling to map - r_val$map_proxy %>% - map_class(wms_params = params_wms()$class, - cql_filter = paste0("gid_region=",r_val$selected_region_feature[["gid"]]), - sld_body = r_val$sld_body, - style = paste0("mapdo:", classes_proposed[selected,]$sld_style), - data_axis = r_val$network_region_axis) - - # set visualisation to classes to tell app that proposed classes are selected - r_val$visualization = "classes" - - r_val_local$selected = selected - } - }) - - observeEvent(r_val_local$selected, { - if (!is.null(r_val_local$selected)) { - r_val$classes_proposed_selected = r_val_local$selected - } - - }) - - - # check if other visualization is applied to map and de-select all proposed classifications - observeEvent(r_val$visualization, { - if (r_val$visualization != "classes") { - updateReactable("table", selected = NA) - } - }) - }) -} diff --git a/R_old/mod_classification_proposed.R b/R_old/mod_classification_proposed.R deleted file mode 100644 index bcb596a..0000000 --- a/R_old/mod_classification_proposed.R +++ /dev/null @@ -1,91 +0,0 @@ -#' classification_proposed UI Function -#' -#' @description A shiny Module. -#' -#' @import shiny -#' @importFrom shinyjs useShinyjs -#' @importFrom reactable reactableOutput -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_classification_proposed_ui <- function(id){ - ns <- NS(id) - tagList( - useShinyjs(), - fluidRow( - style = "margin-top: 10px;", - textOutput(ns("placeholder_ui")), - reactableOutput(ns("table"), width = "100%") - ) - ) -} - -#' classification_proposed Server Functions -#' -#' @import shiny -#' @importFrom reactable renderReactable getReactableState updateReactable -#' -#' @noRd -mod_classification_proposed_server <- function(id, r_val, globals){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - r_val_local <- reactiveValues( - classes_tbl = NULL, - table = NULL, - selected = NULL - ) - - # build table - output$table <- renderReactable( - create_table_fluvialstyles(globals$classes_proposed) - ) %>% - bindCache(globals$classes_proposed$sld_style) - - - # create table output and add classification to map when other variable selected - # observeEvent(input$table__reactable__selected, { - # - # # get actual selected classification from table - # selected <- getReactableState("table", "selected") - # - # # check if row is actually selected - # if (!is.null(selected)) { - # - # # create map styling based on selected classification - # r_val$sld_body = classes_proposed[selected,]$class_sld - # - # # add styling to map - # r_val$map_proxy %>% - # map_class(wms_params = params_wms()$class, - # cql_filter = paste0("gid_region=",r_val$selected_region_feature[["gid"]]), - # sld_body = r_val$sld_body, - # style = paste0("mapdo:", classes_proposed[selected,]$sld_style), - # data_axis = r_val$network_region_axis) - # - # # set visualisation to classes to tell app that proposed classes are selected - # r_val$visualization = "classes" - # - # r_val_local$selected = selected - # } - # }) - - # observeEvent(r_val_local$selected, { - # if (!is.null(r_val_local$selected)) { - # r_val$classes_proposed_selected = r_val_local$selected - # } - # - # }) - - - # check if other visualization is applied to map and de-select all proposed classifications - # observeEvent(r_val$visualization, { - # if (r_val$visualization != "classes") { - # updateReactable("table", selected = NA) - # } - # }) - }) -} diff --git a/R_old/mod_documentation.R b/R_old/mod_documentation.R deleted file mode 100644 index e3ab30b..0000000 --- a/R_old/mod_documentation.R +++ /dev/null @@ -1,49 +0,0 @@ -#' documentation UI Function -#' -#' @description A shiny Module. -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @import shiny -mod_documentation_ui <- function(id){ - ns <- NS(id) - tagList( - golem_add_external_resources(), - fluidPage( - HTML(" -

MAPD'O est un projet visant le développement d'une interface web à l'intention des opérateurs autour des données et modèles en hydromorphologie. C'est un projet réalisé par le laboratoire Environnement Ville Société du CNRS et porté par l'Office Français de la Biodiversité depuis janvier 2023.

- -

L'application repose sur des approches géomatiques d'analyse de la topographie et de l'occupation du sol permettant de produire une carte de continuité latérale des cours d'eau du réseau hydrographique. Différentes métriques morphologiques sont ensuite extraites à intervalle régulier du réseau (largeur, pente, surface drainée, élévation). L'application a pour ambition de fournir des outils d'analyse et d'interprétation de ces métriques afin de faciliter les diagnostics hydromorphologiques des cours d'eau français à l'échelle du bassin versant.

- -

L'application dispose aujourd'hui d'un module d'exploration des données permettant de visualiser les différentes métriques mises à disposition pour l'analyse de bassin versant.

- "), - HTML(" -

Contact : Lise Vaudor (CNRS UMR 5600, Environnement Ville Société) - lise.vaudor@ens-lyon.fr

- "), - tags$a( - href = "https://evs-gis.github.io/mapdowebsite/", - icon("book"), - "Toute la documentation est ici", - target = "_blank" - ) - ) - ) -} - -#' documentation Server Functions -#' -#' @noRd -mod_documentation_server <- function(id){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - }) -} - -## To be copied in the UI -# mod_documentation_ui("documentation_1") - -## To be copied in the server -# mod_documentation_server("documentation_1") diff --git a/R_old/mod_explore.R b/R_old/mod_explore.R deleted file mode 100644 index d6ef8f2..0000000 --- a/R_old/mod_explore.R +++ /dev/null @@ -1,914 +0,0 @@ -# for dev, create reactivity graph -# library(reactlog) -# reactlog_enable() - -#' explore UI Function -#' -#' @description A shiny Module. -#' -#' @param id shiny id -#' -#' @rdname mod_explore -#' -#' @import shiny -#' @importFrom shinyjs useShinyjs -#' @importFrom shinycssloaders withSpinner -#' @importFrom bslib popover -#' @importFrom bsicons bs_icon -#' -mod_explore_ui <- function(id){ - ns <- NS(id) - tagList( - # Leave this function for adding external resources - golem_add_external_resources(), - fluidPage( - useShinyjs(), - tags$head( - tags$style( - HTML(".form-group{margin-bottom: 10px}") # less space below selectInput metric_type - ) - ), - fluidRow( - column( - width = 6, - withSpinner(leafletOutput(ns("exploremap"), height = 700)) - ), # column - column( - width = 3, - uiOutput(ns("metricUI")), - uiOutput(ns("areaUI")), - uiOutput(ns("radioButtonsUI")) # uiOutput radios buttons metrics - ), # column - - column( - width = 2, - uiOutput(ns("strahlerfilterUI")), - uiOutput(ns("metricsfilterUI")), - uiOutput(ns("legendUI")), - # uncomment line below to add the download button - # uiOutput(ns("downloadUI")) - ) # column - ), # fluidRow - fluidRow( - tabsetPanel( - tabPanel( - "Profil en long", - div( - fluidRow( - column(width = 9, - plotlyOutput(ns("long_profile")) - ), - column( - width = 3, - style = "margin-top: 20px;", - uiOutput(ns("profilemetricUI")), - uiOutput(ns("profileareaUI")), - uiOutput(ns("profileradiobuttonUI")), - uiOutput(ns("removeprofileaxeUI"), - style = "margin-top: 10px;"), # more space above button - uiOutput(ns("profileroeUI"), - style = "margin-top: 10px;") - ) - ) - ) - ), # tabPanel - tabPanel( - title = div("Profil en travers", - span( - style = "display: inline; align-items: center", - popover( - trigger = bs_icon("info-circle"), - "Profil transversal médian correspondant à la - médiane des valeurs des transects réalisées tout les - 10m sur le fond de vallée du tronçon sélectionné", - placement = "right", - id = "popover_cross_section" - ) - )), - div( - fluidRow( - column(width = 12, - plotlyOutput(ns("cross_section")) - ) - ) - ) - ) # tabPanel - )# tabsetPanel - ),# fluidRow - ### UI DEV TOOLS #### - - # fluidRow( - # column( - # width = 4, - # actionButton(ns("browser"), "browser") - # ), - # column( - # width = 8, - # verbatimTextOutput(ns("printcheck")) - # ) - # ) # fluidRow DEV TOOLS - - ### END DEV TOOLS - ) # fluidPage - ) # tagList -} - -#' explore Server Functions -#' -#' @param input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @import shiny -#' @importFrom leaflet leafletProxy clearGroup leafletOutput renderLeaflet -#' @importFrom htmltools HTML div img -#' @importFrom dplyr filter mutate if_else pull -#' @importFrom plotly event_register event_data plotlyProxy plotlyProxyInvoke renderPlotly plotlyOutput -#' @importFrom bslib popover update_popover -#' @importFrom bsicons bs_icon -#' @importFrom sf st_write -#' @importFrom shinyjs onclick runjs -#' -mod_explore_server <- function(id, con){ - moduleServer(id, function(input, output, session){ - - ns <- session$ns - - ### DEV TOOLS #### - output$printcheck = renderPrint({ - tryCatch({ - # event_data("plotly_hover") - print(input$exploremap_center) - print("exists") - }, - shiny.silent.error = function(e) { - print("doesn't exist") - } - ) - }) - observeEvent(input$browser, { - browser() - }) - - ### R_VAL #### - r_val <- reactiveValues( - ### reactivity controler - region_already_clicked = FALSE, - profile_display = FALSE, # controle if metric and axis is selected = display the profile - - ### data - bassins = NULL, # bassins data - regions_in_bassin = NULL, # all the regions in selected bassin - network_region_axis = NULL, # all the axis in the selected region - selected_region_feature = NULL, # region data clicked - region_click = NULL, # region clicked information list - axis_click = NULL, # axis clicked information list - dgo_axis = NULL, # all DGO in selected axis - axis_start_end = NULL, # start / end df coordinates to add pin on map - strahler = NULL, # min and max strahler values to set strahler filter UI - min_max_metric = NULL, # min and max metric values to set metric filter UI - selected_axis_df = NULL, # DGO in axis dataframe to plot longitudinal profile - data_section = NULL, # DGO elevation data for section profile - roe_region = NULL, # ROE data in selected region - roe_axis = NULL, # ROE data in selected axis - hydro_sites_region = NULL, # hydro sites data in selected region - data_dgo_clicked = NULL, # DGO clicked by user for cross section profile - - ### metric selected by user - selected_metric = NULL, # select main metric column name - selected_metric_name = NULL, # select main metric name to display for user - selected_metric_type = NULL, # select main metric type name to display for user - - ### profile metric selected by user - selected_profile_metric = NULL, # select second metric column name - selected_profile_metric_name = NULL, # select second metric name to display for user - selected_profile_metric_type = NULL, # select second metric type name to display for user - - ### render UI generator - plot = lg_profile_empty(), # plotly render longitudinal profile output (default empty) - section = cr_profile_empty(), # plotly render cross section output (default empty) - ui_strahler_filter = NULL, - ui_metric_type = NULL, - ui_metric = NULL, - ui_unit_area = NULL, - ui_metric_filter = NULL, - ui_profile_metric_type = NULL, - ui_profile_metric = NULL, - ui_profile_unit_area = NULL, - ui_remove_profile_axe = NULL, - ui_roe_profile = NULL, - ui_download = NULL, - - ### geoserver controler - cql_filter = NULL, # WMS filter - sld_body = NULL, # WMS SLD symbology - - ### others variables - opacity = list(clickable = 0.01, not_clickable = 0.10), # opacity value to inform the user about available bassins and regions - leaflet_hover_measure = 2.5, # measure field from mesure to add vertical line on longitudinal profile - leaflet_hover_shapes = list(shapes = list(lg_vertical_line(2.5))), # list to store vertical lines to display on longitudinal profile - roe_vertical_line = NULL, # list with verticale line to plot on longitudinal profile - region_name = NULL # region name file formatted to be download - ) - - ### INIT MAP & PROFILE #### - - output$exploremap <- renderLeaflet({ - r_val$bassins = data_get_bassins(opacity = r_val$opacity, con = con) - map_init_bassins(bassins_data = r_val$bassins, - id_logo_ign_remonterletemps = ns("logo_ign_remonterletemps")) - }) - - onclick(id = "logo_ign_remonterletemps", expr = - runjs(sprintf("window.open('%s', '_blank')", - utils_url_remonterletemps(lng = input$exploremap_center$lng, - lat = input$exploremap_center$lat, - zoom = input$exploremap_zoom))) - ) - - output$long_profile <- renderPlotly({ - return(r_val$plot) - }) - - output$cross_section <- renderPlotly({ - return(r_val$section) - }) - - ### RENDER UI #### - - #### profile #### - - # add input UI for profile additional metric - output$profilemetricUI <- renderUI({ - r_val$ui_profile_metric_type - }) - - # add radiobutton for profile additional metric - output$profileradiobuttonUI <- renderUI({ - r_val$ui_profile_metric - }) - - # UI switch unit area for profile additional metric - output$profileareaUI <- renderUI({ - r_val$ui_profile_unit_area - }) - - # button to remove second axe - output$removeprofileaxeUI <- renderUI({ - r_val$ui_remove_profile_axe - }) - - # checkbox display ROE - output$profileroeUI <- renderUI({ - r_val$ui_roe_profile - }) - - #### metric #### - - # UI create choose metric - output$metricUI <- renderUI({ - if (!is.null(r_val$ui_metric_type)){ - div( - style = "display: flex; align-items: center; margin-bottom: 0px", - r_val$ui_metric_type, - span( - style = "display: flex; margin-left: 10px; margin-top: 12px", - popover( - trigger = bsicons::bs_icon("info-circle"), - "", - placement = "right", - id = ns("popover_metric_type") - ) - ) - ) - } else { - HTML('') - } - }) - - # UI metrics radio buttons - output$radioButtonsUI <- renderUI({ - r_val$ui_metric - }) - - # UI switch unit area - output$areaUI <- renderUI({ - r_val$ui_unit_area - }) - - #### download #### - - # Uncomment below to create add the download button - # output$downloadUI <- renderUI({ - # r_val$ui_download - # }) - # - # output$download <- downloadHandler( - # filename = function() { - # paste0(Sys.Date(), "_", r_val$region_name, ".gpkg") - # }, - # content = function(file) { - # data = data_get_dgo_in_region(r_val$region_click$id, con = con) - # st_write(obj = data, dsn = file, layer = r_val$region_name, - # driver = "GPKG", delete_dsn = TRUE) - # } - # ) - - #### filter #### - - # UI strahler filter - output$strahlerfilterUI <- renderUI( - { - r_val$ui_strahler_filter - }) - - # UI dynamic filter on metric selected - output$metricsfilterUI <- renderUI({ - r_val$ui_metric_filter - }) - - #### map legend #### - - metric_legend <- reactiveVal(NULL) - - output$legendUI <- renderUI({ - - div( - HTML(''), - # metric - div( - style = "display: flex; align-items: center;", - metric_legend(), - ), - # landuse map - if (any(input$exploremap_groups %in% params_map_group()$landuse)) { - map_legend_wms_overlayer(wms_params = params_wms()$landuse) - }, - # continuity map - if (any(input$exploremap_groups %in% params_map_group()$continuity)) { - map_legend_wms_overlayer(wms_params = params_wms()$continuity) - }, - # valley bottom map - if (any(input$exploremap_groups %in% params_map_group()$valley_bottom)) { - map_legend_wms_overlayer(wms_params = params_wms()$valley_bottom) - }, - # zone inondable - if (any(input$exploremap_groups %in% params_map_group()$inondation)) { - map_legend_wms_overlayer(wms_params = params_wms()$inondation) - }, - # ouvrage de protection - if (any(input$exploremap_groups %in% params_map_group()[["ouvrage_protection"]])) { - map_legend_wms_overlayer(wms_params = params_wms()$ouvrage_protection) - }, - # ROE - if (any(input$exploremap_groups %in% params_map_group()[["roe"]])) { - map_legend_vector_overlayer(layer_label = "Référentiel des Obstacles à l'Ecoulement", - color = "#323232") - }, - # Site hydrométrique - if (any(input$exploremap_groups %in% params_map_group()[["hydro_sites"]])) { - map_legend_vector_overlayer(layer_label = "Site hydrométrique", - color = "#33B1FF") - }, - style = "margin-bottom: 10px;" - ) # div - }) - - ### EVENT MAP CLICK #### - - observeEvent(input$exploremap_shape_click,{ - - # track input - track_inputs(input = input) - - #### bassin clicked #### - if (input$exploremap_shape_click$group == params_map_group()[["bassin"]]){ - # disable the click interactivity for the bassin selected - r_val$bassins = r_val$bassins %>% - mutate(click = if_else(display == TRUE, - TRUE, - click)) %>% - mutate(click = if_else(display == TRUE & cdbh == input$exploremap_shape_click$id, - FALSE, - click)) - # get the regions data in selected bassin - r_val$regions_in_bassin = data_get_regions_in_bassin(selected_bassin_id = input$exploremap_shape_click$id, - opacity = r_val$opacity, - con = con) - # update map : zoom in clicked bassin, clear bassin data, display region in bassin - leafletProxy("exploremap") %>% - map_add_regions_in_bassin(bassin_click = input$exploremap_shape_click, - regions_data = r_val$regions_in_bassin, - bassins_data = r_val$bassins) - } - - ### region clicked #### - if (input$exploremap_shape_click$group == params_map_group()$region){ - # store the region click values - r_val$region_click = input$exploremap_shape_click - # disable the click interactivity for the bassin selected - r_val$regions_in_bassin = r_val$regions_in_bassin %>% - mutate(click = if_else(display == TRUE, - TRUE, - click)) %>% - mutate(click = if_else(display == TRUE & gid == r_val$region_click$id, - FALSE, - click)) - - # save the selected region feature for mapping - r_val$selected_region_feature = data_get_region(region_click_id = r_val$region_click$id, - con = con) - # set region name to download - r_val$region_name = utils_normalize_string(r_val$selected_region_feature$lbregionhy) - # get the axis in the region - r_val$network_region_axis = data_get_axis(selected_region_id = r_val$region_click$id, - con = con) - # get ROE in region - r_val$roe_region = data_get_roe_in_region(r_val$region_click$id, - con = con) - # get hydro sites in region - r_val$hydro_sites_region = data_get_hydro_sites(r_val$region_click$id, - con = con) - # get strahler data - r_val$strahler = isolate(data_get_min_max_strahler(selected_region_id = r_val$region_click$id, - con = con)) - # build strahler slider - r_val$ui_strahler_filter = sliderInput(ns("strahler"), - label="Ordre de strahler", - min=r_val$strahler[["min"]], - max=r_val$strahler[["max"]], - value=c(r_val$strahler[["min"]], - r_val$strahler[["max"]]), - step=1) - - # map region clicked with region clicked and overlayers - leafletProxy("exploremap") %>% - map_region_clicked(region_click = input$exploremap_shape_click, - selected_region_feature = r_val$selected_region_feature, - regions_data = r_val$regions_in_bassin, - roe_region = r_val$roe_region, - hydro_sites_region = r_val$hydro_sites_region) - - # run only once, control with region_already_clicked - if (r_val$region_already_clicked == FALSE){ - # build metric selectInput - r_val$ui_metric_type = - selectInput(ns("metric_type"), "Sélectionnez une métrique :", - choices = utils_get_metric_type(params_metrics_choice()), - selected = utils_get_metric_type(params_metrics_choice())[1]) - - # create download button - r_val$ui_download = downloadButton( - ns("download"), - label = "Télécharger les données" - ) - r_val$region_already_clicked = TRUE - } - } - ### axis clicked #### - - if (input$exploremap_shape_click$group == params_map_group()$axis) { - # save the clicked axis values - r_val$axis_click = input$exploremap_shape_click - # reget the axis in the region without the selected axis - r_val$network_region_axis = data_get_axis(selected_region_id = r_val$region_click$id, - con = con) %>% - filter(axis != r_val$axis_click$id) - # get the DGO axis data - r_val$dgo_axis = data_get_network_axis(selected_axis_id = r_val$axis_click$id, - con = con) %>% - mutate(measure = measure/1000) - # extract axis start end point - r_val$axis_start_end = data_get_axis_start_end(dgo_axis = r_val$dgo_axis) - # get ROE in axis clicked - r_val$roe_axis = r_val$roe_region %>% - filter(axis == r_val$axis_click$id) - - # map dgo axis when axis clicked and metric selected - leafletProxy("exploremap") %>% - map_dgo_axis(selected_axis = r_val$dgo_axis, region_axis = r_val$network_region_axis, - main_metric = r_val$selected_metric, second_metric = r_val$selected_profile_metric) %>% - map_axis_start_end(axis_start_end = r_val$axis_start_end, region_axis = r_val$network_region_axis) - - # create or update profile dataset with new axis - r_val$selected_axis_df = r_val$dgo_axis %>% - as.data.frame() - - # update profile with new metric selected - if (r_val$profile_display == TRUE){ - proxy_main_axe <- - lg_profile_update_main( - data = r_val$selected_axis_df, - y = r_val$selected_axis_df[[r_val$selected_metric]], - y_label = r_val$selected_metric_name, - y_label_category = r_val$selected_metric_type - ) - - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 0) %>% - plotlyProxyInvoke("addTraces", proxy_main_axe$trace, 0) %>% - plotlyProxyInvoke("relayout", proxy_main_axe$layout) - - # update ROE vertical lines - if (input$roe_profile == TRUE){ - if (!is.null(r_val$roe_vertical_line)){ - # remove the previous ROE vertical lines if exist - r_val$leaflet_hover_shapes$shapes <- list(r_val$leaflet_hover_shapes$shapes[[1]]) - } - # create the vertical line from ROE distance_axis - r_val$roe_vertical_line <- lg_roe_vertical_line(r_val$roe_axis$distance_axis) - # increment the vertical list shape to keep the hover map vertical line - r_val$leaflet_hover_shapes$shapes <- c(r_val$leaflet_hover_shapes$shapes, - r_val$roe_vertical_line) - # update profile - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("relayout", r_val$leaflet_hover_shapes) - }else{ - # remove the previous ROE vertical lines if exist - r_val$leaflet_hover_shapes$shapes <- list(r_val$leaflet_hover_shapes$shapes[[1]]) - # update profile - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("relayout", r_val$leaflet_hover_shapes) - } - - - if(!is.null(input$profile_metric)){ # second metric selected = update second metric profile - # create the list to add trace and layout to change second axe plot - proxy_second_axe <- lg_profile_second(data = r_val$selected_axis_df, - y = r_val$selected_axis_df[[r_val$selected_profile_metric]], - y_label = r_val$selected_profile_metric_name, - y_label_category = r_val$selected_profile_metric_type) - - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 1) %>% - plotlyProxyInvoke("addTraces", proxy_second_axe$trace, 1) %>% - plotlyProxyInvoke("relayout", proxy_second_axe$layout) - } - } - } - - ### dgo clicked #### - - if (input$exploremap_shape_click$group == params_map_group()$dgo_axis) { - # get data with dgo id - r_val$data_section = data_get_elevation_profiles(selected_dgo_fid = input$exploremap_shape_click$id, - con = con) - # plot cross section - r_val$section = cr_profile_main(data = r_val$data_section, - axis_toponyme = unique(r_val$selected_axis_df$toponyme)) - # get dgo clicked feature - r_val$data_dgo_clicked = r_val$dgo_axis %>% - filter(fid == input$exploremap_shape_click$id) - # Highlight clicked DGO - leafletProxy("exploremap") %>% - map_dgo_cross_section(selected_dgo = r_val$data_dgo_clicked) - } - }) - - ### EVENT METRIC #### - - #### metric type select #### - - observeEvent(input$metric_type, { - - # track input - track_inputs(input = input) - - if (!is.null(input$metric_type)){ - update_popover("popover_metric_type", - HTML(params_metrics_choice()[[input$metric_type]]$metric_type_info)) - } - - - # build metric radioButtons with popover icon - r_val$ui_metric = radioButtons( - inputId = ns("metric"), - label = NULL, - choiceNames = utils_button_label_with_popover(input$metric_type), - choiceValues = as.list(names(utils_get_metric_name_value(input$metric_type))), - selected = character(0) - ) - - # build selectInput unit area for landuse or continuity - if (input$metric_type == "landuse" || input$metric_type == "continuity"){ - r_val$ui_unit_area = selectInput(ns("unit_area"), "Surfaces :", - choices = params_unit_area(), - selected = unname(params_unit_area()[1])) - }else{ - r_val$ui_unit_area = NULL - } - }) - - #### metric select #### - - observeEvent(c(input$metric, input$unit_area), ignoreInit = TRUE, { - - # track input - track_inputs(input = input) - - # change field if unit_area in percentage - if (!is.null(input$metric) && input$unit_area == "percent" - && (input$metric_type %in% c("landuse", "continuity"))){ - r_val$selected_metric = paste0(input$metric,"_pc") - } else if (!is.null(input$metric)) { - r_val$selected_metric = input$metric - } - - if (!is.null(input$metric)){ - r_val$selected_metric_name = params_metrics_choice()[[input$metric_type]]$metric_type_values[[input$metric]]$metric_title - r_val$selected_metric_type = params_metrics_choice()[[input$metric_type]]$metric_type_title - - # build metric filter slider - r_val$min_max_metric <- data_get_min_max_metric(selected_region_id = r_val$region_click$id, - selected_metric = r_val$selected_metric, - con = con) - - r_val$ui_metric_filter = sliderInput(ns("metricfilter"), - label = r_val$selected_metric_name, - min = isolate(r_val$min_max_metric[["min"]]), - max = isolate(r_val$min_max_metric[["max"]]), - value = c( - isolate(r_val$min_max_metric[["min"]]), - isolate(r_val$min_max_metric[["max"]]) - ) - ) - - # update profile with new metric selected - if (r_val$profile_display == TRUE){ - - proxy_main_axe <- - lg_profile_update_main( - data = r_val$selected_axis_df, - y = r_val$selected_axis_df[[r_val$selected_metric]], - y_label = r_val$selected_metric_name, - y_label_category = r_val$selected_metric_type - ) - - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 0) %>% - plotlyProxyInvoke("addTraces", proxy_main_axe$trace, 0) %>% - plotlyProxyInvoke("relayout", proxy_main_axe$layout) - } - } - }) - - ### EVENT METRIC & AXIS RESULTS #### - - observeEvent(c(r_val$selected_metric, r_val$axis_click), { - - if (r_val$profile_display == FALSE){ - - # track input - track_inputs(input = input) - - if (!is.null(r_val$selected_metric) && !is.null(r_val$axis_click)){ - - r_val$profile_display = TRUE # this event run only one time controlled with profile_display - - # build input for profile metric type - r_val$ui_profile_metric_type = selectInput(ns("profile_metric_type"), "Ajoutez une métrique :", - choices = utils_get_metric_type(params_metrics_choice()), - selected = utils_get_metric_type(params_metrics_choice())[1]) - - # built ROE checkboxInput and input - r_val$ui_roe_profile = checkboxInput(ns("roe_profile"), label = "ROE", value = FALSE) - - # update dgo on axis to reset tooltip - leafletProxy("exploremap") %>% - map_dgo_axis(selected_axis = r_val$dgo_axis, region_axis = r_val$network_region_axis, - main_metric = r_val$selected_metric, second_metric = r_val$selected_profile_metric) - - # plot single axe with metric selected - r_val$plot = lg_profile_main(data = r_val$selected_axis_df, - y = r_val$selected_axis_df[[r_val$selected_metric]], - y_label = r_val$selected_metric_name, - y_label_category = r_val$selected_metric_type) %>% - event_register("plotly_hover") - } - } - }) - - ### EVENT PROFILE METRIC #### - - #### profile metric type select #### - - observeEvent(input$profile_metric_type, { - - # track input - track_inputs(input = input) - - # build profile metric radio button - r_val$ui_profile_metric = radioButtons( - inputId = ns("profile_metric"), - label = NULL, - choiceNames = unname(utils_get_metric_name_value(input$profile_metric_type)), - choiceValues = names(utils_get_metric_name_value(input$profile_metric_type)), - selected = character(0) - ) - - # build profile unit area select - if (input$profile_metric_type == "landuse" || - input$profile_metric_type == "continuity") { - r_val$ui_profile_unit_area = selectInput( - ns("profile_unit_area"), - "Surfaces :", - choices = params_unit_area(), - selected = unname(params_unit_area()[1]) - ) - } else{ - r_val$ui_profile_unit_area = NULL - } - - r_val$ui_remove_profile_axe = actionButton( - ns("remove_profile_axe"), - label = "Retirer le second axe" - ) - }) - - #### profile metric select #### - - observeEvent(c(input$profile_metric, input$profile_unit_area), ignoreInit = TRUE, { - - # track input - track_inputs(input = input) - - # change field if unit_area in percentage - if (!is.null(input$profile_metric) && input$profile_unit_area == "percent" - && (input$profile_metric_type %in% c("landuse", "continuity"))){ - r_val$selected_profile_metric = paste0(input$profile_metric,"_pc") - } else if (!is.null(input$profile_metric)) { - r_val$selected_profile_metric = input$profile_metric - } - - if (!is.null(input$profile_metric)){ - r_val$selected_profile_metric_name = params_metrics_choice()[[input$profile_metric_type]]$metric_type_values[[input$profile_metric]]$metric_title - r_val$selected_profile_metric_type = params_metrics_choice()[[input$profile_metric_type]]$metric_type_title - - # update map to change tooltip labels - leafletProxy("exploremap") %>% - map_dgo_axis(selected_axis = r_val$dgo_axis, region_axis = r_val$network_region_axis, - main_metric = r_val$selected_metric, second_metric = r_val$selected_profile_metric) - - # create the list to add trace and layout to change second axe plot - proxy_second_axe <- lg_profile_second(data = r_val$selected_axis_df, - y = r_val$selected_axis_df[[r_val$selected_profile_metric]], - y_label = r_val$selected_profile_metric_name, - y_label_category = r_val$selected_profile_metric_type) - - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 1) %>% - plotlyProxyInvoke("addTraces", proxy_second_axe$trace, 1) %>% - plotlyProxyInvoke("relayout", proxy_second_axe$layout) - } - }) - - #### profile metric remove axe #### - - observeEvent(input$remove_profile_axe, { - - # track input - track_inputs(input = input) - - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 1) - - updateRadioButtons(session, "profile_metric", selected = character(0)) - - r_val$selected_profile_metric = NULL - # update dgo on axis to reset tooltip - leafletProxy("exploremap") %>% - map_dgo_axis(selected_axis = r_val$dgo_axis, region_axis = r_val$network_region_axis, - main_metric = r_val$selected_metric, second_metric = r_val$selected_profile_metric) - - }) - - #### profile metric add ROE #### - - observeEvent(input$roe_profile, { - - # track input - track_inputs(input = input) - - if (input$roe_profile == TRUE){ - if (!is.null(r_val$roe_vertical_line)){ - # remove the previous ROE vertical lines if exist - r_val$leaflet_hover_shapes$shapes <- list(r_val$leaflet_hover_shapes$shapes[[1]]) - } - # create the vertical line from ROE distance_axis - r_val$roe_vertical_line <- lg_roe_vertical_line(r_val$roe_axis$distance_axis) - # increment the vertical list shape to keep the hover map vertical line - r_val$leaflet_hover_shapes$shapes <- c(r_val$leaflet_hover_shapes$shapes, - r_val$roe_vertical_line) - # update profile - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("relayout", r_val$leaflet_hover_shapes) - }else{ - # remove the previous ROE vertical lines if exist - r_val$leaflet_hover_shapes$shapes <- list(r_val$leaflet_hover_shapes$shapes[[1]]) - # update profile - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("relayout", r_val$leaflet_hover_shapes) - } - }) - - ### EVENT FILTER #### - - observeEvent(c(input$strahler, input$metricfilter, r_val$ui_strahler_filter), { - - # track input - track_inputs(input = input) - - if (is.null(input$metricfilter)){ - # build WMS cql_filter - r_val$cql_filter = paste0("gid_region=", r_val$selected_region_feature[["gid"]], - " AND strahler>=", input$strahler[1], - " AND strahler <= ", input$strahler[2]) - - r_val$sld_body = NULL - - } else { - # build WMS cql_filter - r_val$cql_filter = paste0("gid_region=",r_val$selected_region_feature[["gid"]], - " AND strahler>=",input$strahler[1], - " AND strahler <= ",input$strahler[2], - " AND ",r_val$selected_metric,">=",input$metricfilter[1], - " AND ",r_val$selected_metric,"<=",input$metricfilter[2]) - - # build SLD symbology - r_val$sld_body = sld_get_style( - breaks = sld_get_quantile_metric( - selected_region_id = r_val$region_click$id, - selected_metric = r_val$selected_metric, - con = con - ), - colors = sld_get_quantile_colors( - quantile_breaks = sld_get_quantile_metric( - selected_region_id = r_val$region_click$id, - selected_metric = r_val$selected_metric, - con = con - ) - ), - metric = r_val$selected_metric - ) - - # update legend - metric_legend(map_legend_metric(sld_body = r_val$sld_body)) - } - # update map with basic style - leafletProxy("exploremap") %>% - map_metric(wms_params = params_wms()$metric, - cql_filter = r_val$cql_filter, sld_body = r_val$sld_body, - data_axis = r_val$network_region_axis) - }) - - ### EVENT MOUSEOVER #### - - #### plotly profile #### - - # Define an observeEvent to capture hover events - observeEvent(event_data("plotly_hover"), { - if (!is.null(event_data("plotly_hover"))) { - hover_fid <- event_data("plotly_hover")$key[1] - highlighted_feature <- r_val$dgo_axis[r_val$dgo_axis$fid == hover_fid, ] - leafletProxy("exploremap") %>% - addPolylines(data = highlighted_feature, color = "red", weight = 10, - group = params_map_group()$light) - } - }) - - # clear previous point on map when moving along profile to not display all the point move over - observe({ - if (is.null(event_data("plotly_hover"))) { - leafletProxy("exploremap") %>% - clearGroup(params_map_group()$light) - } - }) - - #### leaflet map #### - - # add vertical line on profil on map user mouseover axis - observeEvent(input$exploremap_shape_mouseover, { - if (input$exploremap_shape_mouseover$group == params_map_group()$dgo_axis && !is.null(input$exploremap_shape_mouseover)){ - # extract dgo axis fid from map - r_val$leaflet_hover_measure <- r_val$dgo_axis %>% - filter(fid == input$exploremap_shape_mouseover$id) %>% - pull(measure) - # remove the first element (hover dgo vertical line) - r_val$leaflet_hover_shapes <- list(shapes = r_val$leaflet_hover_shapes$shapes[-1]) - # add the new hover dgo vertical line - r_val$leaflet_hover_shapes$shapes <- c(list(lg_vertical_line(r_val$leaflet_hover_measure)), r_val$leaflet_hover_shapes$shapes) - # change profile layout with vertical line - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("relayout", r_val$leaflet_hover_shapes) - } - }) - }) -} - - -## To be copied in the UI -# mod_explore_ui("explore_1") - -## To be copied in the server -# mod_explore_server("explore_1") diff --git a/R_old/mod_mapdo_app.R b/R_old/mod_mapdo_app.R deleted file mode 100644 index cbbe267..0000000 --- a/R_old/mod_mapdo_app.R +++ /dev/null @@ -1,507 +0,0 @@ - -# UI ---------------------------------------------------------------------- - - - -#' mapdo_app UI Function -#' -#' @description A shiny Module. -#' -#' @import shiny -#' @importFrom shinyjs useShinyjs -#' @importFrom shinycssloaders withSpinner -#' @importFrom bslib popover -#' @importFrom bsicons bs_icon -#' @importFrom leaflet leafletOutput -#' @importFrom htmltools HTML div img -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_mapdo_app_ui <- function(id){ - ns <- NS(id) - tagList( - golem_add_external_resources(), - fluidPage( - useShinyjs(), - tags$head( - tags$style( - HTML(" - .form-group{margin-bottom: 10px} - ") - ) - ), # head - fluidRow( - column( - width = 7, - withSpinner(leafletOutput(ns("map"), height = 500)), - textOutput(ns("selection_textUI")) - ), - column( - width = 5, - tabsetPanel( - id = ns("tabset"), - tabPanel("Classes proposées", - mod_classification_proposed_ui("classification_proposed_1") - ), - tabPanel("Classification manuelle", - mod_classification_manual_ui("classification_manual_1") - ), - tabPanel("Aperçu métriques", - mod_metric_overview_ui("metric_overview_1") - ), type = "pills" - ) #tabsetpanel - ) #column - ), #row - fluidRow( - style = "margin-top: 10px; - margin-bottom: 10px;", - tabsetPanel( - id = ns("tabset2"), - tabPanel( - "Évolution longitudinale", - mod_profil_long_ui("profil_long_1") - ), - tabPanel("Profil transversal", - mod_profil_transverse_ui("profil_transverse_1") - ), - tabPanel("Distribution des classes", - mod_classes_distribution_ui("classes_distribution_1") - ), type = "pills" - ) - ) - ) #page - - ) -} - - - -# SERVER ------------------------------------------------------------------ - - -#' mapdo_app Server Functions -#' -#' @import shiny -#' @importFrom leaflet leafletProxy clearGroup leafletOutput renderLeaflet removeControl addLegend addControl -#' @importFrom leaflet.extras addWMSLegend -#' @importFrom htmltools HTML div img -#' @importFrom dplyr filter mutate if_else pull -#' @importFrom plotly event_register event_data plotlyProxy plotlyProxyInvoke renderPlotly plotlyOutput -#' @importFrom bslib popover update_popover -#' @importFrom bsicons bs_icon -#' @importFrom sf st_write -#' @importFrom shinyjs onclick runjs -#' @noRd -mod_mapdo_app_server <- function(id, con, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - - ### INITIALIZATION #### - - #### Map #### - - output$map <- renderLeaflet({ - r_val$bassins = data_get_bassins(opacity = r_val$opacity, con = con) - map_init_bassins(bassins_data = r_val$bassins, - id_logo_ign_remonterletemps = ns("logo_ign_remonterletemps")) - }) - - onclick(id = "logo_ign_remonterletemps", expr = - runjs(sprintf("window.open('%s', '_blank')", - utils_url_remonterletemps(lng = input$map_center$lng, - lat = input$map_center$lat, - zoom = input$map_zoom))) - ) - - #### Description Text #### - - output$selection_textUI <- renderText({ - r_val$selection_text - }) - - observe({ - r_val$map_proxy <- leafletProxy("map") - }) - - ### TABSET LISTENERS #### - - # save current tabs in reactive values - - observeEvent(input$tabset, { - r_val$tab_open1 = input$tabset - }) - - observeEvent(input$tabset2, { - r_val$tab_open2 = input$tabset2 - }) - - ### EVENT MAP CLICK #### - - observeEvent(input$map_shape_click, { - - # track input - track_inputs(input = input) - - #### bassin clicked #### - if (input$map_shape_click$group == params_map_group()[["bassin"]]){ - - # get bassin name - r_val$bassin_name = r_val$bassins %>% - filter(cdbh == input$map_shape_click$id) %>% - pull(lbbh) - - # disable the click interactivity for the bassin selected - r_val$bassins = r_val$bassins %>% - mutate(click = if_else(display == TRUE, TRUE, click)) %>% - mutate(click = if_else(display == TRUE & cdbh == input$map_shape_click$id, FALSE, click)) - # get the regions data in selected bassin - r_val$regions_in_bassin = data_get_regions_in_bassin(selected_bassin_id = input$map_shape_click$id, - opacity = r_val$opacity, - con = con) - # update map : zoom in clicked bassin, clear bassin data, display region in bassin - leafletProxy("map") %>% - map_add_regions_in_bassin(bassin_click = input$map_shape_click, - regions_data = r_val$regions_in_bassin, - bassins_data = r_val$bassins) - # print name of basin below map - r_val$selection_text = paste0("Bassin: ", r_val$bassin_name) - } - - #### region clicked #### - if (input$map_shape_click$group == params_map_group()$region){ - - # register first selection of region - r_val$region_clicked = TRUE - - # set axis and dgo values back to NULL - r_val$network_region_classified = NULL - r_val$axis_name = NULL - r_val$axis_click = NULL - r_val$axis_clicked = FALSE - r_val$dgo_axis = NULL - r_val$axis_start_end = NULL - r_val$data_dgo_clicked = NULL - r_val$data_section = NULL - r_val$network_region_classified = NULL - r_val$dgo_axis_classified = NULL - r_val$merged_networks_classified = NULL - r_val$roe_region = NULL - - # store the region click values - r_val$region_click = input$map_shape_click - - # disable the click interactivity for the bassin selected - r_val$regions_in_bassin = r_val$regions_in_bassin %>% - mutate(click = if_else(display == TRUE, TRUE, click)) %>% - mutate(click = if_else(display == TRUE & gid == r_val$region_click$id, FALSE, click)) - - # save the selected region feature for mapping - r_val$selected_region_feature = data_get_region(region_click_id = r_val$region_click$id, - con = con) - - # get network of region - r_val$network_region = data_get_network_region(selected_region_id = r_val$region_click$id, - con = con) - - # set region name to download - r_val$region_name = utils_normalize_string(r_val$selected_region_feature$lbregionhy) - - # get the axis in the region - r_val$network_region_axis = data_get_axis(selected_region_id = r_val$region_click$id, - con = con) - # get ROE in region - r_val$roe_region = data_get_roe_in_region(r_val$region_click$id, - con = con) - - # get hydro sites in region - r_val$hydro_sites_region = data_get_hydro_sites(r_val$region_click$id, - con = con) - - # build SLD symbology - r_val$sld_body = sld_get_style( - breaks = sld_get_quantile_metric( - selected_region_id = r_val$region_click$id, - selected_metric = r_val$selected_metric, - con = con - ), - colors = sld_get_quantile_colors( - quantile_breaks = sld_get_quantile_metric( - selected_region_id = r_val$region_click$id, - selected_metric = r_val$selected_metric, - con = con - ) - ), - metric = r_val$selected_metric - ) - - # map region clicked with region clicked and overlayers and initial network with strahler-order - r_val$map_proxy %>% - map_region_clicked(region_click = input$map_shape_click, - selected_region_feature = r_val$selected_region_feature, - regions_data = r_val$regions_in_bassin, - roe_region = r_val$roe_region, - hydro_sites_region = r_val$hydro_sites_region) - - # add strahler-order network visualization to map when classes visualisation is selected (and not manual) - # if ((r_val$visualization == "classes") && is.null(r_val$classes_proposed_selected)) { - # r_val$map_proxy %>% - # map_class(wms_params = params_wms()$class, - # cql_filter = paste0("gid_region!=",r_val$selected_region_feature[["gid"]]), - # style = "mapdo:", - # data_axis = r_val$network_region_axis) - # } - # map_metric(wms_params = params_wms()$metric, - # cql_filter = paste0("gid_region=",r_val$selected_region_feature[["gid"]]), - # sld_body = r_val$sld_body, - # data_axis = r_val$network_region_axis) %>% - # addWMSLegend(uri = map_legend_metric(sld_body = r_val$sld_body), - # position = "bottomright", - # layerId = "legend_metric") - # addControl( - # html = HTML(paste0('
- #
Legend Title
- #
- # Legend - #
- #
- # ')), - # position = "bottomright" - # ) - - # addControl( - # html = paste0('
- #

Legend Title

- # Legend - #
'), - # position = "bottomright" - # ) - # addControl( - # html = "Custom Legend Title", - # position = "bottomright", - # className = "legend-title" - # ) - - - - - # print name of basin and region below map - r_val$selection_text = paste0("Bassin: ", r_val$bassin_name, - ", région: ", r_val$selected_region_feature$lbregionhy) - } - - #### axis clicked #### - - if (input$map_shape_click$group == params_map_group()$axis) { - - # set values back to NULL - r_val$data_dgo_clicked = NULL - r_val$data_section = NULL - r_val$dgo_axis_classified = NULL - r_val$merged_networks_classified = NULL - r_val$leaflet_hover_measure = NULL - r_val$roe_axis = NULL - r_val$dgo_axis = NULL - - # save the clicked axis values - r_val$axis_click = input$map_shape_click - - # reget the axis in the region without the selected axis - r_val$network_region_axis = data_get_axis(selected_region_id = r_val$region_click$id, - con = con) %>% - filter(axis != r_val$axis_click$id) - - # get the DGO axis data - r_val$dgo_axis = data_get_network_axis(selected_axis_id = r_val$axis_click$id, - con = con) %>% - mutate(measure = measure/1000) - - # get axis name - r_val$axis_name = r_val$dgo_axis$toponyme[1] - - # extract axis start end point - r_val$axis_start_end = data_get_axis_start_end(dgo_axis = r_val$dgo_axis) - - # get ROE in axis clicked - r_val$roe_axis = r_val$roe_region %>% - filter(axis == r_val$axis_click$id) - - # map dgo axis when axis clicked and metric selected - r_val$map_proxy %>% - map_dgo_axis(selected_axis = r_val$dgo_axis, region_axis = r_val$network_region_axis, - main_metric = r_val$selected_metric, second_metric = r_val$selected_profile_metric) %>% - map_axis_start_end(axis_start_end = r_val$axis_start_end, region_axis = r_val$network_region_axis) - - # print name of basin and region below map - r_val$selection_text = paste0("Bassin: ", r_val$bassin_name, - ", région: ", r_val$selected_region_feature$lbregionhy, - ", axe: ", r_val$axis_name) - - # create or update profile dataset with new axis - r_val$selected_axis_df = r_val$dgo_axis %>% - as.data.frame() - - # inform the first axis has been clicked - r_val$axis_clicked = TRUE - } - - #### dgo clicked #### - - if (input$map_shape_click$group == params_map_group()$dgo_axis) { - # get data with dgo id - r_val$data_section = data_get_elevation_profiles(selected_dgo_fid = input$map_shape_click$id, - con = con) - - # get dgo clicked feature - r_val$data_dgo_clicked = r_val$dgo_axis %>% - filter(fid == input$map_shape_click$id) - - # Highlight clicked DGO - r_val$map_proxy %>% - map_dgo_cross_section(selected_dgo = r_val$data_dgo_clicked) - } - }) - - #### DGO Mouseover #### - - # check for hover over dgo event - observeEvent(input$map_shape_mouseover, { - if (input$map_shape_mouseover$group == params_map_group()$dgo_axis && !is.null(input$map_shape_mouseover)){ - - # extract dgo axis fid from map - r_val$leaflet_hover_measure = r_val$dgo_axis %>% - filter(fid == input$map_shape_mouseover$id) %>% - pull(measure) - } else { - r_val$leaflet_hover_measure = NULL - } - }) - - #### EVENT legend update #### - - observeEvent(input$map_groups, { - - # landuse map - if (any(input$map_groups %in% params_map_group()$landuse)) { - leafletProxy("map") %>% - addWMSLegend(map_legend_wms_overlayer(wms_params = params_wms()$landuse), - position = "bottomleft", - layerId = "landuse") - } else { - leafletProxy("map") %>% - removeControl(layerId = "landuse") - } - - # lateral continuity map - if (any(input$map_groups %in% params_map_group()$continuity)) { - leafletProxy("map") %>% - addWMSLegend(map_legend_wms_overlayer(wms_params = params_wms()$continuity), - position = "bottomleft", - layerId = "continuity") - } else { - leafletProxy("map") %>% - removeControl(layerId = "continuity") - } - - # valley bottom map - if (any(input$map_groups %in% params_map_group()$valley_bottom)) { - leafletProxy("map") %>% - addWMSLegend(map_legend_wms_overlayer(wms_params = params_wms()$valley_bottom), - position = "bottomleft", - layerId = "valley_bottom") - } else { - leafletProxy("map") %>% - removeControl(layerId = "valley_bottom") - } - - # zone inondable map - if (any(input$map_groups %in% params_map_group()$inondation)) { - leafletProxy("map") %>% - addWMSLegend(map_legend_wms_overlayer(wms_params = params_wms()$inondation), - position = "bottomleft", - layerId = "inondation") - } else { - leafletProxy("map") %>% - removeControl(layerId = "inondation") - } - - # ouvrage de protection map - if (any(input$map_groups %in% params_map_group()[["ouvrage_protection"]])) { - leafletProxy("map") %>% - addWMSLegend(map_legend_wms_overlayer(wms_params = params_wms()$ouvrage_protection), - position = "bottomleft", - layerId = "ouvrage_protection") - } else { - leafletProxy("map") %>% - removeControl(layerId = "ouvrage_protection") - } - - # Custom legend HTML - custom_legend <- - - # ROE - if (any(input$map_groups %in% params_map_group()[["roe"]])) { - leafletProxy("map") %>% - addControl( - HTML(" -
-
-
Obstacles à l'Ecoulement (ROE)
-
"), - position = "bottomleft", layerId = "roe" - ) - # addLegend( - # position = "bottomright", - # colors = "#323232", - # labels = "Obstacles à l'Ecoulement (ROE)", - # layerId = "roe" - # ) - } else { - leafletProxy("map") %>% - removeControl(layerId = "roe") - } - - # Site hydrométrique - if (any(input$map_groups %in% params_map_group()[["hydro_sites"]])) { - leafletProxy("map") %>% - addControl( - HTML(" -
-
-
Sites hydrométriques
-
"), - position = "bottomleft", layerId = "hydro_sites" - ) - # addLegend( - # position = "bottomright", - # colors = "#33B1FF", - # labels = "Obstacles à l'Ecoulement (ROE)", - # layerId = "hydro_sites" - # ) - } else { - leafletProxy("map") %>% - removeControl(layerId = "hydro_sites") - } - - # Site hydrométrique - # if (any(input$map_groups %in% params_map_group()[["hydro_sites"]])) { - # map_legend_vector_overlayer(layer_label = "Site hydrométrique", - # color = "#33B1FF") - # } - }) - - - }) -} diff --git a/R_old/mod_metric_overview.R b/R_old/mod_metric_overview.R deleted file mode 100644 index a7bd06d..0000000 --- a/R_old/mod_metric_overview.R +++ /dev/null @@ -1,158 +0,0 @@ -#' metric_overview UI Function -#' -#' @description A shiny Module. -#' -#' @import shiny -#' @importFrom shinyjs useShinyjs -#' @importFrom reactable reactableOutput -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_metric_overview_ui <- function(id){ - ns <- NS(id) - tagList( - useShinyjs(), - tags$style(HTML(" - .reactable-table { - font-size: 15px; /* Adjust this value to change the text size */ - } - ")), - fluidRow(style = "margin-top: 10px;", - textOutput(ns("placeholder_ui")), - column(width = 6, - uiOutput(ns("description"))), - column(width = 6, - uiOutput(ns("selectinput"))) - ), - fluidRow( - div(class = "reactable-table", - reactableOutput(ns("table"), width = "100%") - ) - ) - ) -} - -#' metric_overview Server Functions -#' -#' @import shiny -#' @import dplyr -#' @importFrom reactable renderReactable -#' @importFrom sf st_drop_geometry -#' @importFrom tidyr pivot_longer -#' -#' @noRd -mod_metric_overview_server <- function(id, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - r_val_local <- reactiveValues( - characteristics_table = NULL, # reactable table - descriptionUI = NULL, # Description/Title text - placeholder_text = "Cliquez sur un région hydrographique pour afficher la comparaison régionale des métriques. ", - selectinputUI = NULL, # select input for unit - unit = NULL, # unit for metrics - - region_pivot = NULL, # pivoted df of region as input for data_df - axis_pivot = NULL, # pivoted df of region as input for data_df - dgo_pivot = NULL, # pivoted df of dgo as input for data_df - data_df = NULL # df to create table - ) - - output$table <- renderReactable( - r_val_local$characteristics_table - ) - - output$description <- renderUI( - r_val_local$descriptionUI - ) - - # text placeholder - output$placeholder_ui <- renderText({ - r_val_local$placeholder_text - }) - - output$selectinput <- renderUI( - r_val_local$selectinputUI - ) - - # observe if region clicked to create UI - observe({ - if (r_val$region_clicked == TRUE) { - # remove placeholder text - r_val_local$placeholder_text = NULL - - # create header - r_val_local$descriptionUI = HTML("

Comparaison de moyennes

") - - # create metric-select input - r_val_local$selectinputUI = selectInput(ns("select_unit"), label = NULL, - choices = list("surface relative (%)", "surface absolute (ha)")) - } - }) - - # create pivoted df for axis each time it changes - observeEvent(c(r_val$network_region, r_val$tab_open1), { - if (!is.null(r_val$network_region) && (r_val$tab_open1 == "Aperçu métriques")) { - - r_val_local$region_pivot <- fct_table_pivot_sf(r_val$network_region) %>% - dplyr::rename(mean_region = mean, distr_region = distr) - - # set axis and dgo to NULL - r_val_local$axis_pivot = NULL - r_val_local$dgo_pivot = NULL - } - }) - - # create pivoted df for axis each time it changes - observeEvent(c(r_val$dgo_axis, r_val$tab_open1), { - if (!is.null(r_val$dgo_axis) && (r_val$tab_open1 == "Aperçu métriques")) { - - r_val_local$axis_pivot <- fct_table_pivot_sf(r_val$dgo_axis) %>% - dplyr::rename(mean_axis = mean, distr_axis = distr) - - # set dgo_pivot to NULL - r_val_local$dgo_pivot = NULL - } - }) - - # create pivoted df for dgo each time it changes - observeEvent(c(r_val$data_dgo_clicked, r_val$tab_open1), { - if (!is.null(r_val$data_dgo_clicked) && (r_val$tab_open1 == "Aperçu métriques")) { - # dgo data - r_val_local$dgo_pivot <- r_val$data_dgo_clicked %>% - sf::st_drop_geometry() %>% - dplyr::select(-c(fid, axis, measure, toponyme, strahler, gid_region)) %>% - tidyr::pivot_longer(-c(), names_to = "metric_name", values_to = "segment") %>% - dplyr::mutate(segment = round(segment, 2)) - } - }) - - # check for changes in unit, or regional and axis network or selected dgo to create the df as basis for table - observeEvent(c(r_val_local$region_pivot, r_val_local$axis_pivot, r_val_local$dgo_pivot), { - - if (!is.null(r_val_local$region_pivot)) { - # create data for table - r_val_local$data_df <- fct_table_create_table_df(region_pivot = r_val_local$region_pivot, - axis_pivot = r_val_local$axis_pivot, - dgo_pivot = r_val_local$dgo_pivot) - } - }) - - # create new table each time when df changed - observeEvent(c(r_val_local$data_df, input$select_unit),{ - - if (!is.null(r_val_local$data_df) & !is.null(input$select_unit)){ - # check which surface unit should be used for metrics - if (input$select_unit == "surface relative (%)") { - r_val_local$characteristics_table <- fct_table_create_reactable(r_val_local$data_df, "%") - } else { - r_val_local$characteristics_table <- fct_table_create_reactable(r_val_local$data_df, "ha") - } - } - - }) - }) -} diff --git a/R_old/mod_profil_long.R b/R_old/mod_profil_long.R deleted file mode 100644 index 2354642..0000000 --- a/R_old/mod_profil_long.R +++ /dev/null @@ -1,424 +0,0 @@ - - -# UI ---------------------------------------------------------------------- - -#' profil_long UI Function -#' -#' @description A shiny Module. -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_profil_long_ui <- function(id){ - ns <- NS(id) - tagList( - useShinyjs(), - div( - fluidRow( - style = "margin-top: 10px;", - column(width = 10, - plotlyOutput(ns("long_profile")) - ), - column( - width = 2, - style = "margin-top: 20px;", - uiOutput(ns("profile_first_metricUI")), - uiOutput(ns("add_sec_axeUI"), - style = "margin-top: 30px;"), - uiOutput(ns("profile_sec_metricUI"), - style = "margin-left : 23px; margin-top: 10px"), - uiOutput(ns("profileroeUI")), - uiOutput(ns("profile_backgroundUI")) - ) - ) - ) - ) -} - - -# Server ------------------------------------------------------------------ - -#' profil_long Server Functions -#' -#' @importFrom dplyr filter pull -#' @importFrom plotly event_register plotlyOutput renderPlotly event_data -#' @importFrom leaflet addPolylines clearGroup -#' -#' @noRd -mod_profil_long_server <- function(id, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - ### INITIALIZATION #### - - #### REACTIVES #### - r_val_local <- reactiveValues( - plot = lg_profile_empty(), # plotly render longitudinal profile output (default empty) - leaflet_hover_shapes = NULL, # list to store vertical lines to display on longitudinal profile - ui_roe_profile = NULL, # UI placeholder for ROE checkbox - ui_background_profile = NULL, # UI placeholder for background classes checkbox - roe_vertical_line = NULL, # list with verticale line to plot on longitudinal profile - - # first metric - profile_first_metric = NULL, - - selected_profile_metric_title = NULL, # metric title to be displayed instead of pure variable name - selected_profile_metric_type = NULL, # metric type title - - # second metric - proxy_second_axe = NULL, - profile_sec_metric = NULL, # second metric selection - add_sec_axe = NULL, # add second axis - sec_metric_name = NULL, # title - sec_metric_type = NULL, # metric type title - - # plotly shapes - shapes_dgo = NULL, # list with shapes to plot clicked dgo element as line - shapes_roe = NULL, # list with shapes to plot ROE obstacles as lines - shapes_background = NULL, # list with shapes to plot classes in background - - ) - - #### OUTPUTS #### - output$long_profile <- renderPlotly({ - return(r_val_local$plot) - }) - - # selectinput for metric - output$profile_first_metricUI <- renderUI({ - if (!is.null(r_val_local$profile_first_metric)) { - div( - style = "display: flex; align-items: center", - r_val_local$profile_first_metric, - span( - style = "display: flex; margin-left: 10px; margin-top: 20px", - popover( - trigger = bsicons::bs_icon("info-circle"), - "", - placement = "right", - id = ns("popover_metric") - ) - ) - ) - } - }) - - # add selectinput for additional metric - output$profile_sec_metricUI <- renderUI({ - - if (!is.null(r_val_local$profile_sec_metric)) { - div( - style = "display: flex; align-items: center", - r_val_local$profile_sec_metric, - span( - style = "margin-left: 10px; margin-top: -10px", - popover( - trigger = bsicons::bs_icon("info-circle"), - "", - placement = "right", - id = ns("popover_metric2") - ) - ) - ) - } - }) - - # button to add second axe - output$add_sec_axeUI <- renderUI({ - r_val_local$add_sec_axe - }) - - # checkbox display ROE - output$profileroeUI <- renderUI({ - r_val_local$ui_roe_profile - }) - - # checkbox display background based on classification - output$profile_backgroundUI <- renderUI({ - r_val_local$ui_background_profile - }) - - - # make plot available to other - observe({ - r_val$plot_long_proxy <- plotlyProxy("long_profile") - }) - - #### axis select #### - - observeEvent(r_val$axis_clicked, { - - # track input - track_inputs(input = input) - - if (!is.null(r_val$dgo_axis) & (r_val$axis_clicked == TRUE)) { - - # build second axis input and add and remove buttons - r_val_local$profile_first_metric = selectInput(ns("profile_first_metric"), label = "Métrique :", - choices = params_get_metric_choices(), - selected = params_get_metric_choices()[1]) - } - }) - - #### build longitudinal profile plot #### - observeEvent(c(input$profile_first_metric, r_val$dgo_axis), { - - if (!is.null(input$profile_first_metric) & !is.null(r_val$dgo_axis)) { - r_val_local$plot <- - lg_profile_main( - data = r_val$dgo_axis, - y = r_val$dgo_axis[[input$profile_first_metric]], - y_label = metrics_params[metrics_params$metric_name == input$profile_first_metric,]$metric_title, - y_label_category = metrics_params[metrics_params$metric_name == input$profile_first_metric,]$metric_type_title - ) %>% - event_register("plotly_hover") - - # build second axis input and add and remove buttons - r_val_local$add_sec_axe = checkboxInput(ns("sec_axis"), - label = "Ajoutez 2éme métrique :", - value = FALSE) - r_val_local$profile_sec_metric = selectInput(ns("profile_sec_metric"), label = NULL, - choices = params_get_metric_choices(), - selected = params_get_metric_choices()[[2]][1], - width = "100%") - - # build ROE checkboxInput - r_val_local$ui_roe_profile = NULL # delete checkbox before creating new one - r_val_local$ui_roe_profile = checkboxInput(ns("roe_profile"), - label = "Obstacles à l'Ecoulement", - value = FALSE) - - # build background classification checkboxInput - r_val_local$ui_background_profile = NULL # delete checkbox before creating new one - r_val_local$ui_background_profile = checkboxInput(ns("background_profile"), - label = "Classifications en arrière-plan", - value = FALSE) - } else { - r_val_local$plot = lg_profile_empty() - } - }) - - - #### add or remove second axis #### - - observeEvent(c(input$sec_axis, input$profile_sec_metric), { - - # track input - track_inputs(input = input) - - # add second axis - if (input$sec_axis == TRUE) { - # get metric title and type - r_val_local$sec_metric_name = - metrics_params |> filter(metric_name == input$profile_sec_metric) |> pull(metric_title) - r_val_local$sec_metric_type = - metrics_params |> filter(metric_name == input$profile_sec_metric) |> pull(metric_type_title) - - # create the list to add trace and layout to change second axe plot - r_val_local$proxy_second_axe <- lg_profile_second(data = r_val$dgo_axis, - y = r_val$dgo_axis[[input$profile_sec_metric]], - y_label = r_val_local$sec_metric_name, - y_label_category = r_val_local$sec_metric_type) - # add second metric to plot - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 1) %>% - plotlyProxyInvoke("addTraces", r_val_local$proxy_second_axe$trace, 1) %>% - plotlyProxyInvoke("relayout", r_val_local$proxy_second_axe$layout) - } - # remove second axis - else { - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("deleteTraces", 1) - - r_val_local$proxy_second_axe = NULL - } - }) - - ### SHAPES Plotly #### - - #### clicked dgo #### - - observe({ - - if (!is.null(r_val$data_dgo_clicked)) { - # remove the previous element - r_val_local$shapes_dgo = NULL - - # get new shapes-element for longitudinal plot marker of clicked dgo for - r_val_local$shapes_dgo <- list(lg_vertical_line(r_val$data_dgo_clicked %>% pull(measure))) - } else if (is.null(r_val$data_dgo_clicked)) { - r_val_local$shapes_dgo = NULL - } - }) - - #### ROE #### - - observeEvent(input$roe_profile, { - - if (input$roe_profile == TRUE) { - # create the vertical line from ROE distance_axis - r_val_local$shapes_roe = lg_roe_vertical_line(r_val$roe_axis$distance_axis) - - } else { - # remove the previous ROE vertical lines if exist - r_val_local$shapes_roe = NULL - } - }) - - #### background classification #### - - observeEvent(c(input$background_profile, r_val$classes_proposed_selected, - r_val$manual_classes_table), { - - # track input - track_inputs(input = input) - - if (!is.null(input$background_profile) && !is.null(r_val$dgo_axis)) { - - # add background classification shapes - if (input$background_profile == TRUE) { - - # proposed classification applied - if (r_val$visualization == "classes") { - r_val$dgo_axis_classified = r_val$dgo_axis %>% - assign_classes_proposed(proposed_class = classes_proposed[r_val$classes_proposed_selected,]$class_name) - } - - # manual classification applied - else if (r_val$visualization == "manual" & - !is.null(r_val$manual_classes_table)) { - r_val$dgo_axis_classified <- r_val$dgo_axis %>% - na.omit() %>% - assign_classes_manual(classes = r_val$manual_classes_table) - } - - if (!is.null(r_val$dgo_axis_classified)) { - r_val_local$shapes_background = create_classes_background(r_val$dgo_axis_classified) - } - - } - # remove background classification - else if (input$background_profile == FALSE) { - r_val_local$shapes_background = NULL - } - } - }) - - #### COMBINE shapes #### - - # reactive that listens to all changes in shapes and returns a combined list of them - combined_shapes <- reactive({ - - # create always new an empty list to store only shapes which are really activated - shapes_list <- list() - - if (!is.null(r_val_local$shapes_dgo)) { - shapes_list <- c(shapes_list, r_val_local$shapes_dgo) - } - - if (!is.null(r_val_local$shapes_roe)) { - shapes_list <- c(shapes_list, r_val_local$shapes_roe) - } - - if (!is.null(r_val_local$shapes_background)) { - shapes_list <- c(shapes_list, r_val_local$shapes_background) - } - - if (!is.null(r_val_local$leaflet_hover_shapes)) { - shapes_list <- c(shapes_list, r_val_local$leaflet_hover_shapes) - } - - shapes_list - - }) - - # observe the combined shapes and update the plotly plot - observe({ - - if (!is.null(combined_shapes())) { - - shapes <- combined_shapes() - - # update profile with changed shapes - plotlyProxy("long_profile") %>% - plotlyProxyInvoke("relayout", list(shapes = shapes)) - } - }) - - - ### METRIC INFO #### - - # update infobutton when metric selected changes for the first and second metric - observe({ - if (!is.null(input$profile_first_metric)) { - update_popover("popover_metric", - HTML(metrics_params %>% - filter(metric_name == input$profile_first_metric) %>% - pull(metric_description))) - } - }) - - observe({ - if (!is.null(input$profile_sec_metric)) { - update_popover("popover_metric2", - HTML(metrics_params %>% - filter(metric_name == input$profile_sec_metric) %>% - pull(metric_description))) - } - }) - - - ### HOVER EVENTS #### - - #### plotly profile #### - - # capture hover events on profile-plot to display dgo on map - observeEvent(event_data("plotly_hover", source = 'L'), { - - if(!is.null(r_val_local$plot)) { - # event data - hover_event <- event_data("plotly_hover", source = 'L') - - # add line to map and plot - if (!is.null(hover_event)) { - hover_fid <- hover_event$key[1] - highlighted_feature <- r_val$dgo_axis[r_val$dgo_axis$fid == hover_fid, ] - r_val$map_proxy %>% - addPolylines(data = highlighted_feature, color = "red", weight = 10, - group = params_map_group()$light) - } - } - - }) - - # clear previous point on map when moving along profile to not display all the point move over - observe({ - if (!is.null(r_val_local$plot)) { - if (is.null(event_data("plotly_hover", source = 'L'))) { - r_val$map_proxy %>% - clearGroup(params_map_group()$light) - } - } - }) - - - #### leaflet map dgo mouseover #### - - observe({ - - if (!is.null(r_val$leaflet_hover_measure)) { - if (!is.null(r_val_local$plot)) { - # remove the first element (hover dgo vertical line) - r_val_local$leaflet_hover_shapes = NULL - # add the new hover dgo vertical line - r_val_local$leaflet_hover_shapes = list(lg_vertical_line(r_val$leaflet_hover_measure, color = "red")) - } - } else if (is.null(r_val$leaflet_hover_measure)) { - r_val_local$leaflet_hover_shapes = NULL - } - - }) - }) -} diff --git a/R_old/mod_profil_transverse.R b/R_old/mod_profil_transverse.R deleted file mode 100644 index 9d8490d..0000000 --- a/R_old/mod_profil_transverse.R +++ /dev/null @@ -1,55 +0,0 @@ -#' profil_transverse UI Function -#' -#' @description A shiny Module. -#' -#' @param id,input,output,session Internal parameters for {shiny}. -#' -#' @noRd -#' -#' @importFrom shiny NS tagList -mod_profil_transverse_ui <- function(id){ - ns <- NS(id) - tagList( - fluidRow( - style = "margin-top: 10px;", - column(width = 12, - plotlyOutput(ns("cross_section")) - ) - ) - ) -} - -#' profil_transverse Server Functions -#' -#' @noRd -mod_profil_transverse_server <- function(id, r_val){ - moduleServer( id, function(input, output, session){ - ns <- session$ns - - r_val_locals <- reactiveValues( - section = cr_profile_empty() # plotly render cross section output (default empty) - ) - - # output - output$cross_section <- renderPlotly({ - return(r_val_locals$section) - }) - - # plot cross section when dgo clicked - observe({ - - if (!is.null(r_val$data_section)) { - r_val_locals$section = cr_profile_main(data = r_val$data_section, - axis_toponyme = unique(r_val$selected_axis_df$toponyme)) - } else if (is.null(r_val$data_section)){ - r_val_locals$section = cr_profile_empty() - } - }) - }) -} - -## To be copied in the UI -# mod_profil_transverse_ui("profil_transverse_1") - -## To be copied in the server -# mod_profil_transverse_server("profil_transverse_1") diff --git a/R_old/run_app.R b/R_old/run_app.R deleted file mode 100644 index 5d60ac1..0000000 --- a/R_old/run_app.R +++ /dev/null @@ -1,28 +0,0 @@ -#' Run the Shiny Application -#' -#' @param ... arguments to pass to golem_opts. -#' See `?golem::get_golem_options` for more details. -#' @inheritParams shiny::shinyApp -#' -#' @export -#' @importFrom shiny shinyApp -#' @importFrom golem with_golem_options -run_app <- function( - onStart = NULL, - options = list(), - enableBookmarking = NULL, - uiPattern = "/", - ... -) { - with_golem_options( - app = shinyApp( - ui = app_ui, - server = app_server, - onStart = onStart, - options = options, - enableBookmarking = enableBookmarking, - uiPattern = uiPattern - ), - golem_opts = list(...) - ) -} diff --git a/R_old/utils-pipe.R b/R_old/utils-pipe.R deleted file mode 100644 index fd0b1d1..0000000 --- a/R_old/utils-pipe.R +++ /dev/null @@ -1,14 +0,0 @@ -#' Pipe operator -#' -#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details. -#' -#' @name %>% -#' @rdname pipe -#' @keywords internal -#' @export -#' @importFrom magrittr %>% -#' @usage lhs \%>\% rhs -#' @param lhs A value or the magrittr placeholder. -#' @param rhs A function call using the magrittr semantics. -#' @return The result of calling `rhs(lhs)`. -NULL