Call julia function from python

Hi, guys, I use bayesion optimization of python plus subfunction of julia to do my simulation, and I can successfully run the simple function see here, maybe I should ask another question, if I want to combine the speed of julia and the convenience of python, should I call julia sub-function(needs much time) from python or call python’s bayesian optimization packages from julia, I am in a mess…

#  sub-function written in julia
function black_box_function(x, y)   #save in the name of "example.jl"
    return -x^2 - (y - 1)^2 + 1
end
# run in python
from bayes_opt import BayesianOptimization
from julia import Main
Main.include("example.jl")
Main.black_box_function(2,3)  #  it works   

however if I put the sub-function into the bayesian optimization, then it crashed

# run in python
from bayes_opt import BayesianOptimization
from julia import Main
Main.include("example.jl")

# def black_box_function(x, y):
#       return -x ** 2 - (y - 1) ** 2 + 1       # initial sub-function defined in python, and works well

# Bounded region of parameter space
pbounds = {'x': (2, 4), 'y': (-3, 3)}

optimizer = BayesianOptimization(  
    f=Main.black_box_function,             # sub-function defined in julia, doesn't work
    pbounds=pbounds,
    random_state=1,
)

optimizer.maximize(                       
    init_points=5,
    n_iter=5,
)

looks like your python function is passing keyword arguments instead of positional arguments.

https://github.com/maffettone/bayes_opt/blob/master/bayes_opt/target_space.py#L223-L225

so in the Julia side, do one more definitions so it takes keyword arguments, hopefully that works:

black_box_function(;x, y) = black_box_function(x, y) 
1 Like

Yes, it works, thanks