11
$\begingroup$

This question is an extension of Passing down arguments.

To help clarify my question, I will be referring to another recent post of mine Making Quartile Plots from a Dataset, the code to which can be found here.

Context

It is clear that arguments can be passed down as demonstrated in both the documentation and in @Szabolcs answer to Passing down arguments by using passedToOption -> OptionValue[<option>].

Although verbose it works fine when one needs to only pass one or two options. However this convention is too verbose and cluttering to write clear code when one must pass a lot of options.

Consider Mathematica's many Plot functions and the numerous options available. While the defaults are nice, if one is making a custom plotting function, such as in Making Quartile Plots from a Dataset, one may prefer different options those chosen by Wolfram. Further, to maintain the flexibility of the original Plot function, all the options must be defined in the Options of the function - Wolfram's defaults and my own.

In the linked code above, one can see why this would be useful, especially for the BinnedQuartilePlot and the host of color functions that pass their options down several functions.

Question

Is there a concise way to pass, from one function to another, all Options of the encapsulating function - both the defaults and those explicitly set?

Code

f[x_] := x^2
Options[myPlot] := {"PlotRange" -> Full, "PlotStyle" -> "Pastel", "Filling" -> "Axis"}
myPlot[function_, OptionsPattern[]] :=
 Plot[function[x], {x, 1, 5},
  PlotRange -> OptionValue["PlotRange"],
  PlotStyle -> OptionValue["PlotStyle"],
  Filling -> OptionValue["Filling"]]
$\endgroup$
  • 2
    $\begingroup$ related: Clean and handy Options management/filtering $\endgroup$ – Kuba Mar 23 '17 at 17:00
  • 2
    $\begingroup$ Why not do something like myPlot[function_, opts : OptionsPattern[]] := Plot[function[x], {x, 1, 5}, Evaluate @ FilterRules[{opts} ~Join~ Options[myPlot], Options[Plot]]]? $\endgroup$ – J. M. is away Mar 23 '17 at 17:16
  • 2
    $\begingroup$ That should really be PlotRange, not "PlotRange". Generally, string and symbol versions should be interchangeable when used in option handling functions. But if you (or the author or some other function) accidentally uses some other functions to manipulate options (like @MB1965 did with DeleteDuplicatesBy, see my comment), then there may be a mixup. $\endgroup$ – Szabolcs Mar 24 '17 at 14:23
  • 2
    $\begingroup$ I mean, if an option name exists as a symbol, better to use it as a symbol. When introducing a new name, feel free to use a string. I usually use a string to avoid creating too many symbols. $\endgroup$ – Szabolcs Mar 24 '17 at 14:56
  • 1
    $\begingroup$ @Sum, it's the modern form of a pattern I've been using for years, back when Mathematica had the (package) function FilterOptions[] instead of the modern FilterRules[]. $\endgroup$ – J. M. is away Mar 24 '17 at 15:00
13
$\begingroup$

Let us assume that you are designing a function which can take its own unique options, but also shares option names with Plot. What is the best way to implement such a function myPlot? Below I will try to give a complete guide on how to do this.

There are two common approaches:

  1. The default values for Plot-specific options will be taken directly from Plot. Changing Plot options with SetOptions also affects myPlot. It is not possible to use SetOptions on myPlot with Plot-specific options. This is only possible with options unique to myPlot.

  2. myPlot has its own copy of Plot's options. Changing Plot's options does not affect myPlot. Any of these options can be changed directly on myPlot using SetOptions.

Most builtin functions use approach (2).

For the following, it is good to be aware that when an option is specified multiple times, Mathematica always takes the first value.

Inheriting defaults from Plot

Here's how to implement approach (1). We start by setting the defaults of myPlot's unique options:

Options[myPlot] = { Top -> 10 };

myPlot[f_, opt : OptionsPattern[{myPlot, Plot}]] := 
  Plot[f[x], {x, 0, OptionValue[Top]}, 
    Evaluate@FilterRules[{opt}, Options[Plot]]
  ]

Here, the purpose of specifying Plot within OptionsPattern was to avoid error messages when using options that are present in Options[Plot] but not in Options[myPlot].

An additional effect is that now you can use OptionValue with Plot-specific options. We do not need this in this specific implementation. However, specifying Plot within OptionsPattern is still necessary to avoid errors.

Using Evaluate before FilterRule was necessary because Plot is HoldAll.

If you put this function in a package, at some point you may want to add syntax information to it. Like this:

SyntaxInformation[myPlot] = {"ArgumentsPattern" -> {_, OptionsPattern[]}}

But now we run into a problem. Plot-specific options work, but they are coloured in red, as if they were incorrect.

Mathematica graphics

The workaround is using an undocumented entry in SyntaxInformation, "OptionNames":

SyntaxInformation[
   myPlot] = {"ArgumentsPattern" -> {_, OptionsPattern[]}, 
   "OptionNames" -> Union[First /@ Options[myPlot], First /@ Options[Plot]]};

Separate defaults for myPlot and Plot

This is the more common approach, and this is what builtins use.

We start by setting myPlot's unique options, as well as copying over Plot's options. Here, we do not change Plot's defaults.

Options[myPlot] = Join[
   {Top -> 10}
   Options[Plot]
  ];

Now we are ready to change some Plot-specific options from their default values:

SetOptions[myPlot, {PlotRange -> All, PlotStyle -> Red}];

Now we can define myPlot:

myPlot[f_, opt : OptionsPattern[]] := 
 Plot[f[x], {x, 0, OptionValue[Top]}, 
    Evaluate@FilterRules[Join[{opt}, Options[myPlot]], Options[Plot]]
 ]

We no longer need to list function names in OptionsPattern[]. But now we need to pass down all options, as set either in opt or in Options[myPlot] to the Plot function. We can simply Join all of them together, relying on the fact that when duplicates are present, the value will be taken from the first occurrence.

Now the SyntaxInformation can be simpler:

SyntaxInformation[myPlot] = {"ArgumentsPattern" -> {_, OptionsPattern[]}}

The allowed option names will be taken from Options[myPlot].


Finally, you can also mix these two approaches. You can have only a subset of Plot's options present in Options[myPlot]. I do not recommend that you do this because it can be confusing to users. Either put all of them in there (the more common approach), or none of them at all.

$\endgroup$
  • $\begingroup$ Can I ask a few newbie questions? what is opt : OptionsPattern[] syntax? What about about FilterRules in general? $\endgroup$ – SumNeuron Mar 24 '17 at 14:57
  • 1
    $\begingroup$ opt is the pattern name. x : _ is exactly the same thing as x_ (see its FullForm). When the pattern is something else than _, you need : to give it a name. $\endgroup$ – Szabolcs Mar 24 '17 at 14:58
  • $\begingroup$ I see. Thank you. Where did you learn that? $\endgroup$ – SumNeuron Mar 24 '17 at 14:59
  • 1
    $\begingroup$ @SumNeuron I would tell you that everything is in the documentation. But inexplicably, in version 11.1 some essential tutorial links were removed from that page. If you still use 11.0, you will find them at the top. Otherwise look here: reference.wolfram.com/language/tutorial/PatternsOverview.html $\endgroup$ – Szabolcs Mar 24 '17 at 15:06
  • $\begingroup$ I noticed that (removal of links) as well. I just haven't seen : used before. $\endgroup$ – SumNeuron Mar 24 '17 at 15:08

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.