Movatterモバイル変換


[0]ホーム

URL:


dggridR: Discrete Global Grids for R

Richard Barnes

2024-07-17

dggridR.R

Spatial Analysis Done Right

You want to do spatial statistics, and it’s going to involvebinning.

Binning with a rectangular grid introduces messy distortions. At themacro-scale using a rectangular grid does things like making Greenlandbigger than the United States and Antarctica the largest continent.

Mercator Projection
Mercator Projection

But this kind of distortion is present no matter what the resolutionis.

What you want are bins of equal size, regardless of where they are onthe globe, regardless of their resolution.

dggridR solves this problem.

dggridR builds discrete global grids which partition the surface ofthe Earth into hexagonal, triangular, or diamond cells,all ofwhich have the same size. (There are some minor details whichare detailed in theCaveats section below.)

Discrete Global Grid in use
Discrete Global Grid in use

This package includes everything you need to make spatial binninggreat again.

Many details are included in the vignette.

Grids

The following grids are available:

Unless you are using cells with very large areas (significantfractions of Earth’s hemispheres), I recommend the ISEA3H be yourdefault grid.

This grid, along with the other Icosahedral grids ensures that allcells are of equal area, with a notable exception. At every resolution,the Icosahedral grids contain 12 pentagonal cells which each have anarea exactly 5/6 that of the hexagonal cells. But you don’t need toworry about this too much for two reasons. (1) As the table below shows,these cells are a small, small minority of the total number of cells.(2) The grids are orientated so that these cells are in out-of-the-wayplaces. Future versions of this package will allow you to reorient thegrids, if need be. (TODO)

For more complex applications than simple spatial binning, it isnecessary to consider trade-offs between the different grids. Goodreferences for understanding these include(Kimerling et al. 1999; Gregory et al.2008).

Users attempting multi-scale analyses should be aware that in thehexagonal grids cells from one resolution level are partially containedby the cells of other levels.

Nested hexagonal grid
Nested hexagonal grid

At present, there is no convenient way to convert grid cell ids atone resolution level to another. In the future, I hope to add thiscapability to the package. (TODO)

ISEA3H Details

The following table shows the number of cells, their area, andstatistics regarding the spacing of their center nodes for the ISEA3Hgrid type.

ISEA3H grid cell characteristics.
ResNumber of CellsCell Area (km^2)MinMaxMeanStd
01251,006,562.17241
13217,002,187.390804,156.180004,649.100004,320.49000233.01400
2925,667,395.796932,324.810002,692.720002,539.69000139.33400
32721,889,131.932311,363.560001,652.270001,480.0200089.39030
4812629,710.64410756.96100914.27200855.4190052.14810
52,432209,903.54803453.74800559.23900494.9590029.81910
67,29269,967.84934248.80400310.69300285.6520017.84470
721,87223,322.61645151.22100187.55000165.058009.98178
865,6127,774.2054882.31100104.4700095.263606.00035
9196,8322,591.4018350.4060063.0097055.022603.33072
10590,492863.8006127.3323035.0197031.759602.00618
111,771,472287.9335416.8019021.0902018.341001.11045
125,314,41295.977859.0936811.7061010.587100.66942
1315,943,23231.992625.600657.044626.113670.37016
1447,829,69210.664213.028473.907423.529110.22322
15143,489,0723.554731.866882.350582.037890.12339
16430,467,2121.184911.009041.303351.176380.07442
171,291,401,6320.394970.622290.783910.679300.04113
183,874,204,8920.131660.336280.434590.392130.02481
1911,622,614,6720.043890.207430.261370.226430.01371
2034,867,844,0120.014630.112080.144890.130710.00827

How do I use it?

  1. Construct a discrete global grid system (dggs) object usingdgconstruct()

  2. Get information about your dggs object using:

    • dggetres()
    • dginfo()
    • dgmaxcell()
  3. Get the grid cells of some lat-long points with:

    • dgGEO_to_SEQNUM()
    • One of many, many other such functions
  4. Get the boundaries of the associated grid cells for use inplotting with:

    • dgcellstogrid()
    • dgearthgrid()
    • dgrectgrid()
    • dgshptogrid()
  5. Check that your dggs object is valid (if you’ve mucked with it)using:

    • dgverify()

Examples

Binning Lat-Long Points

The following example demonstrates converting lat-long locations (theepicenters of earthquakes) to discrete global grid locations (cellnumbers), binning based on these numbers, and plotting the result.Additionally, the example demonstrates how to get the center coordinatesof the cells.

