In :
using Symata


# Interface with Julia¶

This notebook gives examples of Symata interacting with its host language Julia.

## Writing and using Julia functions¶

It is easy to write elegant, fast, powerful, flexible, Julia code from within Symata.

As a first example, we multiply powers of elements in two arrays and sum the results. We first try two different methods using pure Symata. Then we write a Julia function to do the same thing.

Here are the arrays.

In :
x1 = Range(10.0^3)
y1 = Range(10.0^3);


Define a procedural function in Symata to compute the sum.

In :
g(x_, y_) := Module([s=0],
begin
For(i=1, i<=Length(x), i += 1, s += x[i]^2 / y[i]^(-3)),
s
end)


Apply this function and time the result.

In :
g(x1,y1)

resultS1 = Timing(g(x1,y1))

Out:
$$\left[ 0.027964272,1.6716708333325002e17 \right]$$

In general, it is faster to use mapping and functional methods in Symata. We can compute the sum like this.

In :
Apply(Plus, x1^2 / y1^3)

resultS2 = Timing(Apply(Plus, x1^2 / y1^3))

Out:
$$\left[ 0.024730418,7.485470860550343 \right]$$

The second method is indeed a bit faster.

In :
resultS1/resultS2

Out:
$$1.1307642272767084$$

### Writing a Julia function while in Symata mode¶

Define a Julia function to do the sum. We choose a functional method.

In :
jfunc = J((x,y) -> sum(u -> u^2 / u^(3), zip(x,y)));

In :
jfunc(x1,y1)
Timing(jfunc(x1,y1))

resultJ = Timing(jfunc(x1,y1))

Out:
$$\left[ 0.000473548,7.485470860550343 \right]$$

The Julia function is much faster.

In :
[resultS1, resultS2 ] / resultJ

Out:
$$\left[ 59.05266625558549,52.22367743079899 \right]$$

(The Julia function is a factor of 5 times slower here than in Symata 0.3.0-dev.9)

We will explain later why it is possible to write such simple and fast code that operates on Symata expressions.

The function f also works on symbolic expressions.

In :
jfunc([a+b, c+d],[u+v,y+z])

Out:
$$\frac{ \left( a + b \right) ^{2}}{ \left( u + v \right) ^{3}} + \frac{ \left( c + d \right) ^{2}}{ \left( y + z \right) ^{3}}$$
In :
ClearAll(x,a)


### Evaluating Symata expressions from Julia¶

The macro @sym evaluates Symata code while in Julia.

First, we switch to Julia mode.

In :
Julia();


Create a Symata expression and bind it to the Julia variable expr.

In :
expr = @sym a + b

Out:
:a + :b

There are julia functions corresponding to many Symata expression heads.

In :
Expand(expr^2)

Out:
:a^2 + :b^2 + 2:a*:b

In :
isymata()


### Calling an existing Julia function¶

To define the Julia function, we used the Symata function J(). The arguments of J are interpreted as pure Julia code, with no translation. It is as if we temporarily enter Julia mode. In fact, we could have defined the function in Julia. Let's try that.

First, we enter Julia mode.

In :
Julia();


Everything we type will be interpreted as Julia language expressions. We write the Julia function. We will explain later how the function works.

In :
fj(x,y) = sum(u -> u^2 / u^(3), zip(x,y));


In :
isymata();


We set the Symata variable fj to the Julia function fj. The Julia function was written in the Main module. (NB we may change this so Julia functions are evaluated in the Symata module)

In :
fj = J( Main.fj );

Timing(fj(x1,y1))

Out:
$$\left[ 0.015170089,7.485470860550343 \right]$$

We can use J() in this way to call any existing Julia function...

time()

Get the system time in seconds since the epoch, with fairly high (typically,
microsecond) resolution.
In :
J(time)()

Out:
$$1.590816945755939e9$$

## Julia functions for Symata¶

How does the Julia function

jfunc = (x,y) -> sum(u -> u^2 / u^(3), zip(x,y))

work ?

As in Symata, x -> body defines a pure, or anonymous, function. zip returns a list of pairs of elements from two lists. In fact, it returns a virtual list, called an iterator, which is more efficient. These pairs are supplied sequentially to the to the function, and the results are summed. No intermediate arrays are formed.

Symata expressions are iterable objects in Julia. Most Julia code that operates on iterable objects will work with Symata expressions. zip takes two iterable objects and returns an iterable object. In Julia, Symata expressions are of type Mxpr. Notice that we did not write Mxpr anywhere in the code. The first time jfunc is called with Symata expressions, Julia compiles a method to handle just this case. The compiler is typically very good at writing code optimized for the input type.

All of this means that the author of Symata wrote no code to implement zip or sum for Symata expressions.

In fact jfunc can be called with many types objects. To demonstrate this, we perform the sum operation on a Symata list and a Julia Array.

We set the Symata variable y2 to a Julia Array of 1000 numbers.

In :
y2 = J(range(1, stop=1000.0, length=1000))

Out:
$$1.0:1.0:1000.0$$

Notice that 1000 numbers were not printed. range returns a virtual array, that is an iterator. We call jfunc twice. The first time, Julia compiles a method for the input types which takes some (not much) time.

In :
jfunc(x1,y2)
resultJ2 = Timing(jfunc(x1,y2))

Out:
$$\left[ 0.000433112,7.485470860550343 \right]$$

Notice that summing over the two types of arrays is a bit slower in this case than using two Symata arrays.

In :
resultJ/resultJ2

Out:
$$1.093361532351909$$

Now we call jfunc on two Julia abstract arrays.

In :
jfunc(y2,y2)
resultJ3 = Timing(jfunc(y2,y2))

Out:
$$\left[ 3.1529e-5,7.485470860550343 \right]$$

Operating on these Julia arrays is about 10 times faster in this case than including a Symata array.

In :
resultJ2/resultJ3

Out:
$$13.736940594373433$$

### Compile and SymataCall¶

Use Compile to compile a Symata expression to Julia

In :
g = Compile([x], x^2);
g(3)

Out:
$$9$$

Use SymataCall to create a Julia "callback" to Symata.

In :
g = SymataCall(x, x^2 );
g(3)

Out:
$$9$$

But, Compile and SymataCall create different functions. Compile translates Symata to Julia and compiles the result. SymataCall wraps the Symata expression in a Julia function that sets the variable and then Symata-evaluates the result. The function returned by Compile executes faster in general. But SymataCall works with expressions that cannot be translated and compiled.

NIntegrate effectively uses SymataCall.

### @symExpr macro for writing Julia code with Symata¶

Here is a Symata expression that evaluates to an expression that could be Julia code.

In :
ex1 = Together(PolyLog(-1,z),(1-z))

Out:
$$\frac{z}{ \left( -1 + z \right) ^{2}}$$
In :
ex1 ./ ( z => 3)

Out:
$$\frac{3}{4}$$

Switch to Julia mode

In :
Julia()


The macro @symExpr evaluates the Symata expression, translates the result to a Julia expression and inserts it into the surrounding Julia expression.

In :
? @symExpr

In :
f1(z) = @symExpr Together(PolyLog(-1,z),(1-z))

Out:
f1 (generic function with 1 method)
In :
f1(3)

Out:
3//4

The function method definition above is equivalent to

f1(z) = z/(z-1)^2
In :
isymata();  # return to Symata mode


### Unpack: Importing Julia arrays into Symata¶

Recall the abstract Julia array that we created above

In :
y2

Out:
$$1.0:1.0:1000.0$$

We import y2 into Symata using Unpack. (Unpack currently works only with one dimensional arrays.)

In :
y3 = Unpack(y2);


The result is a Symata list. We check that it is indeed a list of the expected length and the first and last elements.

In :
[Head(y3), Length(y3), y3, y3[-1]]

Out:
$$\left[ \text{List},1000,1.0,1000.0 \right]$$

y3 is equal to y1, which was created with Range.

In :
y3 == y1 == Range(10.0^3)

Out:
$$\text{True}$$

y3 is not a packed array, but an ordinary Symata array, a list.

In :
y3 = "cat"

Out:
$$\text{"cat"}$$
In :
y3[1:10]

Out:
$$\left[ \text{"cat"},2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0 \right]$$

Of course, we can unpack not just abstract Julia arrays, but physical arrays as well. The Julia function for converting an abstract array to a physical array is collect.

In :
y4 = J(collect)(y2);


Notice what we did here. J(collect) gets a Symata reference to the Julia function collect. We then call the imported function on the Symata variable y2, which refers to an abstract Julia array.

Now we have a physical Julia array

In :
[Head(y4), y4]

Out:
$$\left[ \text{Array{Float64,1}},1.0 \right]$$

You can also construct a Symata expression directly in Julia, like this.

In :
y5 = J(mxpr(:List, Any[collect(range(1.0, stop=1000, length=1000))...]));

In :
[Head(y5), y5[-1]]

Out:
$$\left[ \text{List},1000.0 \right]$$

### Pack: Converting Symata arrays to Julia arrays.¶

Recall that y1 and y3 are both Symata lists.

In :
[Head(y1), Head(y3)]

Out:
$$\left[ \text{List},\text{List} \right]$$

We pack these lists to Julia arrays like this.

In :
y6 = Pack(y1)
y7 = Pack(y3);


What type of object was created ?

In :
[Head(y6), Head(y7)]

Out:
$$\left[ \text{Array{Float64,1}},\text{Array{Any,1}} \right]$$

The first array is of type Float64 and the second of type Any. They are different because, while all elements of y1 are floating point numbers, we set the first element of y7 to "cat". When copying arrays, Julia creates a container of the most specific type that will contain all elements.

## Using Symata in Julia code¶

### NOTE Julia-mode help is currently broken (in both IJulia, and the Symata-IJulia-Julia mode)¶

Symata-mode help does work.

Switch from Symata to Julia mode

In :
Julia();


We will use the following functions and macros

In :
? @sym

In :
? symparsestring

search: symparsestring


In :
? symeval

search: symeval symparseeval symtranseval


In :
? symtranseval

search: symtranseval


In :
? symparseeval

search: symparseeval


In :
? getsymata

search: getsymata


