MathLink.jl
MathLink.jl copied to clipboard
Conversion to julia expressions
Being able to convert WExpr
s to julia Expr
, such that you can define julia functions, that you derived using Mathematica functions would be very nice to have.
We need some sort of way to match up functions between Julia and Mathematica. This is obvious in some cases (e.g. sin
=> W"Sin"
), but some functions differ in their usage or how certain arguments are handled (e.g. sum
vs W"Sum"
).
Is there a way we could query the signatures of the Mathematica functions, such that we could build a mapping via codegen? ( Check, if a method with a matching signature exists and if not, define a bridge )
Not that I know of. MathLink only sees symbol names, it has no semantic knowledge.
This may be better handled in another package built on top of this.
Even a version which doesn't translate function calls would be immensely useful
https://github.com/AmplitudeGravity/usingMathLink/blob/master/useMathLink.ipynb uses https://github.com/chakravala/SyntaxTree.jl to do the very basics of this.
Is it possible to convert a pure complex number in type of WExpr to a julia ComplexF64?
I recently used Meta.parse(W2Mstr(WExpr))
for real numbers and eval(Meta.parse(replace(W2Mstr(weval(WExpr)),"I"=>"im"))) for complex numbers. Function like pyconvert
in PythonCall.jl
is preferred.
I extracted part of @AmplitudeGravity's demo above and extended it in a package here: https://github.com/musoke/WolframExpr.jl. It converts Mathematica/Wolfram expressions to Julia expressions and functions. It only knows how to translate a handful of functions out of the box, but enough for complex rational functions. You can tell it how other functions are defined.
julia> using MathLink, WolframExpr
julia> s = "(1 + G[x])/(1 + x + I*x^2)";
julia> f = string_to_function(s, [:G, :x]);
julia> g(x) = im * x + x^2;
julia> f(g, 1)
1.0 + 0.0im
Hi, based on ticked (https://github.com/JuliaInterop/MathLink.jl/issues/72) I took the liberty to add the feature (`W2Julia ) in into the 0.5.3 release of today (https://github.com/JuliaInterop/MathLink.jl/releases/tag/v0.5.3). It aims to convert MathLink objects to Julia style objects.
For instance it can convert the "Assumptions" to a dictionary. Below are some examples:
@test W2Julia(W`{1,2,3}`) == [1,2,3]
@test W2Julia(W`{1,a,3}`) == [1,W"a",3]
@test W2Julia(W`{1,a,{1,2}}`) == [1,W"a",[1,2]]
@test W2Julia(W`Association["team" -> "HOU", "lastName" -> "Ching"]`) == Dict( "team" => "HOU" , "lastName" => "Ching")
@test W2Julia(W`Association["team" -> {1,2,3}, "lastName" -> "Ching"]`) == Dict( "team" => [1,2,3] , "lastName" => "Ching")
@test W2Julia(W`{1,Association["team" -> {1,2,3}, "lastName" -> "Ching"]}`) == [1,Dict( "team" => [1,2,3] , "lastName" => "Ching")]
As this is almost at the embryo stage, feel free to report strange (or lacking) behavior i other tickets.