MethodOfLines.jl icon indicating copy to clipboard operation
MethodOfLines.jl copied to clipboard

Handy utility for writing boundary conditions with kwargs

Open anandijain opened this issue 3 years ago • 9 comments

cc @MarcBerliner

This macro takes in a CallWith call (ie u(t, x1, x2) where u was defined like @variables u(..) and defines a method u_kw(;t=t, x1=x1, x2=x2) = u(t, x1, x2) to make it a bit easier to specify boundary conditions.

I haven't tested many cases though. If we wanted to make it a PR, the best thing would probably be defining a new CallWith in Symbolics that would allow for u(t=0) as opposed to needing to call the macro and use u_kw(t=0) but this was the easiest to do.

using Symbolics, Test

function _to_kw(ex)
    @assert ex.head == :call
    args = ex.args
    @assert all(x isa Symbol for x in args)
    u = args[1]
    xs = args[2:end]
    kw_fn_name = Symbol(ex.args[1], "_kw")
    kws = []
    for arg in xs
        kw = Expr(:kw, arg, esc(arg))
        push!(kws, kw)
    end
    params = Expr(:parameters, kws...)

    def_call_ex = Expr(:call, kw_fn_name, params)
    block_call_ex = Expr(:call, u, xs...)

    body = Expr(:block, block_call_ex)
    Expr(:function, def_call_ex, body)
end

macro to_kw(ex)
    _to_kw(ex)
end

@variables t
N = 2
x = Symbolics.variables(:x, 1:N)
for (i, xi) in enumerate(x)
    @eval $(Symbol(:x, i)) = $xi
end

@variables u(..)

@to_kw u(t, x1, x2)
@test isequal(u_kw(t=0), u(0, x1, x2))

@variables foo(..)
@to_kw foo(t, x1, x2)
@test isequal(foo_kw(t=0), foo(0, x1, x2))

anandijain avatar Nov 22 '22 17:11 anandijain

Looks interesting, thanks! I may export this. Wouldn't this only work if the variable was called u at present? Would be good to generalise this.

Also by the way, are you @anandijain and @MarcBerliner working together or otherwise affiliated?

xtalax avatar Nov 22 '22 17:11 xtalax

We met at Boston Occultists, an organization devoted to corrupting the minds of local youths! Its a hoot and a holler for sure

anandijain avatar Nov 22 '22 17:11 anandijain

Edited my original message, but not fast enough it seems

xtalax avatar Nov 22 '22 17:11 xtalax

Boston Occultists

Weak. I moved to Salem because I'm not a poser.

ChrisRackauckas avatar Nov 22 '22 18:11 ChrisRackauckas

Is this some MIT joke I'm not cultured enough to understand? :')

xtalax avatar Nov 22 '22 18:11 xtalax

yeah thats a bug, i edited the original to fix the hardcoded :u

anandijain avatar Nov 22 '22 18:11 anandijain

go hunt witches or whatever you do over there

anandijain avatar Nov 22 '22 18:11 anandijain

Anand and I are broadly interested in scientific differential programming and reprogramming the minds of the youth

MarcBerliner avatar Nov 22 '22 18:11 MarcBerliner

Can you submit a PR?

xtalax avatar Dec 01 '22 18:12 xtalax