I'm trying to speed up an ST_MapAlgebra callback function that essentially takes a raster with four bands, checks each band for values less than a given number, and where the check is true, return the fourth band.
This is my messy function:
create or replace function
callback_fn(pixel float[], pos integer[], variadic userargs text[])
returns float
language plpgsql
immutable
as $$
declare
roaddist float;
protected_area float;
citydist float;
return_val float;
begin
citydist := pixel[1][1][1];
roaddist := pixel[2][1][1];
protected_area := pixel[3][1][1];
return_val := pixel[4][1][1];
if protected_area = 1 then return null;
end if;
if citydist <= 2000 then return return_val;
elsif roaddist <= 500 then return return_val;
else return null;
end if;
end;
$$;
So from what I understand, the function above will go through every pixel and either return the "return_val" or it will return NULL. So what I end up with is basically a single band raster with excluded areas removed.
This is exactly what I want, but I was hoping to run this faster. Is there a way to run multiple pixels simultaneously instead of going through each one individually? I'm confused why ST_Reclass can run so quickly to reclassify a whole raster while ST_MapAlgebra seems to take so much longer when (in my mind, at least) the functions are doing similar things - checking the values of a raster and where true, change value, otherwise set null. Is there a way to use ST_Reclass in a callback function to speed up this process?
Additionally, is there a good source for documentation on writing PostGIS raster callback functions? I have been googling a lot over the last few days and have found extremely meager examples.