Skip to content

Instantly share code, notes, and snippets.

@AbelVM
Last active November 3, 2023 16:09
Show Gist options
  • Save AbelVM/dc86f01fbda7ba24b5091a7f9b48d2ee to your computer and use it in GitHub Desktop.
Save AbelVM/dc86f01fbda7ba24b5091a7f9b48d2ee to your computer and use it in GitHub Desktop.
ST_KDensity: a simple spatial kernel density function for PostGIS

ST_KDensity: a simple spatial kernel density function for PostGIS

by Abel Vázquez

image

A simple function that brings to PostGIS the classic ESRI's Kernel Density function described at

https://pro.arcgis.com/en/pro-app/tool-reference/spatial-analyst/how-kernel-density-works.htm

and first translated into usable SQL by https://github.com/arredond

NOTE: it only works with points!

How to use it:

WITH
a AS(
	SELECT 
        array_agg(uniqueid) as ids, 
        array_agg(geom) as geoms 
    FROM 
        mydataset
)
SELECT
    b.*
FROM
    a,
    kernel_density(a.ids, a.geoms) b
The MIT License (MIT)
Copyright (c) 2018 Abel Vázquez Montoro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
CREATE OR REPLACE FUNCTION ST_KDensity(
ids bigint[],
geoms geometry[]
)
RETURNS TABLE(
id bigint,
geom geometry,
kdensity integer
)
AS $$
DECLARE
mc geometry;
c integer;
k numeric;
BEGIN
mc := ST_Centroid(ST_Collect(geoms));
c := array_length(ids, 1);
k := sqrt(1/ln(2));
RETURN QUERY
WITH
dist as (
SELECT
t.gid,
t.g,
ST_Distance(t.g, mc) as distance
FROM
unnest(ids, geoms) as t(gid, g)
),
md as (
SELECT
percentile_cont(0.5) WITHIN GROUP (ORDER BY distance) as median
FROM
dist
),
sd as (
-- https://pro.arcgis.com/en/pro-app/tool-reference/spatial-statistics/standard-distance.htm
SELECT
sqrt(
(
sum((ST_X(g)-ST_X(mc))^2) +
sum((ST_Y(g)-ST_Y(mc))^2)
)/ c
) as standard_distance
FROM
dist
),
sr as (
SELECT
0.9 * least(
sd.standard_distance,
k * md.median
) * c^(-0.2) as search_radius
FROM
sd, md
)
SELECT
gid as id,
g as geom,
kd::int as kdensity
FROM
sr,
dist as a,
LATERAL(
SELECT
count(*) as kd
FROM dist _b
WHERE ST_DWithin(a.g, _b.g, sr.search_radius)
) b;
END;
$$
LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
@dramael
Copy link

dramael commented Feb 19, 2019

Thx for the function.
U must change on pgadmin4 this segment...


  1. SELECT

  2.         sqrt(
    
  3.             (
    
  4.                 sum((ST_X(
    
  5.    				**ST_Centroid(g)**
    
  6.    			)-ST_X(
    
  7.    					**ST_Centroid(mc)**
    
  8.    			))^2) +
    
  9.                 sum((ST_Y(
    
  10.   				**ST_Centroid(g)**
    
  11.   			)-ST_Y(
    
  12. 						**ST_Centroid(mc)**
    
  13. 				))^2)
    
  14.             )/ c
    
  15.         ) as standard_distance
    

@amangeruca
Copy link

great

based on https://pro.arcgis.com/en/pro-app/latest/tool-reference/spatial-statistics/h-how-standard-distance-spatial-statistic-works.htm
i think you should modify it with this

SELECT sqrt( sum((ST_X(g)-ST_X(mc))^2) / c + sum((ST_Y(g)-ST_Y(mc))^2) / c ) ) as standard_distance FROM dist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment