-- Create the table that will contain the Kernel Density Estimation raster
DROP table if exists raster_table;
create table raster_table(
	rid serial,
	rast raster,
	CONSTRAINT raster_table_pkey PRIMARY KEY (rid)
);
-- Create an empty raster
insert into raster_table (rast)
(select st_makeemptyraster(195, 150, 503567.212147483, 200851.873341834, 300, -300, 0, 0, 27700));
-- Add a band to the empty raster
UPDATE raster_table
SET rast = ST_AddBand(rast, 1, '32BF', 0, 0) where rid=1;
-- Create a tempory table with KDE input points. The table has to be called "kde_points". The geometry column has to be called "geom" and the value of a point has to be called "count"
-- In this case, a point values is the number of data points which are snapped to a grid (10 meters resolution). Indeed, it makes the KDE operation faster. 
-- You can use the point values for a weighted KDE if you want.
-- My data table (crime_point2) is made of crimes with three attributes: crime_type (text), month (date) and location_proj(geometry)
DROP TABLE IF EXISTS kde_points;
DROP index IF EXISTS kde_points_index;
create table kde_points as(
select count(location_proj) as value, ST_SnapToGrid(location_proj, 10) as geom 
from crime_point2 
where crime_type='Vehicle crime'
and month='2012-01-01'
group by geom
);
create index kde_points_index on kde_points USING gist(geom);
-- Create the Kernel Density Estimation raster
-- First parameter is the bandwidth
-- Second parameter is the raster column
update raster_table set rast= __kde(1500, rast) where rid=1;