我有一个用Julia写的高性能函数,如何从Python使用它? [英] I have a high-performant function written in Julia, how can I use it from Python?

查看:253
本文介绍了我有一个用Julia写的高性能函数,如何从Python使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个Julia函数,可以很好地完成我需要的工作. 如何快速集成它以便能够从Python调用它?

I have a found a Julia function that nicely does the job I need. How can I quickly integrate it to be able to call it from Python?

假设函数是

f(x,y) = 2x.+y

从Python使用它的最好,最优雅的方法是什么?

What is the best and most elegent way to use it from Python?

推荐答案

假设已安装Python和Julia,则需要执行以下步骤.

Assuming your Python and Julia are installed you need to take the following steps.

  1. 运行Julia并安装PyCall

using Pkg
pkg"add PyCall"

  • 将您的代码放入Julia包

  • Put your code into a Julia package

    using Pkg
    Pkg.generate("MyPackage")
    

    在文件夹src中,您将找到MyPackage.jl,对其进行编辑以使其看起来像这样:

    In the folder src you will find MyPackage.jl, edit it to look like this:

    module MyPackage
    f(x,y) = 2x.+y
    export f
    end
    

  • 安装pyjulia

  • Install pyjulia

    python -m pip install julia
    

    (在Linux系统上,您可能希望使用python3而不是python命令)

    (On Linux systems you might want to use python3 instead of python command)

    对于此步骤,请注意,虽然外部Python可与Julia一起使用.但是,为方便起见,可能值得 考虑使用与Julia一起安装的Python PyCall. 在这种情况下,请使用以下命令进行安装:

    For this step note that while an external Python can be used with Julia. However, for a convenience it might be worth to consider using a Python that got installed together with Julia as PyCall. In that case for installation use a command such this one:

    %HOMEPATH%\.julia\conda\3\python -m pip install julia
    

    或在Linux

    ~/.julia/conda/3/python -m pip install julia
    

    请注意,如果定义了JULIA_DEPOT_PATH变量,则可以用其值替换%HOMEPATH%\.julia~/.julia/.

    Note that if you have JULIA_DEPOT_PATH variable defined you can replace %HOMEPATH%\.julia or ~/.julia/ with its value.

    运行适当的Python并告诉它配置Python-Julia集成:

    Run the appropiate Python and tell it to configure the Python-Julia integration:

    import julia
    julia.install()
    

  • 现在您可以调用您的Julia代码了:

  • Now you are ready to call your Julia code:

    >>> from julia import Pkg
    >>> Pkg.activate(".\\MyPackage") #use the correct path
        Activating environment at `MyPackage\Project.toml`
    >>> from julia import MyPackage
    >>> MyPackage.f([1,2],5)
        [7,9]
    

  • 值得注意的是,此答​​案中建议的方法比独立的Julia文件具有多个优点,尽管不建议这样做,但它是可能的.优点包括:

    It is worth noting that the proposed approach in this answer has several advantages over a standalone Julia file which would be possible, although is less recommended. The advantages include:

    1. 软件包会被预先编译(因此在以后的运行中速度更快),并且可以作为软件包在Python中加载.
    2. 软件包通过1Project.toml`带有自己的虚拟环境,这使生产部署更加舒适.
    3. 可以将Julia包静态地编译到Julia的系统映像中,这可以减少其加载时间---参见 https ://github.com/JuliaLang/PackageCompiler.jl .

    这篇关于我有一个用Julia写的高性能函数,如何从Python使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