jboy
jboy

Reputation: 209

Passing keyword arguments from DifferentialEquations.jl as arguments for a customized function

I want to write a single function that solves an ODE problem and plots the solution using the solver from DifferentialEquations.jl package. And I want users of this function to get to choose the numerical method from the available options in the package.

Consider the following snippet:

function visualsol(ODEProblem, chosen_algo)
  solution = solve(ODEProblem, chosen_algo())
  plot(solution, label="chosen_algo")
end

So for example, if the user chooses to solve using Runge-Kutta 4, then I want the user to be able to call visualsol(ODEProblem, RK4()). Then the ODE Problem is solved using the RK4 numerical method and the solution is plotted with a label "RK4"

What's the proper way to do this?

Upvotes: 2

Views: 132

Answers (2)

Chris Rackauckas
Chris Rackauckas

Reputation: 19142

__default_name(alg) = string(nameof(typeof(alg)))
function visualsol(ODEProblem, chosen_algo)
  solution = solve(ODEProblem, chosen_algo)
  plot(solution, label=__default_name(chosen_algo))
end

You should have people pass RK4(), not RK4, as the latter is missing information and you'd have to effectively force specialization everywhere.

Upvotes: 4

Nils Gudat
Nils Gudat

Reputation: 13800

I've never used DifferentialEquations so I'm not sure how many solvers are available, but assuming it's a handful the easiest thing might just be to do:

solvers = Dict(RK4() => "Runge-Kutta 4", RK5() => "Runge-Kutta 5", [...etc...])

function visualsol(ODEProblem, chosen_algo)
    solution = solve(ODEProblem, chosen_algo)
    plot(solution, label = solvers[chosen_algo])
end

The user would then pass the actual solver instance (e.g. RK4()).

I guess you could also check any of the benchmarking repos that exist in the DiffEq ecosystem, they produce plots which give the performance of different algorithms so they must be doing something similar (i.e. cycle through available algos and label lines on a plot accordingly).

Upvotes: 1

Related Questions