#3069: Evaluate branches in r.mapcalc if-function only when needed

-------------------------------------------------+-------------------------

Reporter: wenzeslaus | Owner: grass-dev@…

Type: enhancement | Status: new

Priority: normal | Milestone: 7.3.0

Component: Raster | Version: svn-trunk

Keywords: r.mapcalc, r3.mapcalc, | CPU: Unspecified

optimization, expression, evaluation, if- |

statement, if-function |

Platform: Unspecified |

-------------------------------------------------+-------------------------

The ''r.mapcalc'' expression `x = if(0, rand(0, 2), 3)` takes about the

same time to evaluate as `x = rand(0, 2) + if(0, 2, 3)`, although the

true-branch of the if-statement is never used. As far as I understand,

this is given by fact that `if` is actually a function in ''r.mapcalc'',

so all the arguments are evaluated before the function is called.

It would be a nice enhancement if the values of if-function arguments

would be computed only when needed, i.e. `x = if(0, rand(0, 2), 3)` would

take same time as `x = if(0, 1, 3)` because `rand(0, 2)` is never used.

This would allow for some optimizations when part of the output raster is

already determined and there is no need to perform the computation, for

example a moving window calculation which needs to be performed only when

the central cell has a certain value. Another case when this would be

advantageous is when both branches (arguments) are costly to compute,

currently both are computed and one thrown away.

Here is the minimal example:

{{{

#!bash

g.region rows=10000 cols=10000

time r.mapcalc "x1 = rand(0, 2) + rand(0, 2) + rand(0, 2) + if(0, 2, 3)"

seed=1

time r.mapcalc "x2 = 2 + if(0, rand(0, 2) + rand(0, 2) + rand(0, 2), 3)"

seed=1

}}}

In both case, I get something like 14.5 s and for the expression with

trivial unused branch (`x = 2 + if(0, 2, 3)`) I get less than 6 s.

--

Ticket URL: <https://trac.osgeo.org/grass/ticket/3069>

GRASS GIS <https://grass.osgeo.org>