#Include librarieslibrary(dggridR)library(collapse)#Construct a global grid with cells approximately 1000 miles acrossdggs<-dgconstruct(spacing=1000,metric=FALSE,resround='down')#Load included test data setdata(dgquakes)#Get the corresponding grid cells for each earthquake epicenter (lat-long pair)dgquakes$cell<-dgGEO_to_SEQNUM(dggs,dgquakes$lon,dgquakes$lat)$seqnum#Converting SEQNUM to GEO gives the center coordinates of the cellscellcenters<-dgSEQNUM_to_GEO(dggs,dgquakes$cell)#Get the number of earthquakes in each cellquakecounts<- dgquakes|>fcount(cell,name ="count")#Get the grid cell boundaries for cells which had quakesgrid<-dgcellstogrid(dggs,quakecounts$cell)#Update the grid cells' properties to include the number of earthquakes#in each cellgrid<-merge(grid,quakecounts,by.x="seqnum",by.y="cell")#Make adjustments so the output is more visually interestinggrid$count<-log(grid$count)cutoff<-fquantile(grid$count,0.9)grid<- grid|>fmutate(count =ifelse(count>cutoff,cutoff,count))#Get polygons for each country of the worldcountries<-map_data("world")

dggridR.R

Okay, let’s draw the plot. Notice how the hexagons appear to be alldifferent sizes. Really, though, they’re not: that’s just the effect oftrying to plot a sphere on a flat surface! And that’s what would happento your data if you didn’t use this package :-)

#Plot everything on a flat map# Handle cells that cross 180 degreeswrapped_grid=st_wrap_dateline(grid,options =c("WRAPDATELINE=YES","DATELINEOFFSET=180"),quiet =TRUE)
## Warning in CPL_wrap_dateline(st_geometry(x), options, quiet): GDAL Error 1:## IllegalArgumentException: Points of LinearRing do not form a closed linestring## Warning in CPL_wrap_dateline(st_geometry(x), options, quiet): GDAL Error 1:## IllegalArgumentException: Points of LinearRing do not form a closed linestring
ggplot()+geom_polygon(data=countries,aes(x=long,y=lat,group=group),fill=NA,color="black")+geom_sf     (data=wrapped_grid,aes(fill=count),color=alpha("white",0.4))+geom_point  (aes(x=cellcenters$lon_deg,y=cellcenters$lat_deg))+scale_fill_gradient(low="blue",high="red")

dggridR.R

dggridR.R

–>

You can also write out a KML file with your data included fordisplaying in, say, Google Earth:

library(sf)#Get the grid cell boundaries for the whole Earth using this dggs in a form#suitable for printing to a KML filegrid<-dgearthgrid(dggs)#Update the grid cells' properties to include the number of earthquakes#in each cellgrid$count<-merge(grid, quakecounts,by.x="seqnum",by.y="cell",all.x=TRUE)#Write out the gridst_write(grid,"quakes_per_cell.kml",layer="quakes",driver="KML")

dggridR.R

Randomly Sampling the Earth: Method 1

Say you want to sampleN areas of equal size uniformlydistributed on the Earth. dggridR provides two possible ways toaccomplish this. The conceptually simplest is to chooseNuniformly distributed lat-long pairs and retrieve their associated gridcells:

#Include librarieslibrary(dggridR)N<-100#How many cells to sample#Distribute the points uniformly on a sphere using equations from#http://mathworld.wolfram.com/SpherePointPicking.htmlu<-runif(N)v<-runif(N)theta<-2*pi*u*180/piphi<-acos(2*v-1)*180/pilon<- theta-180lat<- phi-90df<-data.frame(lat=lat,lon=lon)#Construct a global grid in which every hexagonal cell has an area of#100,000 miles^2. You could, of course, choose a much smaller value, but these#will show up when I map them later.#Note: Cells can only have certain areas, the `dgconstruct()` function below#will tell you which area is closest to the one you want. You can also round#up or down.#Note: 12 cells are actually pentagons with an area 5/6 that of the hexagons#But, with millions and millions of hexes, you are unlikely to choose one#Future versions of the package will make it easier to reject the pentagonsdggs<-dgconstruct(area=100000,metric=FALSE,resround='nearest')#Get the corresponding grid cells for each randomly chosen lat-longdf$cell<-dgGEO_to_SEQNUM(dggs,df$lon,df$lat)$seqnum#Get the hexes for each of these cellsgridfilename<-dgcellstogrid(dggs,df$cell)

dggridR.R

The resulting distribution of cells appears as follows:

#Get the grid in a more convenient formatgrid<-dgcellstogrid(dggs,df$cell)grid<-st_wrap_dateline(grid,options =c("WRAPDATELINE=YES","DATELINEOFFSET=180"),quiet =TRUE)#Get polygons for each country of the worldcountries<-map_data("world")#Plot everything on a flat mapp<-ggplot()+geom_polygon(data=countries,aes(x=long,y=lat,group=group),fill=NA,color="black")+geom_sf(data=grid,fill=alpha("green",alpha=0.4),color=alpha("white",alpha=0.4))p