In :
? setsymata

search: setsymata setsymval



The macro @sym interprets and evaluates its argument in Symata.

In :
a = 1        # set a to 1 in Julia
@sym a = 3   # set a to 3 in Symata
println("a in Julia is $a") # print a in Julia @sym Println("a in Symata is$a") # print a in Symata

a in Julia is 1
a in Symata is 3


You can assign a value in Symata by using @sym

In :
@sym z = "cat"
@sym z

Out:
"cat"

But @sym will not work inside a function. Use getsymata and setsymata instead

In :
getsymata(:z)

Out:
"cat"
In :
setsymata(:z, "dog")
getsymata(:z)

Out:
"dog"

unpacktoList converts a Julia array to a Symat list.

In :
unpacktoList(range(1, stop=4, length=3))

Out:
[1.0,2.5,4.0]

Parse a string of Symata code

In :
scode = Meta.parse("Sqrt(a)")

Out:
:(Sqrt(a))

This is a valid Julia expression, although evaluating it in Julia may cause an error. We translate the expression to Symata and send it through the Symata evaluation sequence.

In :
res = symtranseval(scode)

Out:
3^(1//2)

Print this as Symata would

In :
symprintln(res)

3^(1/2)


Put this together in a function

In :
function squareroots()
a = 1:9
setsymata(:a, unpacktoList(a))
symprintln(symparseeval("Sqrt(a)"))
nothing
end

squareroots()

[1,2^(1/2),3^(1/2),2,5^(1/2),2^(1/2)*3^(1/2),7^(1/2),2*2^(1/2),3]

In :
isymata()  # return to Symata mode


You can translate Symata to Julia like this

In :
ToJuliaString(3 * x^2 * y^3 + Cos(1))

Out:
$$\text{"3 * x ^ 2 * y ^ 3 + cos(1)"}$$

The following gives code that will only work when the Symata module is loaded.

In :
s2 = ToJuliaString( 3*x^2*y^3 + Cos(1), NoSymata => False)

Out:
$$\text{"mplus(mmul(3, mpow(x, 2), mpow(y, 3)), Cos(1))"}$$

We can parse and evaluate this string in Julia.

In :
ExportJ(s2);
J(x = 3, y = 2);
J(eval(Meta.parse(Main.s2)))

Out:
$$216 + \text{Cos} \! \left( 1 \right)$$

## Symata expressions are of type Mxpr¶

We assigned a value to a in symata

In :
Julia()

In :
a = getsymata(:a)

Out:
[1,2,3,4,5,6,7,8,9]
In :
typeof(a)

Out:
Mxpr{:List}

mhead returns the head of a symata expression.

In :
mhead(a)

Out:
:List

margs returns the arguments of a Symata expression.

In :
margs(a)

Out:
9-element Array{Any,1}:
1
2
3
4
5
6
7
8
9

### Use mxpr to construct a Symata expression¶

In :
ex = mxpr(:Cos, mxpr(:Times, :Pi, 2))

Out:
Cos(:Pi*2)

mxpr creates an object but does not evaluate it. Evaluate ex with symeval.

In :
symeval(ex)

Out:
1

It may be more efficient to create a Symata expression by first filling an array of arguments

In :
a = newargs(5);

In :
copyto!(a, 1:5)

Out:
5-element Array{Any,1}:
1
2
3
4
5
In :
mxpra(:List,a)

Out:
[1,2,3,4,5]
In :
mxpra(:Plus,a)

Out:
1 + 2 + 3 + 4 + 5
In :
symeval(mxpra(:Plus,a))

Out:
15

Instead of mxpr, we used mxpra, which does not copy the array of arguments.

We can create Symata expressions like this

In :
println(mmul(3,2), ", " , mmul(:b, :a))

6, :b*:a


mmul, mpow, mplus, mminus are arithemtic methods that can create Symata expressions. When called inside a function with numerical arguments, the compiler will replace them with an efficent Julia method.

We verify this by inspecting the lowered code.

In :
import InteractiveUtils
InteractiveUtils.code_native(mmul,(Int,Int))

	.text
; ┌ @ arithmetic.jl:60 within mmul'
movq	%rdi, %rax
; │┌ @ int.jl:88 within *'
imulq	%rsi, %rax
; │└
retq
nopl	(%rax,%rax)
; └

In :
InteractiveUtils.code_native(*, (Int,Int))

	.text
; ┌ @ int.jl:88 within *'
movq	%rdi, %rax
imulq	%rsi, %rax
retq
nopl	(%rax,%rax)
; └


Many Symata functions have equivalents in Julia. These functions both construct Symata expressions and evaluate them.

In :
Cos(mmul(2,Pi))

Out:
1

symmatamath() defines methods allowing you to use * for mmul, etc.

In :
symatamath()

In :
Cos(2Pi)

Out:
1

Note that Cos is replaced by efficient Julia methods when possible.

In :
isymata()


### Version and date¶

In :
VersionInfo()

Symata version     0.4.6
Julia version      1.6.0-DEV.58
Python version     3.8.3
SymPy version      1.5.1

In :
InputForm(Now())

Out:
2020-05-29T22:35:59.933`