Produce objects with special meaning to gadget3

g3_native(r, cpp, depends = c())
g3_global_formula(f = ~noop, init_val = NULL)

Arguments

r

An R function to decorate with a 'C++' equivalent

cpp

Either:

  1. A character string containing the 'C++' equivalent as a Lambda function

  2. A character string containing 'C++' function template definition, calling the function __fn__

  3. A list of type-casts to use when calling an equivalently named native function

depends

A list of string names of dependent functions. The content of this and the initial [] for any Lambda function should match.

f

An optional formula to modify the content of a globablly-defined variable

init_val

An optiona formula to set the initial value of a globally-defined variable

Details

These functions are generally for gadget3 development, but made available so actions can be produced outside the package.

Value

g3_native

Returns a function that can be used in formulas for both R and TMB-based models.

g3_global_formula

Returns a formula that will be defined globally, and this can preserve state across timesteps.

Examples

# The definition of g3_env$ratio_add_vec looks like:
eg_ratio_add_vec <- g3_native(r = function(orig_vec, orig_amount,
                                        new_vec, new_amount) {
    ((orig_vec * orig_amount + new_vec * new_amount)
      /
    avoid_zero_vec(orig_amount + new_amount))
}, cpp = '[&avoid_zero_vec](vector<Type> orig_vec, vector<Type> orig_amount,
                            vector<Type> new_vec, vector<Type> new_amount)
                            -> vector<Type> {
    return (orig_vec * orig_amount + new_vec * new_amount)
             /
           avoid_zero_vec(orig_amount + new_amount);
}', depends = c('avoid_zero_vec'))
# eg_ratio_add_vec() can then be used in formulas, both in R & TMB.

# Define a random walk action, using g3_global_formula to keep track of
# previous value. NB: my_randomwalk_prevrec must be unique in a model
random_walk_action <- g3_formula(quote({
    if (cur_time > 0) nll <- nll + dnorm(x, stock__prevrec, 1, 1)
    my_randomwalk_prevrec <- x
}), x = 'TODO', my_randomwalk_prevrec = g3_global_formula(init_val = 0.0))