Map algebra with callbacks in PostGIS 2.1
I’ve been playing with the much-enhanced raster support in PostGIS 2.1 in the last few days. Amongst other things I’ve been producing maps with ST_MapAlgebra, which has changed a little since 2.0.
The example callback function in the documentation is somewhat unhelpfully bare-bones: it always returns 0, touching none of its arguments. So here’s an equally useless — but rather more informative — example of a callback function for the simple one-raster, one-band, one-pixel-at-a-time case:
create or replace function
callback_fn(pixel float[], pos integer[], variadic userargs text[])
returns float
language plpgsql
immutable -- careful: this function is immutable, yours may not be
as $$
declare
pixval float;
inputx integer;
inputy integer;
begin
pixval := pixel[1][1][1]; -- pixel indices: [raster #][xdistance][ydistance]
inputx := pos[1][1]; -- pos indices: [raster #][x = 1, y = 2]
inputy := pos[1][2]; -- (raster #0 is the output raster)
return pixval + inputx + inputy;
end;
$$;
-- example call:
select st_mapalgebra(rast, 1, 'callback_fn(float[], integer[], text[])'::regprocedure)
from raster_table;
And here’s something that caught me out: unless you’re passing some userargs, don’t declare your callback function to be strict. If you do, your callback function will never be called because its userargs argument is always null.
-
Ilia Choly