0
点赞
收藏
分享

微信扫一扫

Python与Julia结合使用的个人经验

修炼之士 2022-04-29 阅读 104
pythonjulia

Python与Julia结合使用的个人经验


本人非专业程序员,下面讲的是我从事科学计算时得到的一点心得。
Julia目前感觉速度很快,但是我更喜欢Python绘图。一是Julia绘图国内教程较少,我看官方文档也画不出满意的图;二是Julia绘图没Python灵活;三是目前有些Python库多,很多。因此我希望能方便得用Python直接获得 自己写的Julia函数的结果。

一、库的创建

1.1. Python库的创建

暂略。搜__init__.py的用法。

1.2. Julia包的创建

关于包的创建,暂且先参考这个视频。
下次我再创建包的时候,可以来记录下我的简单流程。


二、库的调用

2.1. Julia调用Julia包

假设你已经创建了自己的程序库/包,可以研究下这段代码:

computername = ENV["COMPUTERNAME"]

if computername == "家里电脑"
	push!(LOAD_PATH, "E:/Documents/JuliaProgram/MyModules/")
elseif computername == "宿舍电脑"
	push!(LOAD_PATH, "F:/Documents/JuliaProgramme/MyModules")
elseif computername=="DESKTOP-FDIN0I7"
	push!(LOAD_PATH, "D:/Documents/Julia/MyModules")
end

这段代码,第一行是为了获得电脑名;后面是为了针对不同的电脑(不同电脑可以用onedrive、坚果云、群晖等等同步同一个个人程序库),将你的包目录添加到LOAD_PATH,这样你using或者import的时候,Julia就会到里面去搜索你的库。

2.2. Python中调用Python库

import socket, sys
host_name = socket.gethostname()
if (host_name == 'localhost.localdomain'): sys.path.insert(0, '/home/XXX/MyFunction') # 导师工作站
if (host_name[0:6] == 'acc-ap'): sys.path.insert(0, '/sharefs/heps/user/XXX/MyFunction') # acc-apXX服务器
if (host_name == 'DESKTOP-FDIN0I7'): sys.path.insert(0, 'D:/Documents/PythonFiles/001.科研/000.Accelerator/MyFunctionForAccelerator') # 办公室电脑
if (host_name == '宿舍电脑'): sys.path.insert(0, r'F:/Documents/PythonProgramme/001.科研/000.Accelerator/MyFunctionForAccelerator') # 宿舍电脑
if (host_name == 'XXXXX'): sys.path.insert(0, r'D:/PythonFile/001.科研/000.Accelerator/MyFunctionForAccelerator') # Surface
if (host_name == '家里电脑'): sys.path.insert(0, r'E:/Documents/PythonProgramme/001.科研/000.Accelerator/MyFunctionForAccelerator') # 家里电脑

前两段是为了获得电脑/服务器名,剩下就是为了针对不同电脑,将各自的库文件夹添加到Python搜索的目录。

2.3. Julia调用Python库

需要安装PyCall这个Julia包。
请注意下面py前缀,这个在Julia中称为“宏”,类似Python中的“装饰器”。我的理解,它的作用就是:

  1. 打开python内核(如果这段程序前面没有打开的话);
  2. 提交后面紧接的文字给python内核——有点像你在python终端中打字给它;
  3. 等着新的指令——意味着后面可以接着前面继续执行。
using PyCall

py"""
import matplotlib.pyplot as plt
plt.style.use("science")
"""

xdata = [0.0, 1, 2, 3, 4]
ydata = [4.0, 3, 2, 1, 0]

py"""
def plot1(xdata, ydata, xlabel, ylabel):
    plt.figure(figsize=(3,3), dpi=200)
    plt.plot(xdata, ydata)
    plt.grid()
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.show()
"""

py"plot1"(xdata, ydata, raw"$x$", raw"$y_1$") # 这里有传参的方法

可以看到我三次分别提交的py装饰的python程序片段,它都能正确执行。
在这里插入图片描述

2.4. Python中调用Julia包

需要安装Julia这个Python库。

from julia import Main

loadpath="""
computername = ENV["COMPUTERNAME"]
if computername == "家里电脑"
	push!(LOAD_PATH, "E:/Documents/JuliaProgram/MyModules/")
elseif computername == "宿舍电脑"
	push!(LOAD_PATH, "F:/Documents/JuliaProgramme/MyModules")
elseif computername=="DESKTOP-FDIN0I7"
	push!(LOAD_PATH, "D:/Documents/Julia/MyModules")
end

using DoubleRFs	# 导入自己写的包
"""
Main.eval(loadpath)	# 这段就会启动Julia内核、执行上面的Julia代码,并等待着

Main.eval(s)的作用,类似于你在Julia终端输入了s这个字符串。终端会从你输入的这行字识别出你知道想干什么,并返回值。

x, y=Main.eval("DoubleRFs.getSynchrotronTunes(400, 3643872.777, 6e9, 1.560987361026252e-5, 2.0399026, -0.584545192849095, 0.1806991469840516, 756, 3, 1360.4)")

万幸Julia内核/终端会在后面等着你输入——我这里第二次提交Main.eval(),可以看到它接着第一次using DoubleRFs继续执行了。
这里x, y获得的结果是正常的(只不过数值类型从Julia中的Vector变成python中numpynumpy.ndarray了)。

plt.plot(x, y, ".")
plt.xlabel(r"$z$")
plt.ylabel(r"$\nu_s$")
plt.show()

在这里插入图片描述


三、Tips about VS Code

如果你用到VSCode,可以在打开.jl代码时,点开设置-用户代码片段-julia.json,添加如下片段:

{
	// Place your snippets for julia here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// same ids are connected.
	// Example:
	// "Print to console": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }

	"My Julia Module":{
		"prefix": "MyModule",
		"body": [
			"computername = ENV[\"COMPUTERNAME\"]",
			"if computername == \"家里电脑\"",
			"	push!(LOAD_PATH, \"E:/Documents/JuliaProgram/MyModules/\")",
			"elseif computername == \"宿舍电脑\"",
			"	push!(LOAD_PATH, \"F:/Documents/JuliaProgramme/MyModules\")",
			"elseif computername==\"DESKTOP-FDIN0I7\"",
    		"	push!(LOAD_PATH, \"D:/Documents/Julia/MyModules\")",
			"end",
		]
	}
}

以后在.jl(julia文件)中键入MyModule就会出来这一整个片段。
python类似,就是.py文件时,编辑python.json文件。

举报

相关推荐

0 条评论