AbelVM
8/23/2018 - 11:08 AM

ST_KDensity: a simple spatial kernel density function for PostGIS

ST_KDensity: a simple spatial kernel density function for PostGIS

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.

ST_KDensity: a simple spatial kernel density function for PostGIS

by Abel Vázquez

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
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;