Giter Club home page Giter Club logo

dggridr's Introduction

DOI

dggridR: Discrete Global Grids for R

Spatial Analysis Done Right

You want to do spatial statistics, and it's going to involve binning.

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

Mercator Projection

But this kind of distortion is present no matter what the resolution is; in fact, it shows up whenever you project a sphere onto a plane.

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

dggridR solves this problem.

dggridR builds discrete global grids which partition the surface of the Earth into hexagonal, triangular, or diamond cells, all of which have the same size. (There are some minor caveats which are detailed in the vignettes.)

Discrete Global Grid in use

(Naturally, you can use much smaller cells than those shown in the image above.)

This package includes everything you need to make spatial binning great again.

Many details and examples are included in the vignette.

Installation

dggridR is available from CRAN via:

install.packages('dggridR')

If you want your code to be as up-to-date as possible, you can install it using:

library(devtools) #Use `install.packages('devtools')` if need be
devtools::install_github("r-barnes/dggridR", vignette=TRUE)

Show me some code

Okay.

Your analysis could be as easy as this:

library(dggridR)
library(collapse)

#Construct a global grid with cells approximately 1000 miles across
dggs          <- dgconstruct(spacing=1000, metric=FALSE, resround='down')

#Load included test data set
data(dgquakes)

#Get the corresponding grid cells for each earthquake epicenter (lat-long pair)
dgquakes$cell <- dgGEO_to_SEQNUM(dggs, dgquakes$lon, dgquakes$lat)$seqnum

#Get the number of earthquakes in each equally-sized cell
quakecounts   <- dgquakes %>% fcount(cell)

Show me more examples!

In R, typing

vignette('dggridR')

will bring up many examples.

But I want higher resolution grids than that

Many different grid resolutions are available for many different grids. The following chart shows the number of cells, their area, and statistics regarding the spacing of their center nodes for the ISEA3H grid type.

Res Number of Cells Cell Area (km^2) Min Max Mean Std
1 32 17,002,187.39080 4,156.18000 4,649.10000 4,320.49000 233.01400
2 92 5,667,395.79693 2,324.81000 2,692.72000 2,539.69000 139.33400
3 272 1,889,131.93231 1,363.56000 1,652.27000 1,480.02000 89.39030
4 812 629,710.64410 756.96100 914.27200 855.41900 52.14810
5 2,432 209,903.54803 453.74800 559.23900 494.95900 29.81910
6 7,292 69,967.84934 248.80400 310.69300 285.65200 17.84470
7 21,872 23,322.61645 151.22100 187.55000 165.05800 9.98178
8 65,612 7,774.20548 82.31100 104.47000 95.26360 6.00035
9 196,832 2,591.40183 50.40600 63.00970 55.02260 3.33072
10 590,492 863.80061 27.33230 35.01970 31.75960 2.00618
11 1,771,472 287.93354 16.80190 21.09020 18.34100 1.11045
12 5,314,412 95.97785 9.09368 11.70610 10.58710 0.66942
13 15,943,232 31.99262 5.60065 7.04462 6.11367 0.37016
14 47,829,692 10.66421 3.02847 3.90742 3.52911 0.22322
15 143,489,072 3.55473 1.86688 2.35058 2.03789 0.12339
16 430,467,212 1.18491 1.00904 1.30335 1.17638 0.07442
17 1,291,401,632 0.39497 0.62229 0.78391 0.67930 0.04113
18 3,874,204,892 0.13166 0.33628 0.43459 0.39213 0.02481
19 11,622,614,672 0.04389 0.20743 0.26137 0.22643 0.01371
20 34,867,844,012 0.01463 0.11208 0.14489 0.13071 0.00827

Credits

The code in the 'src' directory is based off of DGGRIDv6.2b by Kevin Sahr.

However, Richard Barnes has made some significant alterations. These include:

  • Replacement of gpclib with clipper, thus making DGGRID into FLOSS software available for both commercial and non-commercial use without restriction
  • Restructuring and simplifying all of the makefiles to enable compilation in R
  • Direct inclusion of the shapelib library
  • Addition of the SEQTOPOLY option under the GENERATE_GRID faculty
  • Alterations that enable the code to be compiled under GCC6
  • Alterations that make the code ISO C conformant
  • Alterations to resolve -pedantic and -Wall warnings

The package relies on several libraries, as noted in the Licensing section below.

Licensing

This package uses the following libraries:

  • clipper: The clipper library has been released under the Boostv1 license by Angus Johnson

  • dggrid: Kevin Sahr has released dggrid as a "public domain software program"

  • proj4lib: Gerald Evenden has released this code into the public domain. More recent versions of the library, not used here, are under an MIT-style license.

  • shapelib: Frank Warmerdam has released shapelib under an MIT-style license. There is also an LGPL licensing option which I have chosen not to use.

This package, and all code and documentation not otherwise mentioned above (essentially anything outside the src/ directory of this package) are released under the MIT (Expat) license, as stated in the LICENSE file. The LICENCE file exists for use with CRAN.

Disclaimer

This package should operate in the manner described here, in the package's main documentation, and in Kevin Sahr's dggrid documentation. Unfortunately, none of us are paid enough to make absolutely, doggone certain that that's the case. That said, if you find bugs or are seeking enhancements, we want to hear about them.

Citing this Package

Please cite this package as:

Richard Barnes and Kevin Sahr (2017). dggridR: Discrete Global Grids for R. R package version 2.0.4. "https://github.com/r-barnes/dggridR/" doi:10.5281/zenodo.1322866

dggridr's People

Contributors

edzer avatar espinielli avatar pieterprovoost avatar r-barnes avatar sebkrantz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dggridr's Issues

"dgconstruc" (cell center points)

Dear Richard,

I've been going over the User Documentation for DGGRID version 6.2b. I noticed that the original software allows to obtain the cell center points.

"The grid cells generated by a DGGRID run with the value GENERATE_GRID specified for the choice parameter dggrid_operation can be output as cell boundaries, cell center points, or both"

From what I understand, the Package ‘dggridR’ does not allow this information to be obtained.

It´s true?

Best,

Víctor

How to calculate grid distance between hexagons?

Dear Richard,

I am trying to find distance between two hexagons, because I would like to obtain a distance matrix between the hexagons (using the Earthquake database) What can be proper way to calculate this?

Best,

Víctor

Cell assignment not matching polygons from dgcellstogrid()

Not sure if there's something wrong here, or if I'm just using the functions incorrectly, but I'm finding some odd behavior when I try to thin my data. In the reprex below, I create 100 random points then randomly select one from each cell of a hexagonal grid. Everything looks to be working, until I plot the grid and points and it appears that multiple points are being selected from each cell and none from others. This is happening because cell assignment is not matching what happens what you get by working with the hexagonal polygons.

