我最近询问了如何为科学应用程序优化Python循环,并在NumPy中获得了一种优秀,智能的重新编码方式,这使我的执行时间减少了大约100倍!
但是,值的计算B实际上嵌套在其他几个循环中,因为它是在常规的位置网格上进行计算的.有没有类似的智能NumPy重写来削减这个程序的时间?
我怀疑这部分的性能提升不太明显,并且缺点可能是不可能向用户报告计算的进度,结果无法写入输出文件,直到计算的结束,并且可能在一个巨大的步骤中这样做会产生内存影响吗?有可能绕过这些吗?
import numpy as np
import time
def reshape_vector(v):
b = np.empty((3,1))
for i in range(3):
b[i][0] = v[i]
return b
def unit_vectors(r):
return r / np.sqrt((r*r).sum(0))
def calculate_dipole(mu, r_i, mom_i):
relative = mu - r_i
r_unit = unit_vectors(relative)
A = 1e-7
num = A*(3*np.sum(mom_i*r_unit, 0)*r_unit - mom_i)
den = np.sqrt(np.sum(relative*relative, 0))**3
B = np.sum(num/den, 1)
return B
N = 20000 # number of dipoles
r_i = np.random.random((3,N)) # positions …Run Code Online (Sandbox Code Playgroud) 我正在用Python编写一个科学应用程序,其核心是一个处理器密集型循环.我希望尽可能优化这一点,对最终用户至少造成不便,最终用户可能会将其用作未编译的Python脚本集合,并将使用Windows,Mac和(主要是Ubuntu)Linux.
它目前用Python编写,带有一些NumPy,我已经包含了下面的代码.
(如果你有兴趣,环路是加入了大量附近的磁性离子的贡献一起计算在晶体内给定点的磁场,当作小酒吧磁铁.基本上,一个巨大的总和这些. )
# calculate_dipole
# -------------------------
# calculate_dipole works out the dipole field at a given point within the crystal unit cell
# ---
# INPUT
# mu = position at which to calculate the dipole field
# r_i = array of atomic positions
# mom_i = corresponding array of magnetic moments
# ---
# OUTPUT
# B = the B-field at this point
def calculate_dipole(mu, r_i, mom_i):
relative = mu - r_i …Run Code Online (Sandbox Code Playgroud) 我有一个在x轴上有对数刻度的图形.尝试创建插图不起作用,但如果将比例更改为线性,则似乎没有问题.有没有办法解决这个问题,还是ggplot的限制?
这有效:
p = qplot(1:10, 1:10)
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 3, xmax = 6, ymin = 6, ymax = 10)
Run Code Online (Sandbox Code Playgroud)
这不是:
p = qplot(1:10, 1:10, log='x')
g = ggplotGrob(qplot(1, 1))
p + annotation_custom(grob = g, xmin = 3, xmax = 6, ymin = 6, ymax = 10)
Run Code Online (Sandbox Code Playgroud) 是否有办法强制R的table功能包括行或列,即使它们从未出现在数据中?例如,
data.1 <- c(1, 2, 1, 2, 1, 2, 4)
data.2 <- c(1, 4, 3, 3, 3, 1, 1)
table(data.1, data.2)
Run Code Online (Sandbox Code Playgroud)
回报
data.2
data.1 1 3 4
1 1 2 0
2 1 1 1
4 1 0 0
Run Code Online (Sandbox Code Playgroud)
行中缺少3个,列中缺少2个,因为它们没有出现在数据中.
是否有一种简单的方法可以强制将其他行和列插入正确的位置,而是返回以下内容?
data.2
data.1 1 2 3 4
1 1 0 2 0
2 1 0 1 1
3 0 0 0 0
4 1 0 0 0
Run Code Online (Sandbox Code Playgroud) optimization ×2
python ×2
r ×2
contingency ×1
ggplot2 ×1
graph ×1
insets ×1
numpy ×1
physics ×1