3
$\begingroup$

I have a module that uses some default options for NDSolve like so

Options[f] = {WorkingPrecision -> 20};
f[p_, opts:OptionsPattern[]] := Module[{}, NDSolve[{eqns[p], bcs, FilterRules[{opts},Options[NDSolve]]]]

But this doesn't pass the changed default to NDSolve unless they are passed explicitly by the call to f. I seem to be missing something, because I am trying to avoid duplication: I would like to be able to simply add/remove options from the defaults of f and not have to change the body of f, and have these defaults passed to NDSolve.

$\endgroup$
3
$\begingroup$

You can use the fact that rules apply in the order in which they appear:

Options[f] = Join[{WorkingPrecision -> 10}, Options[NDSolve]];
f[opts : OptionsPattern[]] := NDSolve[..., FilterRules[Join[{opts}, 
    Options[NDSolve]], Options[NDSolve]]]

The same principle can also be used to specify default parameters so that OptionValue will automatically fall back on the defaults of NDSolve unless otherwise specified. Consider this example:

Options[f] = {a -> 1, a -> 2, b -> 3};
f[opts : OptionsPattern[]] := OptionValue[a]
f[]

1

It shows that default values are considered in the order in which they appear, i.e. the default value for a in this function is 1 and not 2.

Similarly, you can also write

Options[f] = Join[{WorkingPrecision -> 10}, Options[NDSolve]];
f[opts : OptionsPattern[]] := OptionValue[WorkingPrecision]
f[]

10

and be assured that whatever you specify overrides whatever NDSolve used.

And if we combine the two approaches we get to this:

Options[f] = Join[{WorkingPrecision -> 10}, Options[NDSolve]];
f[opts : OptionsPattern[]] := NDSolve[..., FilterRules[Join[{opts}, 
    Options[f]], Options[NDSolve]]]

which will take into account default options of NDSolve that you have overridden.

These patterns are probably used quite extensively in the built-in functions. The plotting functions also take the options from Graphics for example, I imagine this is how that is done.

$\endgroup$
2
  • $\begingroup$ Yeah, I was never sure about the order, and always too lazy to check and unsure that it would remain invariant in different versions etc. Do you mean FilterRules[Join[{opts}, Options[f]], Options[NDSolve]]]? $\endgroup$ – bjorne Dec 2 '17 at 22:58
  • $\begingroup$ @bjorne Yes, that is what you would use if you had overridden some of the options when specifying defaults for f. $\endgroup$ – C. E. Dec 2 '17 at 23:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.