LazyExpression

LazyExpression

The @expression macro

Create a new LazyExpression and apply optimizations to it to reduce allocations and improve performance.

Expressions that do not depend on Parameters or other [LazyExpression]s are simply evaluated straight away.

Examples

Creating an expression that represents p * x1, where p is a parameter that always evaluates to 2:

julia> x1 = Variable(model);

julia> p = Parameter{Int}(() -> 2, model)
Parameter{Int64, …}(…)

julia> expr = @expression p * x1
LazyExpression{FunctionWrapper{…}(LazyExpression{typeof(*), …}(…))}(…)

julia> expr()
2 * x1

Creating an expression that represents p ⋅ x, where p is a parameter that evaluates to [1, 2] and x is a vector of two variables:

julia> model = Parametron.mock_model();

julia> x = Variable.(1 : 2);

julia> p = Parameter(model, val=[1, 2])
Parameter{Array{Int64,1}, …}(…)

julia> expr = @expression p ⋅ x
LazyExpression{FunctionWrapper{…}(LazyExpression{typeof(Parametron.Functions.vecdot!), …}(…))}(…)

julia> expr()
1 * x1 + 2 * x2 + 0

julia> @allocated expr()
0

Note that evaluating the expression does not allocate, because the ⋅ operation is optimized and transformed into a call to the in-place Functions.vecdot! function.

source

The LazyExpression type

struct LazyExpression{F, A}

Represents an expression that may be evaluated at a later time, by storing both a function, f, and a tuple of function arguments, args.

LazyExpressions are typically not manually constructed by a user, and hence are not exported. Instead, LazyExpressions should be created using the [@expression] macro.

A LazyExpression may be evaluated by simply calling it with no arguments.

Example

julia> a = ones(2); b = ones(2);

julia> expr = Parametron.LazyExpression(+, a, b)
LazyExpression{typeof(+), …}(…)

julia> expr()
2-element Array{Float64,1}:
 2.0
 2.0

julia> b .= 2
2-element Array{Float64,1}:
 2.0
 2.0

julia> expr()
2-element Array{Float64,1}:
 3.0
 3.0
source

Wrapping LazyExpressions

Parametron.wrapFunction.
wrap(expr)

Wrap a LazyExpression in a FunctionWrappers.FunctionWrapper and return a new LazyExpression with the FunctionWrapper as the function f and an empty tuple as the arguments arg.

The type parameters of the returned LazyFunction depend only on the type of the value returned by expr. This is useful when a common interface is needed for different LazyExpressions that share the same return value type.

source