library(sf)
library(dggridR)
library(tidyverse)
set.seed(1)

dggs <- dgconstruct(spacing = 10)

bb <- st_bbox(c(xmin = 0, xmax = 0.25, ymin = 0, ymax = 0.25), crs = 4326) %>% 
  st_as_sfc() %>% 
  st_sf()
pts <- st_sample(bb, 100) %>% 
  st_sf(as.data.frame(st_coordinates(.)), geometry = .) %>% 
  rename(lat = X, lon = Y)
cells <- dgGEO_to_SEQNUM(dggs, pts$lon, pts$lat)
pts$cell <- cells$seqnum
pts_ss <- pts %>% 
  group_by(cell) %>% 
  sample_n(size = 1) %>% 
  ungroup()

cells_poly <- dgcellstogrid(dggs, unique(pts$cell), frame = FALSE) %>% 
  st_as_sf() %>% 
  mutate(cell = unique(pts$cell))
ggplot() +
  geom_sf(data = cells_poly) +
  geom_sf(data = pts) +
  geom_sf(data = pts_ss, col = "red") +
  theme_bw()

hex-sampling

dg_shpfname_south_africa: Wrong path

dg_shpfname_south_africa gives the wrong path on my system (is this the path on the (CRAN) machine that compiles the package?)

dg_shpfname_south_africa
#> [1] "d:/RCompile/CRANpkg/lib/3.4/dggridR/extdata/ZAF_adm0.shp"

it should be

file.path(find.package('dggridR'), "extdata", "ZAF_adm0.shp")
#> [1] "C:/Users/dpprdan/Documents/R/win-library/3.4/dggridR/extdata/ZAF_adm0.shp"
Session info
devtools::session_info()
#> Session info -------------------------------------------------------------
#>  setting  value                       
#>  version  R version 3.4.0 (2017-04-21)
#>  system   x86_64, mingw32             
#>  ui       RTerm                       
#>  language (EN)                        
#>  collate  German_Germany.1252         
#>  tz       Europe/Berlin               
#>  date     2017-05-15
#> Packages -----------------------------------------------------------------
#>  package    * version    date       source                          
#>  assertthat   0.2.0      2017-04-11 CRAN (R 3.3.3)                  
#>  backports    1.0.5      2017-01-18 CRAN (R 3.3.2)                  
#>  base       * 3.4.0      2017-04-21 local                           
#>  colorspace   1.3-2      2016-12-14 CRAN (R 3.3.2)                  
#>  compiler     3.4.0      2017-04-21 local                           
#>  datasets   * 3.4.0      2017-04-21 local                           
#>  DBI          0.6-1      2017-04-01 CRAN (R 3.3.3)                  
#>  devtools     1.13.1     2017-05-13 CRAN (R 3.4.0)                  
#>  dggridR    * 1.0.1      2017-04-24 CRAN (R 3.4.0)                  
#>  digest       0.6.12     2017-01-27 CRAN (R 3.3.2)                  
#>  dplyr      * 0.5.0      2016-06-24 CRAN (R 3.3.1)                  
#>  evaluate     0.10       2016-10-11 CRAN (R 3.3.1)                  
#>  ggplot2    * 2.2.1      2016-12-30 CRAN (R 3.3.2)                  
#>  graphics   * 3.4.0      2017-04-21 local                           
#>  grDevices  * 3.4.0      2017-04-21 local                           
#>  grid         3.4.0      2017-04-21 local                           
#>  gtable       0.2.0      2016-02-26 CRAN (R 3.3.0)                  
#>  htmltools    0.3.6      2017-04-28 CRAN (R 3.4.0)                  
#>  knitr        1.15.1     2016-11-22 CRAN (R 3.3.2)                  
#>  lattice      0.20-35    2017-03-25 CRAN (R 3.3.3)                  
#>  lazyeval     0.2.0.9000 2016-06-23 Github (hadley/lazyeval@c155c3d)
#>  magrittr     1.5        2014-11-22 CRAN (R 3.3.0)                  
#>  memoise      1.1.0      2017-04-21 CRAN (R 3.3.3)                  
#>  methods    * 3.4.0      2017-04-21 local                           
#>  munsell      0.4.3      2016-02-13 CRAN (R 3.3.0)                  
#>  plyr         1.8.4      2016-06-08 CRAN (R 3.3.1)                  
#>  R6           2.2.1      2017-05-10 CRAN (R 3.4.0)                  
#>  Rcpp         0.12.10    2017-03-19 CRAN (R 3.3.3)                  
#>  rgdal      * 1.2-7      2017-04-25 CRAN (R 3.3.3)                  
#>  rmarkdown    1.5        2017-04-26 CRAN (R 3.3.3)                  
#>  rprojroot    1.2        2017-01-16 CRAN (R 3.3.2)                  
#>  scales       0.4.1      2016-11-09 CRAN (R 3.3.2)                  
#>  sp         * 1.2-4      2016-12-22 CRAN (R 3.3.2)                  
#>  stats      * 3.4.0      2017-04-21 local                           
#>  stringi      1.1.5      2017-04-07 CRAN (R 3.3.3)                  
#>  stringr      1.2.0      2017-02-18 CRAN (R 3.3.3)                  
#>  tibble       1.3.0      2017-04-01 CRAN (R 3.3.3)                  
#>  tools        3.4.0      2017-04-21 local                           
#>  utils      * 3.4.0      2017-04-21 local                           
#>  withr        1.0.2      2016-06-20 CRAN (R 3.3.1)                  
#>  yaml         2.1.14     2016-11-12 CRAN (R 3.3.2)

Problem with dgcellstogrid: lack of understanting with rgdal::OGR???

Hi,

I've been using dggridR several months ago without any problem. Now after upgrading some libraries n my system (including the gdal libs) I'm consistently obtaining this error (using your earthquakes example, but with my own data as well):

grid <- dgcellstogrid(dggs, dgquakes$cell, frame=TRUE)
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open layer

I've checked and dgconstruct is generating the KML file in my /tmp directory. I've reinstalled rgdal and dggridR. No solution with that so far.

Any ideas of what could be happening?

I'm running dggridR 1.0.1 and rgdal 1.2-8 on a Kubuntu 16.04 with R 3.4.1

Thanks, EKS

Late edit:
NOTE:
Playing around I've removed the layer param form the readOGR function in dg_process_kml and it works. Is that the source of the problem???

Documentation shows deprecated methods.