dggridR.R

Randomly Sampling the Earth: Method 2

Say you want to sampleN areas of equal size uniformlydistributed on the Earth. dggridR provides two possible ways toaccomplish this. The easiest way to do this is to note that grid cellsare labeled from 1 toM, whereM is thelargest cell id at the resolution in question. Therefore, we can samplecell ids and generate a grid accordingly.

#Include librarieslibrary(dggridR)N<-100#How many cells to sample#Construct a global grid in which every hexagonal cell has an area of#100,000 miles^2. You could, of course, choose a much smaller value, but these#will show up when I map them later.#Note: Cells can only have certain areas, the `dgconstruct()` function below#will tell you which area is closest to the one you want. You can also round#up or down.#Note: 12 cells are actually pentagons with an area 5/6 that of the hexagons#But, with millions and millions of hexes, you are unlikely to choose one#Future versions of the package will make it easier to reject the pentagonsdggs<-dgconstruct(area=100000,metric=FALSE,resround='nearest')maxcell<-dgmaxcell(dggs)#Get maximum cell idcells<-sample(1:maxcell, N,replace=FALSE)#Choose random cellsgrid<-dgcellstogrid(dggs,cells)#Get grid

dggridR.R

The resulting distribution of cells appears as follows:

#Get the grid in a more convenient formatgrid<-dgcellstogrid(dggs,df$cell)grid<-st_wrap_dateline(grid,options =c("WRAPDATELINE=YES","DATELINEOFFSET=180"),quiet =TRUE)#Get polygons for each country of the worldcountries<-map_data("world")#Plot everything on a flat mapp<-ggplot()+geom_polygon(data=countries,aes(x=long,y=lat,group=group),fill=NA,color="black")+geom_sf(data=grid,fill=alpha("green",0.4),color=alpha("white",0.4))p

dggridR.R

Save a grid for use in other software

Sometimes you want to use a grid in software other than R. Tofacilitate this, the grid generation commands include thesavegrid argument, as demonstrated below.

library(dggridR)#Generate a global grid whose cells are ~100,000 miles^2dggs<-dgconstruct(area=100000,metric=FALSE,resround='nearest')#Save the cells to a KML file for use in other softwaregridfilename<-dgearthgrid(dggs,savegrid=tempfile())

dggridR.R

Get a grid that covers South Africa

library(dggridR)#Generate a dggs specifying an intercell spacing of ~25 milesdggs<-dgconstruct(spacing=100,metric=FALSE,resround='nearest')#Read in the South Africa's borders from the shapefilesa_border<-st_read(dg_shpfname_south_africa(),layer="ZAF_adm0")st_crs(sa_border)=4326#Get a grid covering South Africasa_grid<-dgshptogrid(dggs,dg_shpfname_south_africa())#Plot South Africa's borders and the associated gridp<-ggplot()+geom_sf(data=sa_border,fill=NA,color="black")+geom_sf(data=sa_grid,fill=alpha("blue",0.4),color=alpha("white",0.4))p

dggridR.R

Caveats

At every resolution, the Icosahedral grids contain 12 pentagonalcells which each have an area exactly 5/6 that of the hexagonal cells.In the standard orientation, these are located as follows (scaled to asize corresponding to the grid resolution):

dggridR.R

Roadmap

Credits

This R package was developed by Richard Barnes (https://rbarnes.org/).

The dggrid conversion software was developed predominantly by KevinSahr (https://discreteglobal.wpengine.com/), withcontributions from a few others.

Large portions of the above documentation are drawn from the DGGRIDversion 6.2b User Documentation, which is available in its entiretyhere.

Disclaimer

This packageshould operate in the manner described here, inthe package’s main documentation, and in Kevin Sahr’s dggriddocumentation. Unfortunately, none of us are paid enough to makeabsolutely, doggone certain that that’s the case. Use at your owndiscretion. That said, if you find bugs or are seeking enhancements, wewant to hear about them.

Citing this Package

Please cite this package as:

Richard Barnes and Kevin Sahr (2017). dggridR: Discrete Global Gridsfor R. R package version 2.0.4. “https://github.com/r-barnes/dggridR/

References

Gregory, Matthew J., A. Jon Kimerling, Denis White, and Kevin Sahr.2008.“A Comparison of Intercell Metrics on Discrete Global GridSystems.”Computers, Environment and Urban Systems 32(3): 188–203.https://doi.org/10.1016/j.compenvurbsys.2007.11.003.
Kimerling, Jon A., Kevin Sahr, Denis White, and Lian Song. 1999.“Comparing Geometrical Properties of Global Grids.”Cartography and Geographic Information Science 26 (4): 271–88.https://doi.org/10.1559/152304099782294186.

[8]ページ先頭

©2009-2025 Movatter.jp