Error[8]: Undefined offset: 239, File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 121
File: /www/wwwroot/outofmemory.cn/tmp/plugin_ss_superseo_model_superseo.php, Line: 473, decode(

Python与Julia结合使用的个人经验
本人非专业程序员,下面讲的是我从事科学计算时得到的一点心得。
Julia速度很快,我随手写的Julia代码,常常比我精心用numba优化的Python代码快。但另一方面,Python确实令我难以割舍。一是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

这段代码,总的来说实现了两个功能:

  1. 将你自己的包目录添加到搜索目录;
  2. 不同电脑/服务器可以运行同样的代码。第一行是为了获得电脑名;后面是为了针对不同的电脑/服务器(不同电脑可以用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:
	// ,  for tab stops, // same ids are connected. for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// Example:
	// 	"prefix": "log",
	// "Print to console": {
	// 	"body": [
	// 		"console.log('');",
	// 		""
	// 	],
	// 	"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 == \"宿舍电脑\"" # 这里最开始要是四个空格,不是tab
			,"    push!(LOAD_PATH, \"F:/Documents/JuliaProgramme/MyModules\")"
			,"elseif computername==\"DESKTOP-FDIN0I7\""
			,"    push!(LOAD_PATH, \"D:/Documents/Julia/MyModules\")"
    		,"end"
			,]
		}
	}
.jl

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

)
File: /www/wwwroot/outofmemory.cn/tmp/route_read.php, Line: 126, InsideLink()
File: /www/wwwroot/outofmemory.cn/tmp/index.inc.php, Line: 166, include(/www/wwwroot/outofmemory.cn/tmp/route_read.php)
File: /www/wwwroot/outofmemory.cn/index.php, Line: 30, include(/www/wwwroot/outofmemory.cn/tmp/index.inc.php)
Python与Julia结合使用的个人经验_java_内存溢出

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

Python与Julia结合使用的个人经验,第1张

Python与Julia结合使用的个人经验
  • 一、库的创建
    • 1.1. Python库的创建
    • 1.2. Julia包的创建
  • 二、库的调用
    • 2.1. Julia调用Julia包
    • 2.2. Python中调用Python库
    • 2.3. Julia调用Python库
    • 2.4. Python中调用Julia包
  • 三、Tips about VS Code

本人非专业程序员,下面讲的是我从事科学计算时得到的一点心得。
Julia速度很快,我随手写的Julia代码,常常比我精心用numba优化的Python代码快。但另一方面,Python确实令我难以割舍。一是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

这段代码,总的来说实现了两个功能:

  1. 将你自己的包目录添加到搜索目录;
  2. 不同电脑/服务器可以运行同样的代码。第一行是为了获得电脑名;后面是为了针对不同的电脑/服务器(不同电脑可以用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:
	// ,  for tab stops, // same ids are connected. for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
	// Example:
	// 	"prefix": "log",
	// "Print to console": {
	// 	"body": [
	// 		"console.log('');",
	// 		""
	// 	],
	// 	"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 == \"宿舍电脑\"" # 这里最开始要是四个空格,不是tab
			,"    push!(LOAD_PATH, \"F:/Documents/JuliaProgramme/MyModules\")"
			,"elseif computername==\"DESKTOP-FDIN0I7\""
			,"    push!(LOAD_PATH, \"D:/Documents/Julia/MyModules\")"
    		,"end"
			,]
		}
	}
.jl

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/792800.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-05
下一篇 2022-05-05

发表评论

登录后才能评论

评论列表(0条)

保存