#Get the corresponding grid cells for each earthquake epicenter (lat-long pair) dgquakes$cell <- dgtransform(dggs,dgquakes$lat,dgquakes$lon)

from the readme. "dgtransform" is deprecated.

Error when implementing facet_wrap()

I have time series data for locations of events in a given region. I'd like to show the spatial-temporal patterns using dggridR and the facet_wrap function in ggplot. However, when I do this I get the following error:
Error in if (empty(data)) { : missing value where TRUE/FALSE needed

As an example, I extracted the month information from the dgquakes dataset using library(lubridate), and followed the example plot for dggridR. I added facet_wrap(~month) and received the same error:

p+coord_map("ortho", orientation = c(-38.49831, -179.9223, 0))+
+   xlab('')+ylab('')+
+   theme(axis.ticks.x=element_blank())+
+   theme(axis.ticks.y=element_blank())+
+   theme(axis.text.x=element_blank())+
+   theme(axis.text.y=element_blank())+
+   ggtitle('Your data could look like this') +
+   facet_wrap(~month)

Error in if (empty(data)) { : missing value where TRUE/FALSE needed

Any suggestions on how to work around this?

dgearthgrid merge with binned data gives holes etc.

Instead of selecting just grid cells with data using dgcellstogrid(), I would like to display the full grid, including cells with NA.

I tried doing this by replacing dgcellstogrid with dggearthgrid and then merging using merge(all=TRUE) but the result is a messed up grid.

Reproducible example using your vignette code:

library(dggridR)
library(dplyr)
dggs          <- dgconstruct(spacing=1000, metric=FALSE, resround='down')
data(dgquakes)
dgquakes$cell <- dgGEO_to_SEQNUM(dggs,dgquakes$lon,dgquakes$lat)$seqnum
cellcenters   <- dgSEQNUM_to_GEO(dggs,dgquakes$cell)
quakecounts   <- dgquakes %>% group_by(cell) %>% summarise(count=n())
#** HERE replace dgcellstogrid() with dgearthgrid()**
# grid          <- dgcellstogrid(dggs,quakecounts$cell,frame=TRUE,wrapcells=TRUE)
grid          <- dgearthgrid(dggs, frame=TRUE, wrapcells=TRUE)
# merge using all=T to include NAs
grid          <- merge(grid,quakecounts,by.x="cell",by.y="cell", all = TRUE)

#PLOT
countries <- map_data("world")
p <- ggplot() + 
    geom_polygon(data=countries, aes(x=long, y=lat, group=group), fill=NA, color="black")   +
    geom_polygon(data=grid,      aes(x=long, y=lat, group=group, fill=count), alpha=0.4)    +
    geom_path   (data=grid,      aes(x=long, y=lat, group=group), alpha=0.4, color="white") +
    geom_point  (aes(x=cellcenters$lon_deg, y=cellcenters$lat_deg)) +
    scale_fill_gradient(low="blue", high="red")
p

Rplot01

how dgcellstogrid function works?

Hi,
Does this function uses sampling points to generate DGG cells? I have seen that this function generates gaps between dgg cells. By changing spacing parameter the gaps disappear I wanted to know why this happens and how to determine spacing parameter for this function to avoid such gaps?

dgearthgrid is slow

Long generation times. This is probably due to interfacing with R. For users employing savegrid, it should be possible to speed up generation by avoiding communication with R.

issue with KML

I tried the below but it didn't work:

dggs <- dgconstruct(projection="ISEA", aperture=3, topology="HEXAGON", res= 2, metric=TRUE, resround='nearest')
grid <- dgearthgrid(dggs, frame = FALSE)
writeOGR(grid, "grid.kml", "grid", "KML")

Error in writeOGR(grid, "grid.kml", "grid", "KML") :
obj must be a SpatialPointsDataFrame, SpatialLinesDataFrame or
SpatialPolygonsDataFrame

How to export successfully?

I want to build a grid and output it, but R always prompts me for this information. What do I need to do about it?

dggs <- dgconstruct(res=10)
dgearthgrid(dggs, frame = TRUE, wrapcells = TRUE, savegrid = 'C:\\Users\\z466\\Desktop\\FEEMS FLIES\\Grid_100.shp')
Error in writeOGR(grid, shpfname, driver = "ESRI Shapefile", layer = "dggrid") : 
  Spatial Polygons objects should have valid ordering comments
use rgeos::createSPComment()

memory usage by dgcellstogrid

Edited to simplify reproducible example. If I run the following code, the memory usage blows up (tens of GB), even though no objects are stored in the R environment. The issue appears both in Rstudio and R, both running R v. 3.4.4

 library(dggridR)
 
 hexgrid6 <- dgconstruct(res=6) # Construct geospatial hexagonal grid
 
 for(i in 1:1000){
   dgcellstogrid(hexgrid6, 1)
 }

Valgrind Issues

Running R's valgrind

R -d "valgrind --tool=memcheck --leak-check=full" --vanilla

produces a few run-time issues

==13831== Conditional jump or move depends on uninitialised value(s)
==13831==    at 0x2814A593: operator== (DgDiscRFS.h:57)
==13831==    by 0x2814A593: operator!= (DgDiscRFS.h:60)
==13831==    by 0x2814A593: operator= (DgDiscRFS.h:47)
==13831==    by 0x2814A593: DgResAdd (DgDiscRFS.h:28)
==13831==    by 0x2814A593: DgAddress (DgAddress.h:24)
==13831==    by 0x2814A593: DgRF<DgResAdd<DgIVec2D>, long>::makeLocation(DgResAdd<DgIVec2D> const&) const (DgRF_template.h:60)
==13831==    by 0x28161D19: DgDiscRFS2D (DgDiscRFS2D.h:39)
==13831==    by 0x28161D19: DgHexGrid2DS::DgHexGrid2DS(DgRFNetwork&, DgRF<DgDVec2D, long double> const&, int, unsigned int, bool, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, int, bool) (DgHexGrid2DS.cpp:25)
==13831==    by 0x2816739E: DgIDGG::initialize() (DgIDGG.cpp:901)
==13831==    by 0x28168091: DgIDGG::DgIDGG(DgGeoSphRF const&, DgGeoCoord const&, long double, unsigned int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, int, bool, int, unsigned int) (DgIDGG.cpp:749)
==13831==    by 0x281EC86F: dglib::GridThing::GridThing(long double, long double, long double, unsigned int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (dglib.cpp:87)
==13831==    by 0x281C3DA8: GridStat_nCells(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int) (Rwrapper.cpp:74)
==13831==    by 0x281D4792: Rcpp::CppFunction4<double, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int>::operator()(SEXPREC**) (Module_generated_CppFunction.h:407)
==13831==    by 0x211F4940: InternalFunction_invoke(SEXPREC*) (Module.cpp:122)
==13831==    by 0x4F0DA13: ??? (in /usr/lib/R/lib/libR.so)
==13831==    by 0x4F4E857: Rf_eval (in /usr/lib/R/lib/libR.so)
==13831==    by 0x4F512DA: ??? (in /usr/lib/R/lib/libR.so)
==13831==    by 0x4F4E5FA: Rf_eval (in /usr/lib/R/lib/libR.so)
==13831== 
==13831== Conditional jump or move depends on uninitialised value(s)
==13831==    at 0x2817C5A6: operator== (DgDiscRFS.h:57)
==13831==    by 0x2817C5A6: operator!= (DgDiscRFS.h:60)
==13831==    by 0x2817C5A6: operator= (DgDiscRFS.h:47)
==13831==    by 0x2817C5A6: DgResAdd (DgDiscRFS.h:28)
==13831==    by 0x2817C5A6: DgAddress (DgAddress.h:24)
==13831==    by 0x2817C5A6: DgRF<DgResAdd<DgQ2DICoord>, long>::makeLocation(DgResAdd<DgQ2DICoord> const&) const (DgRF_template.h:60)
==13831==    by 0x28179677: DgIDGGS::DgIDGGS(DgRFNetwork&, DgGeoSphRF const&, DgGeoCoord const&, long double, unsigned int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, int, bool) (DgIDGGS.cpp:106)
==13831==    by 0x2817A8CC: DgIDGGS3H (DgIDGGS3H.h:27)
==13831==    by 0x2817A8CC: DgIDGGS::makeRF(DgRFNetwork&, DgGeoSphRF const&, DgGeoCoord const&, long double, unsigned int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool, int, bool) (DgIDGGS.cpp:48)
==13831==    by 0x281EA8CD: dglib::GridThing::init(long double, long double, long double, unsigned int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (dglib.cpp:109)
==13831==    by 0x281EC9D5: dglib::GridThing::GridThing(long double, long double, long double, unsigned int, int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (dglib.cpp:96)
==13831==    by 0x281C3DA8: GridStat_nCells(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int) (Rwrapper.cpp:74)
==13831==    by 0x281D4792: Rcpp::CppFunction4<double, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, int>::operator()(SEXPREC**) (Module_generated_CppFunction.h:407)

along with many potential issues at exit.

These do not appear to materially affect operation and should be fixed upstream.

Polygon boundary errors in diamond grid

There seems to be some error in calculating the boundary polygon at resolution 2 and higher in the diamond grid. (Please see attached image) Red lines are resolution 2, Green lines are resolution 1. Higher resolutions exhibit a similar issue.
image

When I manually calculate the midpoint of the great circle arc between vertexes of the resolution 1 diamond, I get the following result. Yellow pin is my manually calculated mid point of the edge.

image

I'm guessing this is an error in the linked DGGS library itself, but I can't seem to find a github repository for that library. I used the contact page at discreteglobalgrids.com to try and alert them to the issue as well, but not sure if the people running the site are the same people maintaining the DDGS library.

develop package website with pkgdown

In order to make dggridR even more easily accessible it could be interesting to develop its own website using pkgdown.
(It could be automatically built and served on GitHub pages via CI tools like TravisCI as explained in pkgdown)

Two pentagons cells

Hi Richard,

Would it be possible to explain why there are two non hexagonal cell will display when I run your code please! you can find one above the south pole.

Thanks

Vignette not available

Hello,

After installing the package using install_github('r-barnes/dggridR', build_vignettes = TRUE) I get this error
Error in loadVignetteBuilder(pkgdir, TRUE) :
vignette builder 'R.rsp' not found
Execution halted
Error: Failed to install 'dggridR' from GitHub:
System command 'R' failed, exit status: 1, stdout + stderr:

Following your recommendation of using install_github('r-barnes/dggridR', vignette=TRUE) the error is vignette 'dggridR' not found.

I think there is an issue with building the vignette.

Cell sequences in geographic objects

I am aware of two different kinds of cartographic objects that can be obtained from a DGG with dggridR:

  1. Cell centres, obtained with something like:
dggs <- dgconstruct(res=3)
allSeqs <- seq(1, dgmaxcell(dggs))
cellCentres <- dgSEQNUM_to_GEO(dggs, allSeqs)
  1. Cell polygons, that can be saved to disk with:
dggs <- dgconstruct(res=3)
allSeqs <- seq(1, dgmaxcell(dggs))
dgcellstogrid(dggs, allSeqs, frame=FALSE, savegrid="./cells.shp")

In neither case are the cell sequences kept with the object. cellCentres is an array of two lists (one for longitude and another for latitude), the shapefile saved to disk does not have attributes.

It is possible to merge cell sequences and the centres' coordinates into a single data.frame object, however, there is no way of knowing if the order is the same across these objects:
df.cellCentres <- data.frame(allSeqs, cellCentres[[1]], cellCentres[[2]])

Is there any formal way of obtaining the cells sequences for any of these objects? Can the data.frame example above be trusted?

Any wrapper for python?

Hi,
I noticed that the main library is in c++, so is there any possibility to work on a wrapper for python?I have experience working on python but I have not written wrappers for c++ libraries. Is it even possible to have a try?

Add a cell column to spatial output of dgcellstogrid() and dgearthgrid()

When called with frame = TRUE, both dgcellstogrid() and dgearthgrid() return a data frame with a cell column that's useful for joining to other data. However, when frame = FALSE is used a SpatialPolygons object is returned that doesn't provide a way to connect which cell number corresponds to each polygons. These functions would be much more useful if they returned SpatialPolygonsDataFrame objects with the cell number.

suggestion: include sinusoidal binning scheme

I wonder if you'd be interested to include the binning scheme used by the ocean colour group for L3?

This scheme is described here: http://oceancolor.gsfc.nasa.gov/cms/L3Bins.html

I've implemented it in simple form here, but I didn't finish the rounding out like you have in this package:
https://github.com/mdsumner/roc/blob/master/R/bins.R

It would be easy to use your grid-table approach to make these easier to work with, so that's something I'll try anyway - but it might be one to include here?

I've put the format in as a feature request to GDAL, it could be simply read in as a non-spatial table: https://trac.osgeo.org/gdal/ticket/6551 (programming the NetCDF for this format is painful but the GDAL tools are almost doing all the work already)

plotting problems

Trying to plot a grid over the coterminous United States, and I'm getting plots that appear to be buggy:

library(dggridR)
library(sf)
library(ggplot2)
dg6 <- dgconstruct(res=6)

# A hack to determine all grid cells that overlap the continuous US.
# Surely there's a better way...
conus <- spData::us_states
conus_raster <- fasterize::fasterize(conus,
                                     raster::raster(ncol=1000, nrow = 1000, 
                                                    xmn = -125, xmx = -66, 
                                                    ymn =24, ymx = 50))
conus_coords <- raster::as.data.frame(conus_raster, xy = T)
conus_coords <- conus_coords[!is.na(conus_coords$layer), ]
conus_cells <- unique(dgGEO_to_SEQNUM(dg6, conus_coords$x, conus_coords$y)[[1]])
length(conus_cells)

# Need to submit an issue against dggridR for the below:
grid <- dgcellstogrid(dg6, conus_cells)
p <- ggplot() + geom_sf(data = conus) + 
                geom_path(data = grid, aes(x = long, y = lat))
p

# This hack works for now
p <- ggplot() + geom_sf(data = conus, fill = "gray50", col = "gray50")
pb <- txtProgressBar(min = 1, max = length(conus_cells), initial = 1, style = 3)
for (i in seq_along(conus_cells)) {
  setTxtProgressBar(pb, i)
  grid <- dgcellstogrid(dg6, conus_cells[i])
  p <- p + geom_path(data = grid, aes(x = long, y = lat), 
                     col = "black", alpha = .3) +
           geom_polygon(data = grid, aes(x = long, y = lat), 
                     col = "goldenrod", alpha = .3)
    
}
p

The first plotting attempt yields

Rplot

Problem with dgshptogrid

Hi,
First of all: Thanks for implementing this package in R. It was exactly what I was searching for and the package looks great.
Unfortunately, I have a problem with with dgshptogrid function.

I was able to construct this small example, which should illustrate my problem.

library(dggridR)

temp.polygon <- Polygon(rbind(c(30.658062, -30.454239), c(18.423378, -34.326279), c(9.700586,   4.082381), c(-8.244678,   4.574364), c(-16.291415,  16.988192), c(33.059410,  19.501835), c(46.730717,  10.781729), c(30.658062, -30.454239)))

temp.polygons <- Polygons(list(temp.polygon),1)
temp.spatialpolygons <- SpatialPolygons(list(temp.polygons))

sp_df <- SpatialPolygonsDataFrame(temp.spatialpolygons, data.frame(ID = 1))

In order to use this polygone, I save it as shapefile in my working directory

writeOGR(sp_df, "./", "sp_df_shp", driver = "ESRI Shapefile")

Then, I try to use dgshptogrid as shown in the example in ?dgshptogrid

dggs      <- dgconstruct(spacing = 25, metric = FALSE, resround = 'nearest')
new_grid <- dgshptogrid(dggs, "./sp_df_shp.shp")

ERROR: polygon intersects quad #2 but a vertex of that polygon is more than 90' from the quad center.
polygon is:
WGS84_AUTHALIC_SPHERE {
WGS84_AUTHALIC_SPHERE{(30.6581, -30.4542)}
WGS84_AUTHALIC_SPHERE{(46.7307, 10.7817)}
WGS84_AUTHALIC_SPHERE{(33.0594, 19.5018)}
WGS84_AUTHALIC_SPHERE{(-16.2914, 16.9882)}
WGS84_AUTHALIC_SPHERE{(-8.24468, 4.57436)}
WGS84_AUTHALIC_SPHERE{(9.70059, 4.08238)}
WGS84_AUTHALIC_SPHERE{(18.4234, -34.3263)}
WGS84_AUTHALIC_SPHERE{(30.6581, -30.4542)}
}

FATAL ERROR: break-up polygon or reorient grid
running command '/Library/Frameworks/R.framework/Versions/3.4/Resources/library/dggridR/bin/dggrid /var/folders/gy/4bhc8q_s2nbf72h98zxybz2h0000gn/T//Rtmp8SlW0X/dggridR-8a077e36d8b.meta' had status 1

I'm fairly new to geometry and mapping, and the answer might be obvious for other people, therefore I would highly appreciate any help what I have to change.

Another small problem concerns the example for the dgshptogrid-function. The path stored in

dg_shpfname_south_africa

is

[1] "/Volumes/XT3/Builds/R-dev-web/QA/Simon/packages/el-capitan-x86_64/Rlib/3.4/dggridR/extdata/ZAF_adm0.shp"

At least in RStudio running on a Mac with macOS Sierra, this path doesn't work. However, the example worked after I downloaded the shapefile from Github and saved it locally in my working directory.

Thanks a lot,
Urs

Save Hexagon into shape file

Using dggridR to save the Hexagon grids into shape file to be used in ArcMap, Cells which cross -180/180 degrees can present difficulties for plotting, As a result, such
cells will have components in the range [180,360) can you please let me know how to disconnect these grids?

code

library(dggridR)
dggs_test <- dgconstruct(res=20)
res <- dg_closest_res_to_spacing(dggs_test,spacing=1000,round='down',metric=TRUE)
dggs_test <- dgsetres(dggs_test,res)
grid_issam <- dgearthgrid(dggs_50,savegrid="D:/New_R/shp/temp8.shp") #Save directly to a file
gridsas <- as(dggs_50, "SpatialPolygonsDataFrame")

Hexagon_DGGS_5

Some insights on how to plot dggridR grids on a earth sphere?

Hi,

I downloaded and installed dggridR, and I am very pleased about how easy it was to install and summarize my data in a grid.

My next problem is plotting though and it probably due to my lack of experience with Geodesic Discrete Global Grid Systems, but could there be some example code in the README.md to show how to plot the second figure ("You data could look like this")?

/David

dg_process_polydata in dggridR.R

When setting wrapcells=TRUE for this function call, the logic alters polygons that span a longitude of more than 180 degrees. This works most of the time, except for cells that either contain or have a vertex or edge that lies on either the north or south pole.

I think groups_to_wrap needs to exclude any polygon groups that lie on or include (90, 0) and (-90, 0).

Increasing the diff filter will not be a solution to all edge cases.

Suggestion: Output grids as polygons.

Hi there

Really great package, I've been using global grids for analysis of ecological data for a few years so this is a fantastic tool. I wonder whether it would be possible to add the function to generate a polygon of the grids as an output. I've spent a few days trying to generate these from the polylines (and the underlying point data) but polylines that cross the meridian for some reason double back on themselves so you end up with a set of polygons with huge areas, effectively spanning the globe. I will keep having a fiddle with it and if I manage to code this up I will get in touch, but otherwise perhaps a function for a future release.

All the best

Rob Holland

Issues in ArcGIS Pro 3D map.

image
image
image
When I use shape for 3D map in ArcGIS pro, top and bottom are not correct and there are long line.
How to fix this issue?

this is my code.

library(dggridR)
dggs_test <- dgconstruct(res=25)
res <- dg_closest_res_to_spacing(dggs_test,spacing=50,round='down',metric=TRUE)
dggs_test <- dgsetres(dggs_test,res)
global <- dgearthgrid(dggs_test, frame=FALSE)
global.cell <- data.frame(cell=getSpPPolygonsIDSlots(global), row.names=getSpPPolygonsIDSlots(global))
global <- SpatialPolygonsDataFrame(global, global.cell)
for(i in 1:length(global@polygons)) {
  if(max(global@polygons[[i]]@Polygons[[1]]@coords[,1]) - 
     min(global@polygons[[i]]@Polygons[[1]]@coords[,1]) > 270) {
    global@polygons[[i]]@Polygons[[1]]@coords[,1] <- (global@polygons[[i]]@Polygons[[1]]@coords[,1] +360) %% 360
  }
}

writeOGR(global, "D:/", "global", driver = "ESRI Shapefile")

dgearthgrid broken in R 4.0.0

The following works fine in R 3.6.3, but fails in R 4.0.0:

dggs <- dgconstruct(res = 6)
grid <- dgearthgrid(dggs, frame = TRUE)

The error says that it can't find the function GlobalGrid.

dgearthgrid creates artifacts in SpatialPolygonsDataFrame

When creating a normal data.frame with dgearthgrid for use with ggplot, the results are fine:

library(dggridR)
dggs <- dgconstruct(res = 6)
grid <- dgearthgrid(dggs, frame = TRUE)
ggplot(grid) +
  aes(long,lat,group=group) +
  geom_polygon() +
  geom_path(color="white")

image

And if I then convert that to a SpatialPolygonsDataFrame and tidy it up for ggplot, still fine:

grid_list <- split(grid[,c("long","lat")], grid$group)
ps <- sapply(grid_list, Polygon)
p1 <- lapply(seq_along(ps), function(i) Polygons(list(ps[[i]]), ID = names(grid_list)[i]))
grid_list_polys <- SpatialPolygons(p1, proj4string = CRS("+proj=longlat +datum=WGS84"))
grid_list_polys_df <- SpatialPolygonsDataFrame(grid_list_polys, data.frame(id = names(grid_list), row.names = names(grid_list)))
ggplot(tidy(grid_list_polys_df)) +
  aes(long,lat,group=group) +
  geom_polygon() +
  geom_path(color="white")

image

But if I use dgearthgrid with frame = FALSE, it introduces artifacts into the SpatialPolygonsDataFrame:

grid <- dgearthgrid(dggs, frame = FALSE)
grid <- as(grid, "SpatialPolygonsDataFrame")
ggplot(tidy(grid)) +
  aes(long,lat,group=group) +
  geom_polygon() +
  geom_path(color="white")

image

Furthermore, it's also an invalid spatial object:

rgeos::gIsValid(grid)
# returns FALSE due to self-intersection

package citation

The vignette says: "Please cite this package as: Richard Barnes (2016). dggridR: Discrete Global Grids for R. https://github.com/r-barnes/dggridR." However,

> citation("dggridR")

To cite packagedggridRin publications use:

  Richard Barnes (2016). dggridR: Discrete Global Grids for R. R
  package version 0.1.11. https://CRAN.R-project.org/package=dggridR

A BibTeX entry for LaTeX users is

  @Manual{,
    title = {dggridR: Discrete Global Grids for R},
    author = {Richard Barnes},
    year = {2016},
    note = {R package version 0.1.11},
    url = {https://CRAN.R-project.org/package=dggridR},
  }

You could add a CITATION file to the package, but I'd suggest to go for the canonical (default) citation, since google scholar tends to pick these up.

missing cells when creating a small-scale grid (~10 km or less spacing)?

I'm using dggridR to create a grid across the state of Wisconsin, and when I go to plot the hexagons overlaid on the state border I've noticed that some cells seem to disappear when I use a finer spatial scale (say ~15 km vs ~10 km):

library(dggridR)
library(tidyverse)
library(rnaturalearth)
library(sf)
library(patchwork)

# create WI border shapefile
wi_border <- ne_states(country = 'united states of america', returnclass = 'sf') %>%
  filter(postal == c('WI')) %>%
  st_union() %>%
  write_sf(str_c(tempdir(), '/', 'wi.shp')) # save to shapefile


# ~15 km cells ------------------------------------------------------------

# generate a dggs specifying an intercell spacing of ~15 km
dggs <- dgconstruct(spacing = 15, metric = TRUE)

# use dggs, WI border to generate hexagon grid
wi_grid <- dgshptogrid(dggs, str_c(tempdir(), '/', 'wi.shp'), frame = FALSE)

# convert to sf
wi_grid <- wi_grid %>%
  st_as_sf()

# read in WI border from the shapefile
wi_border <- read_sf(dsn = str_c(tempdir(), '/', 'wi.shp'))

# plot WI border and the associated grid
p1 <- ggplot() + 
  geom_sf(data = wi_border, fill = 'white', color = "black")   +
  geom_sf(data = wi_grid, color = 'white', fill = "blue", alpha = 3/10, size = 0.5)  +
  theme_minimal() +
  ggtitle('~15 km spacing')


# ~10 km cells -------------------------------------------------------------------

# generate a dggs specifying an intercell spacing of ~10 km
dggs <- dgconstruct(spacing = 10, metric = TRUE)

# use dggs, WI border to generate hexagon grid
wi_grid <- dgshptogrid(dggs, str_c(tempdir(), '/', 'wi.shp'), frame = FALSE)

# convert to sf
wi_grid <- wi_grid %>%
  st_as_sf()

# plot WI border and the associated grid
p2 <- ggplot() + 
  geom_sf(data = wi_border, fill = 'white', color = "black")   +
  geom_sf(data = wi_grid, color = 'white', fill = "red", alpha = 5/10, size = 0.5)  +
  theme_minimal() +
  ggtitle('~10 km spacing')


# plot both ---------------------------------------------------------------

p1 + p2

Rplot01

Not sure if this is stemming from dgconstruct or dgshptogrid, or if it is happening during the plotting process.

Thanks,

Jay

installation failed

It seems that is not possible to install diggridR on R 4.0
install.packages('dggridR') Installiere Paket nach ‘/home/R/x86_64-pc-linux-gnu-library/4.0’ (da ‘lib’ nicht spezifiziert) Warnmeldung: package ‘dggridR’ is not available for this version of R
and
install_github('r-barnes/dggridR', vignette=TRUE)
or
install_github('r-barnes/dggridR')
gave some error:
`g++ -std=gnu++11 -I"/usr/share/R/include" -DNDEBUG -I'/usr/local/lib/R/site-library/Rcpp/include' -fpic -g -O2 -fdebug-prefix-map=/build/r-base-fhxXXR/r-base-4.0.4=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -c util.cpp -o util.o
g++ -std=gnu++11 -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o dggridR.so DgAddressBase.o DgBase.o DgBoundedHexC2RF2D.o DgBoundedIDGG.o DgBoundedIDGGS.o DgBoundedRF2D.o DgBoundedRFS2D.o DgCell.o DgColor.o DgConverterBase.o DgDVec2D.o DgDVec3D.o DgDiscRFS2D.o DgDistanceBase.o DgDmdD4Grid2D.o DgDmdD4Grid2DS.o DgDmdD8Grid2D.o DgDmdD8Grid2DS.o DgEllipsoidRF.o DgGeoSphRF.o DgHexC1Grid2D.o DgHexC2Grid2D.o DgHexGrid2DS.o DgIDGG.o DgIDGGS.o DgIDGGS3H.o DgIDGGS43H.o DgIDGGS4D.o DgIDGGS4H.o DgIDGGS4T.o DgIVec2D.o DgIVec3D.o DgIcosaMap.o DgInAIGenFile.o DgInLocTextFile.o DgInShapefile.o DgInShapefileAtt.o DgInputStream.o DgLocBase.o DgLocList.o DgLocVector.o DgLocation.o DgOutAIGenFile.o DgOutGeoJSONFile.o DgOutKMLfile.o DgOutLocFile.o DgOutLocTextFile.o DgOutPtsText.o DgOutRandPtsText.o DgOutShapefile.o DgOutputStream.o DgParamList.o DgPolygon.o DgProjFuller.o DgProjGnomonicRF.o DgProjISEA.o DgProjTriRF.o DgRFBase.o DgRFNetwork.o DgRandom.o DgSeriesConverter.o DgSqrD4Grid2D.o DgSqrD4Grid2DS.o DgSqrD8Grid2D.o DgSqrD8Grid2DS.o DgSuperfund.o DgTriGrid2D.o DgTriGrid2DS.o DgUtil.o RcppExports.o Rwrapper.o adjlon.o clipper.o dbfopen.o dglib.o hypot.o pj_auth.o pj_mlfn.o pj_msfn.o pj_phi2.o pj_qsfn.o pj_tsfn.o safileio.o sbnsearch.o shpopen.o shptree.o util.o -L/usr/lib/R/lib -lR
installing to /home/R/x86_64-pc-linux-gnu-library/4.0/00LOCK-dggridR/00new/dggridR/libs
** R
** data
** inst
** byte-compile and prepare package for lazy loading
free(): invalid pointer
Aborted (core dumped)
ERROR: lazy loading failed for package ‘dggridR’

  • removing ‘/home/R/x86_64-pc-linux-gnu-library/4.0/dggridR’
    Fehler: Failed to install 'dggridR' from GitHub:
    (konvertiert von Warnung) installation of package ‘/tmp/RtmpGc4tc6/fileafbe56af62a6/dggridR_2.0.8.tar.gz’ had non-zero exit status`

Is there a chance to fix ist?

FATAL ERROR: coordinate out of range on M1 mac

I'm having some issues on an M1 mac which I did not have on an Intel mac. In particular, dgGEO_to_SEQNUM() often results in the following error:

> dggs <- dgconstruct(spacing = 1000, metric = FALSE, resround = "down")
Resolution: 3, Area (mi^2): 1173851.79791229, Spacing (mi): 843.496246531418, CLS (mi): 964.285490648183
> dgGEO_to_SEQNUM(dggs, 23, 35)$seqnum
FATAL ERROR: DgQ2DDtoIConverter::convertTypedAddress():  coordinate out of range: (3, 9)
[1] 67

Also, this is what I get when I try the example in the vignette. Note the overlapping polygons west of Chile and between South Africa and Antarctica.

grid

Session info:

R version 4.1.2 (2021-11-01)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Monterey 12.3

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods  
[7] base     

other attached packages:
[1] ggplot2_3.3.5 dggridR_3.0.0 sp_1.4-6      sf_1.0-7     
[5] rlang_1.0.2   dplyr_1.0.8  

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.8.3       pillar_1.7.0       compiler_4.1.2    
 [4] prettyunits_1.1.1  remotes_2.4.2      class_7.3-19      
 [7] tools_4.1.2        digest_0.6.29      pkgbuild_1.3.1    
[10] gtable_0.3.0       lattice_0.20-45    lifecycle_1.0.1   
[13] tibble_3.1.6       pkgconfig_2.0.3    cli_3.2.0         
[16] DBI_1.1.2          rstudioapi_0.13    curl_4.3.2        
[19] e1071_1.7-9        s2_1.0.7           withr_2.4.3       
[22] maps_3.4.0         generics_0.1.2     vctrs_0.4.0       
[25] grid_4.1.2         classInt_0.4-3     rprojroot_2.0.2   
[28] tidyselect_1.1.2   glue_1.6.2         R6_2.5.1          
[31] processx_3.5.2     fansi_1.0.3        farver_2.1.0      
[34] callr_3.7.0        purrr_0.3.4        magrittr_2.0.3    
[37] scales_1.1.1       units_0.8-0        ps_1.6.0          
[40] ellipsis_0.3.2     assertthat_0.2.1   colorspace_2.0-2  
[43] labeling_0.4.2     utf8_1.2.2         KernSmooth_2.23-20
[46] proxy_0.4-26       wk_0.6.0           munsell_0.5.0     
[49] crayon_1.5.1      

Can dggridR output neighbors of each cell?

Dear Richard,

I am aware that DGGRID can output neighbors of cells by setting parameters "neighbor_output_***" in the Metafile

I wonder can dggridR output neighbors of each cell? How to do it?

I checked all the files of dggridR and didn't find the answer.

Thank you very much, for your fantastic algorithms!

Best regards,
Langping

Add cell centers

For certain applications it would be good to be able to retrieve the centers of grid cells. For example when looking at connectivity networks. It also would be quicker to work with the high resolution data when the points could be a good approximation of the full grid. The grid cell centers are as far as i know generated and reported in the .gen files (e.g http://webpages.sou.edu/~sahrk/dgg/isea.old/gen/isea3h.html )

R versions supported

Documentation does not mention R versions supported, and it did not worked with Ubuntu 17.04 R package (version: 3.3.2). I ended up upgrading R version to 3.4.1 from a CRAN mirror.

Quad Tree Index Improvements

One advantage of the aperture 4 diamond grid is it's analogous relationship to the quad tree data structure. However the Q2DI and Q2DD indexing scheme seems to leave a bit to be desired in terms of being able to traverse the tree both horizontally (for example when crossing over one of the edges of one of the ten lowest resolution diamonds) and vertically (trying to discern parent/child relationships among nodes).

I've wrapped some of the dggridR functions to build out some basic tree traversal - getting neighbors, parents, children, etc involving a bunch of calls to dgGEO_to_Q2DI and dgQ2DI_to_SEQNUM to get it to work with dgcellstogrid. However, perhaps the package could be improved by making this logic more straightforward by building it into the index itself by including list elements for parent, children, and neighbors?

I think it would also be helpful to users to have a tree traversal example added to the readme. Would it be worthwhile for me to work on a pull request to add these elements?

Error in `example(dgearthgrid)`

library(dggridR)
dggs <- dgconstruct(res=20)
res  <- dg_closest_res_to_spacing(dggs,spacing=1000,round='down',metric=FALSE)
dggs <- dgsetres(dggs,res)
gridfilename <- dgearthgrid(dggs,savegrid=TRUE) #Save directly to a file

fails in forthcoming rgdal on is.character(dsn) because savegrid=TRUE, which is not what the docs say:

#' @param savegrid  If savegrid is set to a file path, then a shapefile 
#'                  containing the grid is written to that path and the filename
#'                  is returned. No other manipulations are done.
#'                  Default: NA (do not save grid, return it)

suggestion: Give relative coordinates of lat-long within a cell

Given a lat-long, I can get a cell address. It would be cool to get it's relative location in the cell after the projection. For example, let's assume the shape exists in an x-y plane and the centroid of a shape is the origin. We could also always assume that a shape is a constant size, regardless of the actual scale, say inscribed in the unit circle. Then I might have a point go from a given lat long to cell 1432 with relative coordinate (-0.24, 0.4).

This doesn't appear to be functionality in the underlying dggrid, but when you move to another library, it would be very helpful to have if available.

Odd little issue moving from dgtransform -> dgGEO_to_SEQNUM

Wrapping up my first project using R and running into a minor issue I was a little puzzled by.

In my code, I have this:
circleFinal$cells <- dgtransform(dggs,circleFinal$lat,circleFinal$long)

Of course, I get this warning:
Warning messages: 1: In dgtransform(dggs, circleFinal$lat, circleFinal$long) : The 'dgtransform(dggs,lat,lon)' function has been deprecated. Please use ' dgGEO_to_SEQNUM(dggs,lon,lat)' instead! NOTE THE ARGUMENT ORDER!

So I change it to this:
circleFinal$cells <- dgGEO_to_SEQNUM(dggs, circleFinal$long, circleFinal$lat)

And now I get this error when that line is processed:
Error in max(cells) : invalid 'type' (list) of argument

I must be missing something dead simple, right? dggridR version is 2.0.2 from this repository.

Figured I'd share a little about what I did after starting from scratch yesterday at 6pm...

Discovered and started using R + dggridR yesterday evening after I had the need to overhaul a grid system I previously put together with turfJS and my rectangular grid system was proving wildly inconsistent in generating grids for cities around the world. After an all nighter I have it fully integrated and automating grid generation for my app.

Many thanks to Richard Barnes and Kevin Sahr for their work on dggrid! This makes up for all the math courses I never took beyond Calc II 👍

dgshptogrid produces invalid output below res=11

Hi! I've been testing dgshptogrid out for an area of interest and it seems to be producing some invalid outputs once I get below res=11. Here's an example of what I'm doing:

dggs <- dgconstruct(res=15)
hall_grid <- dgshptogrid(dggs, 'C:/data/HallArea.shp', savegrid='C:/data/res15.shp')

Here's a screenshot of the output I'm getting:

image

I'm not sure if the problem is with what I'm doing, what the R library does or if there's a problem inside of DGGRID itself.

Discrete grid using earthquake data

Dear Richard.

I was looking at the example of creating a discrete grid using earthquake data. I have 3 questions regarding how to obtain additional information:

  1. In the example provided, hexagons where there was an earthquake are extracted and nicely visualized. This is done with the following code:

#Get the number of earthquakes in each cell
quakecounts <- dgquakes %>% group_by(cell) %>% summarise(count=n())

#Get the grid cell boundaries for cells which had quakes
grid <- dgcellstogrid(dggs,quakecounts$cell,frame=TRUE,wrapcells=TRUE)

#Update the grid cells' properties to include the number of earthquakes
#in each cell
grid <- merge(grid,quakecounts,by.x="cell",by.y="cell")

My consult is as follows. I'd like to know how to get the coordinates of hexagons (cells) where there was no record of earthquakes. I'd also like to visualize those hexagons (cells). Imagine that we want to show the safest places on earth, understood as those cells where there was no record of earthquakes. How can I compute and visualize this information using earthquake data example.

  1. My second question is about the "grid" object previously generated (the set of grid cell boundaries). According to my understanding, this object contains the coordinates of each cell (i. e. hexagon). When observing each cell it is characterized by latitude and longitude values. I also noticed that the "order" column generates 7 values for each cell. What do these 7 values mean? My expectation was to find 6 values and not 7 values for each cell. Maybe I miss something.

  2. The last question is how best to calculate the centroid of each cell (without introducing unexpected bias or distortions). What would you recommend?

Again, thank you very much for making this important R package freely available.

Best, Victor

dggridR back on CRAN

I just noticed dggridR has been archived, any intention of getting it back on CRAN?

Error running dggrid.exe

Hi,

I'm trying to run dgshptogrid on a Windows machine with R3.4.1.
I've downloaded a Shapefile from Belgium and checked it using ogrinfo from gdalutils package.

ogrinfo(dg_shpfname_belgium)
[1] "INFO: Open of D:/projects/be_1km.shp'" [2] " using driver ESRI Shapefile' successful."
[3] "1: be_1km (Polygon)"

However, when I try to generate a grid within the Shapefile using:
dggs <- dgconstruct(spacing=25, metric=TRUE, resround='nearest')
sa_grid <- dgshptogrid(dggs,dg_shpfname_belgium,frame=TRUE)

I get the error:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open data source
In addition: Warning message:
running command 'C:/Users/msanders1/Documents/R/win-library/3.4/dggridR/bin/dggrid.exe C:\Users\MSANDE~1\AppData\Local\Temp\Rtmpw9AUrF\dggridR-1f44dd44cda.meta' had status 1

The tempfolder exists, but the meta file does not exist. A kml-file is generated.
Could someone explain what I'm doing wrong and how to solve this issue?
Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.