# Analyze Spatial Patterns

## Setup

Load packages and import HYPE model files.

    # Load Packages
    library(HYPEtools)
    library(sf)
    library(leaflet)
    library(dplyr)

    # Get Path to HYPEtools Model Example Files
    model_path <- system.file("demo_model", package = "HYPEtools")

    # Import HYPE Model Files
    gd <- ReadGeoData(file.path(model_path, "GeoData.txt"))
    gcl <- ReadGeoClass(file.path(model_path, "GeoClass.txt"))
    stats.cout <- ReadSubass(file.path(model_path,"results","subass1.txt"))
    mcrun <- ReadMapOutput(file.path(model_path,"results","mapCRUN.txt"))

## Read GIS Files

    # Read GIS Files
    map.subid <- st_read(file.path(model_path, "gis","Nytorp_map.gpkg"))
    #> Reading layer `Nytorp_map' from data source
    #>   `C:\Users\a002416\AppData\Local\Temp\Rtmpa61thU\Rinst3ab81ef4261b\HYPEtools\demo_model\gis\Nytorp_map.gpkg'
    #>   using driver `GPKG'
    #> Simple feature collection with 25 features and 38 fields
    #> Geometry type: POLYGON
    #> Dimension:     XY
    #> Bounding box:  xmin: 518978 ymin: 6413496 xmax: 541065.4 ymax: 6444436
    #> Projected CRS: SWEREF99 TM

    map.Qobs <- st_read(file.path(model_path,"gis", "Nytorp_station.gpkg")) %>%
      mutate(SUBID = 3587, .after = "long") # Add SUBID to gauge station attributes
    #> Reading layer `Nytorp_station' from data source
    #>   `C:\Users\a002416\AppData\Local\Temp\Rtmpa61thU\Rinst3ab81ef4261b\HYPEtools\demo_model\gis\Nytorp_station.gpkg'
    #>   using driver `GPKG'
    #> Simple feature collection with 1 feature and 2 fields
    #> Geometry type: POINT
    #> Dimension:     XY
    #> Bounding box:  xmin: 538901.5 ymin: 6432544 xmax: 538901.5 ymax: 6432544
    #> Projected CRS: SWEREF99 TM

    # Show the column names of imported GIS file
    names(map.Qobs)
    #> [1] "lat"   "long"  "SUBID" "geom"

    # Plot Model Subbasins
    plot(map.subid)

## Plot Model Performance on a Static Map

    # Show the column names of imported subbasin performance file
    names(stats.cout)
    #>  [1] "SUBID"   "NSE"     "CC"      "RE(%)"   "RSDE(%)" "Sim"     "Rec"
    #>  [8] "SDSim"   "SDRec"   "MAE"     "RMSE"    "Bias"    "SDE"     "KGE"
    #> [15] "KGESD"   "KGEM"    "NRMSE"   "NSEW"    "Nrec"

    # Choose to plot NSE; Assign the selected statistics column number to stat.col.plot
    stat.col.plot <- 2 # For NSE
    stat.nm.plot <- "NSE"

    # Generate Plot - There is only one observation station, so only one point appears on the map
    PlotMapPoints(x = stats.cout[, c(1,stat.col.plot)],
                  sites = map.Qobs, sites.subid.column = 3, bg = map.subid)
    #> Joining "SUBID" from GIS Data (sites) To "SUBID" from subass (x)

## Plot Model Performance on an Interactive Leaflet Map

    # Generate Plot - There is only one observation station, so only one point appears on the map
    # PlotMapPoints(map.type = "leaflet",
    #               x = stats.cout[, c(1,stat.col.plot)],
    #               sites = map.Qobs, sites.subid.column = 3, bg = map.subid,
    #               legend.pos = "bottomright",
    #               plot.scale = FALSE, plot.arrow = FALSE, plot.label=TRUE, bg.label.column = 25, plot.bg.label="static")

