## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----eval=FALSE---------------------------------------------------------------
# # install.packages("devtools")
# devtools::install_github("sachit27/greenR", dependencies = TRUE)

## ----eval = FALSE-------------------------------------------------------------
# library(greenR)
# data <- get_osm_data("City of London, United Kingdom")

## ----eval = FALSE-------------------------------------------------------------
# green_areas_data <- data$green_areas
# visualize_green_spaces(green_areas_data)
# green_space_clustering(green_areas_data, num_clusters = 3)

## ----eval = FALSE-------------------------------------------------------------
# mapbox_token <- "your_mapbox_access_token_here"
# accessibility_mapbox(green_areas_data, mapbox_token)

## ----eval = FALSE-------------------------------------------------------------
# accessibility_greenspace(green_areas_data, 47.56427527336772, 7.595820936462059)
# map <- nearest_greenspace(data$highways, data$green_areas, 51.4761, -0.2008)

## ----eval = FALSE-------------------------------------------------------------
# print(map)  # Displays the interactive map

## ----eval = FALSE-------------------------------------------------------------
# # Example: Analyze accessibility in the City of London using walking network
# library(greenR)
# library(terra) # For raster population, if used
# 
# # Download OSM data
# data <- get_osm_data("City of London, United Kingdom")
# 
# # Run accessibility analysis for walking
# result <- analyze_green_accessibility(
#   network_data = data$highways$osm_lines,
#   green_areas = data$green_areas$osm_polygons,
#   mode = "walking",
#   grid_size = 300 # meters (change as needed)
#   # population_raster = my_pop_raster # Optional: a terra::SpatRaster layer
# )
# 
# # The result is a list with grid-level accessibility and summary stats.
# str(result)

## ----eval = FALSE-------------------------------------------------------------
# # Generate visualizations (static plots, radar plot, interactive Leaflet)
# viz <- create_accessibility_visualizations(
#   accessibility_analysis = result,
#   green_areas = data$green_areas$osm_polygons,
#   mode = "walking"
# )
# 
# # Publication-ready distance map
# print(viz$distance_map)
# 
# # Barplot: spatial and population-weighted coverage within thresholds
# print(viz$coverage_plot)
# 
# # Radar plot: directional accessibility (labels inside the axis)
# print(viz$directional_plot)
# 
# # Combined plot (distance, coverage, radar)
# print(viz$combined_plot)
# 
# # Interactive map (can be viewed in RStudio Viewer)
# viz$leaflet_map
# 
# # Summary stats as text
# cat(viz$summary)
# 
# # Directional table for further analysis
# print(viz$directional_table)

## ----eval = FALSE-------------------------------------------------------------
# 
# tryCatch({
#   green_index <- calculate_green_index(data, 4326, 100)
#   print(head(green_index))
# }, error = function(e) {
#   message("Note: Green index calculation was skipped in this vignette build.")
#   message("This function requires the DuckDB spatial extension, which may not be available in all environments.")
#   # Create a dummy green_index object for demonstration purposes
#   green_index <- data.frame(
#     osm_id = 1:5,
#     green_index = runif(5),
#     geometry = rep("LINESTRING(0 0, 1 1)", 5)
#   )
#   green_index <- sf::st_as_sf(green_index, wkt = "geometry", crs = 4326)
#   print(head(green_index))
# })
# 
# 
# # 8. Create the green index plot
# 
# This function visualizes the green index on a map, with options for both static and interactive display. Interactive maps are rendered using Leaflet, allowing users to zoom, pan, and interact with the map to explore the green index in more detail.
# 
# -   Dynamic Mapping: Create interactive, dynamic maps for a more engaging and detailed visualization.
# -   Customization: Modify color palette, text size, resolution, title, axis labels, legend position, line width, and line type to suit your preferences.
# 

## ----eval = FALSE-------------------------------------------------------------
# # Create a static plot
# map <- plot_green_index(green_index)
# 
# # Customize static plot
# map <- plot_green_index(green_index, colors = c("#FF0000", "#00FF00"), line_width = 1, line_type = "dashed")
# 
# # Create an interactive plot using Leaflet
# map <- plot_green_index(green_index, interactive = TRUE, base_map = "CartoDB.DarkMatter")
# 
# # Use a light-themed base map
# map <- plot_green_index(green_index, interactive = TRUE, base_map = "CartoDB.Positron")
# 

## ----eval = FALSE-------------------------------------------------------------
# print(map) #to view the map in the console. You can use htmlwidgets to save the html

## ----eval = FALSE-------------------------------------------------------------
# mapbox_token <- "your_mapbox_access_token_here"
# 
# create_linestring_3D(green_index, "green_index", mapbox_token)

## ----eval = FALSE-------------------------------------------------------------
# mapbox_token <- "your_mapbox_access_token_here"
# 
# # Create a temporary file
# temp_file <- tempfile(fileext = ".html")
# 
# # Create the 3D hexagon map
# create_hexmap_3D(
#   data = green_index,
#   value_col = "green_index",
#   mapbox_token = mapbox_token,
#   output_file = temp_file,
#   color_palette = "interpolateViridis"
# )
# 
# # Remove the temporary file
# unlink(temp_file)

## ----eval = FALSE-------------------------------------------------------------
# percentage <- calculate_percentage(green_index)

## ----eval = FALSE-------------------------------------------------------------
# download_file <- save_json(green_index, "File_Path") #file path has to be specified. For example "/Users/.../map.geojson"
# map <- save_as_leaflet(green_index, "File_Path")

