fortran66のブログ

fortran について書きます。

【メモ帳】Fortran から Julia 呼び出し その3

Fortran から julia 呼んでそこから python 呼んでそこから Fortran 呼び出し

Python から呼び出す Fortran subroutine sub.f90

subroutine test() bind(c, name = 'test')
    print *, 'subroutine test: Fortran calls Julia calls Python calls Fortran subroutine'
end subroutine test
gfortran -shared -o sub.so sub.f90

Fortran メインプログラム test.f90

Julia を呼び出し、Julia の PyCall によって Python の numpy, matplotlib, ctypes を呼び出し、絵を描き Fortran のサブルーチンを呼び出します。

module julia_mod
    use, intrinsic :: iso_fortran_env
    use, intrinsic :: iso_c_binding
    implicit none
    interface
        subroutine jl_init() bind(c, name = 'jl_init__threading')
        end subroutine jl_init

        subroutine jl_atexit_hook(status) bind(c, name = 'jl_atexit_hook')
            import
            integer(c_int), value :: status
        end subroutine jl_atexit_hook

        function jl_eval_string(pstr) bind(c, name = 'jl_eval_string')
            import
            type(c_ptr) :: jl_eval_string
            type(c_ptr), value :: pstr
        end function jl_eval_string
    end interface

contains
    subroutine eval(text)
        character(*), intent(in) :: text
        type(c_ptr) :: iret
        character(:), allocatable, target :: buff
        buff = text // achar(0)
        iret = jl_eval_string(c_loc(buff))
    end subroutine eval
end module julia_mod

program test
    use julia_mod
    implicit none
    type(c_ptr) :: iret

    call jl_init()

    call eval('println("Julia from Fortran")')

    call eval('using PyCall')
    call eval('np = pyimport("numpy")')
    call eval('x = np.random.rand(20)')
    call eval('println(x)')

    call eval('plt = pyimport("matplotlib.pyplot")')
    call eval('plt.plot(x)')
    call eval('plt.savefig("plt.jpg")')

    call eval('pyimport("ctypes")')
    call eval('f = np.ctypeslib.load_library("sub.so", ".")')
    call eval('f.test()')

    call jl_atexit_hook(0)
end program test
hp8@HP8:~/forjulia$ gfortran -o test -fPIC -L$JULIA_DIR/lib -Wl,-rpath,$JULIA_DIR/lib test.f90 -ljulia
hp8@HP8:~/forjulia$ ./test
Julia from Fortran
[0.5654498902512056, 0.1661842542698303, 0.2505778464395546, 0.7666649031127386, 0.8496339671276011, 0.9273802000807766, 0.8927764872674302, 0.3006637895458586, 0.8680738476853896, 0.7854580868588814, 0.45450410234687666, 0.28052468257184127, 0.061124512953987575, 0.19881999156124885, 0.9443622824939664, 0.12457596083666511, 0.46569931418942245, 0.9063580131505672, 0.6581766728087582, 0.2236554710108204]
 subroutine test: Fortran calls Julia calls Python calls Fortran subroutine
hp8@HP8:~/forjulia$ eog plt.jpg

f:id:fortran66:20201108014408p:plain

Guide to Fortran 2008 Programming

Guide to Fortran 2008 Programming

1から始める Juliaプログラミング

1から始める Juliaプログラミング

Pythonによるデータ分析入門 第2版 ―NumPy、pandasを使ったデータ処理

Pythonによるデータ分析入門 第2版 ―NumPy、pandasを使ったデータ処理

  • 作者:Wes McKinney
  • 発売日: 2018/07/26
  • メディア: 単行本(ソフトカバー)