Introduction

Knitting this document will set up the objects needed for the shiny app.

library(rpostgis)
library(RPostgreSQL)
library(sf)
library(mapview)
library(leaflet.extras)
library(dplyr)
library(raster)
library(elevatr)
library(units)

conn <- dbConnect("PostgreSQL", host = "postgis", dbname = "nateng" ,user = "docker", password = "docker")


grassland<-st_read(conn,query="select * from calc_grass")
transects<-st_read(conn,query="select * from transects")
counts<-st_read(conn,query="select * from counts")

# d<-st_buffer(st_union(st_zm(grassland)), 10) ## This was used to unite the polygons at divided sites into fragments.
# d<-st_cast(d,"POLYGON")
# d<-st_sf(d)
# d$area<-as.numeric(st_area(d))
# grass_frags<-d
# write_sf(grass_frags,conn)
grass_frags<-st_read(conn,query="select * from grass_frags")
dbDisconnect(conn)

Simplify the fragments.

The st_distance function uses the whole geometry (not just centroids). So distances are calculated between the edges of the polygons. However if very complex geometries are used the function will take a very long time. So geomtetries are simplificed first. The best algoeithm for this is found in the rmapshaper package.

frags<-rmapshaper::ms_simplify(grass_frags, keep = 0.02,keep_shapes = TRUE)
dist_mat<-st_distance(frags)
dist_mat<-drop_units(dist_mat)
#grass_frags %>% filter(area> 50000) ->dd
centers <- st_centroid(frags)
## Warning in st_centroid.sf(frags): st_centroid assumes attributes are
## constant over geometries of x
coords<-st_coordinates(centers)
library(sp)
library(maptools)
library(spdep)

build_network<-function(dist=1000,dmat=dist_mat,cds=coords)
{
  
  dmat[dmat>dist]<-0
  nbs<-mat2listw(dmat)
  net<-nb2lines(nbs$neighbours,coords=cds)
  net<-st_as_sf(net)
  st_crs(net)<-st_crs(grass_frags)
  return (list(net=net,nbs=nbs))
}


net<-build_network()
network<-st_transform(net$net,4326)

mapview(network,legend=FALSE) +mapview(frags,legend=FALSE) ->mp

mp
save(list=ls(),file="grasslands.rob")