A cell is within d_km of a source cell when the great-circle (haversine, R = 6371.0088 km)
distance between the two CELL CENTRES is at most d_km. For each source cell the candidates are
a window of rows (+- ceiling(d / row height) + 1) and columns (the exact longitude reach of a
d_km cap at the source latitude, asin(sin(d/R) / cos(lat)); every column when the cap holds
a pole), the column index wrapping modulo nc (so a cell at 179.975 E reaches the cells at
-179.975) and the rows clipped at the poles; the haversine filter then decides. The grid is
cell_id = row * nc + col + 1, row 0 at ymax (90 N), col 0 at xmin (-180), deg per cell –
global05 by default (grid_spec_for("global05")), any regular global grid by argument.
Arguments
- src
character; a relation with a
cell_idcolumn and, optionally, the grouping columnby(e.g.mdl_key): the result is distinct(by, cell_id).- d_km
numeric; the distance, km (> 0).
- by
character or
NULL; the grouping column ofsrccarried through.- nc, nr
integer; the grid's columns and rows (7200 x 3600).
- deg
numeric; the cell size in degrees (0.05).
nc * degmust be 360 andnr * deg180.
Examples
cat(cells_within_sql("src_cells", 100))
#> WITH s AS (
#> SELECT cell_id,
#> (CAST(cell_id AS BIGINT) - 1) // 7200 AS r0, (CAST(cell_id AS BIGINT) - 1) % 7200 AS c0,
#> 90 - ((CAST(cell_id AS BIGINT) - 1) // 7200 + 0.5) * 0.05 AS lat0,
#> -180 + ((CAST(cell_id AS BIGINT) - 1) % 7200 + 0.5) * 0.05 AS lon0
#> FROM src_cells),
#> w AS (
#> SELECT *, CASE WHEN sin(100 / 6371.0088) / cos(radians(lat0)) >= 1 THEN 7200
#> ELSE CAST(ceil(degrees(asin(sin(100 / 6371.0088) / cos(radians(lat0)))) / 0.05) AS INTEGER) + 1 END AS dcm
#> FROM s),
#> cand AS (
#> SELECT lat0, lon0, r0 + dr AS r1, ((c0 + dc) % 7200 + 7200) % 7200 AS c1
#> FROM w, range(-19, 19 + 1) a(dr),
#> generate_series(-least(dcm, 3600), least(dcm, 3600)) b(dc)
#> WHERE r0 + dr BETWEEN 0 AND 3599),
#> cand2 AS (
#> SELECT lat0, lon0, r1, c1,
#> 90 - (r1 + 0.5) * 0.05 AS lat1, -180 + (c1 + 0.5) * 0.05 AS lon1
#> FROM cand)
#> SELECT DISTINCT CAST(r1 * 7200 + c1 + 1 AS INTEGER) AS cell_id
#> FROM cand2
#> WHERE 2 * 6371.0088 * asin(sqrt(least(1,
#> pow(sin(radians(lat1 - lat0) / 2), 2) +
#> cos(radians(lat0)) * cos(radians(lat1)) * pow(sin(radians(lon1 - lon0) / 2), 2)))) <= 100