## ----eval = FALSE-------------------------------------------------------------
# # Example: Analyze green area polygon density
# osm_data <- get_osm_data("City of London, United Kingdom")
# 
# result <- analyze_green_and_tree_count_density(
#   osm_data = osm_data,
#   mode = "green_area",      # or "tree_density"
#   h3_res = 8,               # H3 resolution (smaller is coarser)
#   color_palette = c("#FFEDA0", "#74C476", "#005A32"),
#   save_lorenz = TRUE
# )
# 
# # Interactive Leaflet map (colored by density bins)
# result$map
# 
# # Print analytics (mean, median, skewness, Gini, count per km2, etc)
# print(result$analytics)
# 
# # (Optional) Lorenz curve PNG path
# result$lorenz_plot

## ----eval = FALSE-------------------------------------------------------------
# # Example: Analyze canopy height in Zurich using bounding box
# res_bbox <- chm_analysis(
#   bbox = c(8.51, 47.36, 8.56, 47.40),
#   output_dir = tempdir(),
#   max_tiles = 2,
#   create_plots = TRUE
# )
# print(res_bbox$stats)
# 
# # Example: Use a location name (automatic geocoding)
# res_loc <- chm_analysis(
#   location = "Parc La Grange, Geneva, Switzerland",
#   output_dir = tempdir(),
#   max_tiles = 2
# )
# print(res_loc$stats)
# 
# # Example: Use your own canopy height raster
# res_tif <- chm_analysis(
#   chm_tif = "my_canopy.tif",
#   output_dir = tempdir(),
#   create_plots = TRUE,
#   height_threshold = 3
# )
# print(res_tif$stats)

## ----eval = FALSE-------------------------------------------------------------
# # Basic UHI analysis for a city
# result <- analyze_and_visualize_uhi(
#   location = "Basel, Switzerland",
#   date_range = c("2023-06-01", "2023-08-31"),
#   hex_resolution = 10,
#   thermal_source = "auto"  # Tries ECOSTRESS first, then Landsat
# )
# 
# # View the interactive map (opens in browser/viewer)
# result$maps$interactive
# 
# # View static publication-ready maps
# print(result$maps$combined)  # Combined 4-panel map
# print(result$maps$scatter)   # Scatter plot dashboard
# 
# # Access statistics
# print(result$stats$descriptive)
# print(result$stats$correlations)
# 
# # Check metadata
# print(result$meta)

## ----eval = FALSE-------------------------------------------------------------
# # Export results to multiple formats
# result$export_results("basel_uhi", formats = c("geojson", "csv", "gpkg"))
# 
# # Using a bounding box instead of city name
# result_bbox <- analyze_and_visualize_uhi(
#   location = c(7.55, 47.53, 7.65, 47.58),  # xmin, ymin, xmax, ymax
# 
#   date_range = c("2023-07-01", "2023-07-31"),
#   hex_resolution = 9  # Larger hexagons for faster processing
# )
# 
# # With optional GHSL built-up data for more accurate built coverage
# result_ghsl <- analyze_and_visualize_uhi(
#   location = "Zurich, Switzerland",
#   date_range = c("2023-06-01", "2023-08-31"),
#   ghsl_path = "path/to/ghsl_built.tif",
#   composite_scenes = TRUE,  # Composite multiple scenes to reduce cloud gaps
#   max_scenes = 5
# )

## ----eval = FALSE-------------------------------------------------------------
# result <- calculate_and_visualize_GVI("image.png") #specify the image path
# OpenImageR::imageShow(result$segmented_image) #To visualize the segmented image
# green_pixels_raster <- as.raster(result$green_pixels_image) #To visualize green pixels
# plot(green_pixels_raster)
# 
# # Save the segmented image
# OpenImageR::writeImage(result$segmented_image, "segmented_image.png")
# 
# # Save the green pixels image
# OpenImageR::writeImage(result$green_pixels_image, "green_pixels_image.png")

## ----eval = FALSE-------------------------------------------------------------
# d1 <- get_osm_data("New Delhi, India")
# dsf <- d1$green_areas$osm_polygons
# d2 <- get_osm_data("Basel, Switzerland")
# bsf <- d2$green_areas$osm_polygons
# d3 <- get_osm_data("Medellin, Colombia")
# msf <- d3$green_areas$osm_polygons
# 
# cities_data <- list(dsf, bsf, msf)
# gssi_values <- gssi(cities_data, "ESRI:54009")

## ----eval = FALSE-------------------------------------------------------------
# library(greenR)
# 
# # Basic SVF screening using AWS terrain and Global Building Atlas (GBA) building footprints
# result_svf <- uh_svf(
#   city_name = "Basel",
#   bbox = c(7.58, 47.55, 7.60, 47.57),
#   terrain_source = "elevatr",
#   elevatr_z = 13,
#   buildings_source = "gba",
#   sample_mode = "street",
#   spacing_street_m = 30,
#   n_directions = 36,
#   output_dir = tempdir(),
#   output_prefix = "basel_svf"
# )
# 
# # View the calculated microclimate statistics and summaries
# print(result_svf$analytics)

## ----eval = FALSE-------------------------------------------------------------
# library(greenR)
# 
# # Run the complete decision support MCDA suite for a city
# result_decision <- uh_decision(
#   city_name = "Basel, Switzerland",
#   hex_size_m = 100,
#   ndvi_datetime = "2025-06-01/2025-08-31",
#   lst_datetime = "2025-06-01/2025-08-31",
#   output_dir = tempdir()
# )
# 
# # Explore the resulting data layers
# # Contains priority_grid (hex level), block_priority (superblock level), and canyon_priority (street corridor level)
# print(names(result_decision))