## Plot Simulated Runoff on a Static Map

    # Show the column names of imported GIS file
    names(map.subid)
    #>  [1] "AROID"      "YTKOD"      "NAMN"       "VDRID"      "INOBJ"
    #>  [6] "UTOBJ"      "OMRID_NED"  "OMRTYP"     "HARO"       "DISTRICT"
    #> [11] "LANDSKOD"   "AREAL"      "AVM"        "HAVAVM"     "HORDNING"
    #> [16] "AAUEB"      "AA_ANT_ARO" "MEDHOJD"    "VERSION"    "Shape_Leng"
    #> [21] "SUBID"      "aroid_old"  "Shape_Area" "omr_info"   "SUBID2016"
    #> [26] "RIVLEN"     "rotarea"    "rivlen_old" "rivlenold_" "SUBID201_1"
    #> [31] "AREA"       "PARREG"     "int_andel_" "barrskg"    "lovskg"
    #> [36] "blandskg"   "skog_tot"   "REGION"     "geom"

    # Generate Plot
    PlotMapOutput(mcrun, map = map.subid, map.subid.column = 25, var.name = "CRUN", legend.title = "Runoff (mm/d)",
                  col = ColQ, col.breaks = NULL, legend.pos = "right")
    #> Joining "SUBID2016" from GIS Data (map) To "SUBID" from MapOutput (x)

## Plot Simulated Runoff on an Interactive Leaflet Map

    # Generate Plot
    # PlotMapOutput(mcrun, map.type = "leaflet", map = map.subid, map.subid.column = 25, var.name = "CRUN", legend.title = "Runoff (mm/d)",
    #               col = ColQ, col.breaks = NULL, legend.pos = "bottomright", map.adj = 0, plot.scale = FALSE, plot.arrow = FALSE)

## Create Leaflet Map with Additional Bling

    # Generate leaflet map with additional bling
    # leafmap <- PlotMapOutput(mcrun, map.type = "leaflet", map = map.subid, map.subid.column = 25, var.name = "CRUN", legend.title = "Runoff (mm/d)",
    #               col = ColQ, col.breaks = NULL, legend.pos = "bottomright", map.adj = 0, plot.scale = TRUE, plot.arrow = FALSE, plot.label = TRUE, plot.searchbar = TRUE)

    # Add Additional Basemap and Marker for SMHI Location
    # leafmap <- leafmap %>%
    #
    #   # Update Layers Control to include the new Basemap and SMHI Marker
    #   addLayersControl(
    #     baseGroups=c("Map","Street","Topo","Satellite","Stamen Toner"),
    #     overlayGroups=c("Subbasins","SMHI"),
    #     options=layersControlOptions(collapsed = FALSE, autoIndex = TRUE)) %>%
    #
    #   # Add Basemap
    #   addProviderTiles(provider = providers$Stamen.Toner, group = "Stamen Toner") %>%
    #
    #   # Add Marker on Map for SMHI Location
    #   addMarkers(group = "SMHI",
    #              lng = 16.151890,
    #              lat = 58.578950,
    #              popup = "SMHI")

    # View Updated Map
    # leafmap

## Plot Map Outputs in an Interactive Shiny App

    # Start App - Symbolize with points
    # VisualizeMapPoints(
    #   results.dir = system.file("demo_model", "results", package = "HYPEtools"),
    #   sites = system.file("demo_model", "gis", "Nytorp_centroids.gpkg", package = "HYPEtools"),
    #   sites.subid.column = 25,
    #   bg = system.file("demo_model", "gis", "Nytorp_map.gpkg", package = "HYPEtools")
    # )

    # Start App - Symbolize with polygons
    # VisualizeMapOutput(
    #   results.dir = system.file("demo_model", "results", package = "HYPEtools"),
    #   map = system.file("demo_model", "gis", "Nytorp_map.gpkg", package = "HYPEtools"),
    #   map.subid.column = 25
    # )