Compiling a function that takes lots of optional arguments

I have a function that takes lots of optional arguments (basically some design parameters, about 10 of them) and performs some basic algebraic calculations involving complex numbers with the options. The function generally evaluates to a complex number. For example, I have something like:

Options[myfunc] = {param1 -> 1.0, param2 -> 2.0, param3 -> 3.0, etc.};
myfunc[x, opts: OptionsPattern[]] :=
Module[
{var1,var2,  etc.},
var1 = OptionValue[param1]; etc.
I*x*var1 + var2 + 1/(var3 + I var4)*... etc.
]


The function is listable in x and I want to evaluate it as fast as possible for different x's.

I need to use this function in lots of plotting, solving and optimization procedures as part of a Manipulate GUI. The problem is that such procedures takes significant amount of time (~ 10s) which renders the Manipulate GUI unusable.

My question is if I can compile myfunc somehow to speed up the rest of the processing? If not, is there an alternative way to define a function with Options (or optional arguments) to make it compilable? Can I compile the entire Manipulate GUI? If compilation is not possible, any hints about how to define such function in an efficient way?

• Compiled functions do not take options. You can, however, construct a wrapper that takes options and then passes values to a compiled function. May 20, 2015 at 7:20
• Thanks, sounds like a good solution... May 20, 2015 at 7:21
• I'd suggest introducing the parameters as a vector with an argument for the count of the arguments. Then you can special case inside the compiled code. Or, compile separate functions for different numbers of arguments and have a wrapper that specializes to them from the general case. No time to elaborate now; sorry. May 20, 2015 at 8:23
• I'm not sure if this is wholly relevant to the case at hand, but one sample manipulate I have direct from Wolfram takes a slightly different approach. Basically define a single parameter for your function as an association. myFunc[commsAssoc_] within the assoc you have different keys referring to both the data and the parameters, and you control the function processing by writing to the association before calling it, and potentially write the output back before quitting the function. Its not a particularly clean way of doing it but seems to work reasonably well on our large-ish datasets. May 20, 2015 at 12:28

• The first level is merely syntactical; you would use OptionsPattern, OptionValue etc., in a high level function simply for convenience, but pass all arguments as machine types to an inner compiled function.
• A different level is compilation at the time the high-level function is called based on the option values and other parameters. Possibly memoization would be used to prevent re-compiling the same thing multiple times. One may also want to modularize the code and use CompilationOptions -> {"InlineCompiledFunctions" -> True} as part of this process.