Passing Arguments to Map Algebra Callbacks

2017-03-30
database

Goal

The docs say that we can pass additional arguments to ST_MapAlgebra callbacks, but how do we actually do that?

In this post, I’ll show you how to pass additional arguments (the VARIADIC arguments referred to by the text array called userargs in the documentation) to ST_MapAlgebra callbacks in PostGIS.

Purpose

I had some problems with this while I was writing my post on simulating multi-band rasters, and the docs leave something to be desired.

I ended up asking about it on GIS Stack Exchange, and this post is my attempt to boost that answer.

The Answer

Thanks to Pierre Racine, one of the creators of PostGIS, we have the answer! As he demonstrates in this example:

1
2
3
4
5
6
7
8
9
10
11
12
ST_MapAlgebra(b1.rast, -- raster to operate on
1, -- band
'generate_random_raster(double precision[], integer[], text[])'::regprocedure, -- custom function signature
pixeltype, -- can be null
extenttype, -- can be null
customextent, -- can be null
distancex, -- can be null
distancey, -- can be null
firstextraargument,
secondextraargument,
...
)

Here’s how it looks in my use case:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
SELECT
ST_AddBand(b1.rast, -- torast
ST_MapAlgebra(b1.rast,
1,
'generate_random_int_raster(double precision[][][], integer[][], text[])'::regprocedure,
'8BUI'::text, --pixeltype
null, -- extenttype
null, -- customextent
null, -- distancex
null, -- distancey
'3'::text, -- firstextraargument
'1'::text, -- secondextraargument
'TRUE'::text -- third extra argument
), -- fromrast
1, -- Target FROM band (band one of fromrast)
2 -- Target TO band (band two of torast)
)
AS rast
FROM starter AS b1;

Now, you might be thinking, “That’s exactly how the docs (jump to ‘35.4.5. SQL Functions with Variable Numbers of Arguments’) say you pass VARIADIC arguments, Nick!” And I read those too!

I don’t know why it didn’t work the first time I tried it, but as I explained on SE, I have a very strong suspicion it had something to do with my inexperience with PostGIS in general and how it works with double/single quotes in particular. I hope this helps you avoid the same problem.

If you’re interested in learning more about how you can use ST_MapAlgebra, check out my Raster Math Series.

If you’d like to see more about writing ST_MapAlgebra callbacks that accept userags, you can dig through these examples suggested by Pierre Racine, or this totally crazy but really cool one from Regina Obe on setting up the famous Game of Life in PostGIS.