我第一次嘗試在 colab 中使用 Numba,我認為我已經成功安裝了 Numba,因為 @jit 現在不是未定義的,但我的代碼中出現錯誤。以下是我的嘗試:
!apt-get install nvidia-cuda-toolkit
!pip3 install numba
import os
dev_lib_path = !find / -iname 'libdevice'
nvvm_lib_path = !find / -iname 'libnvvm.so'
assert len(dev_lib_path)>0, "Device Lib Missing"
assert len(nvvm_lib_path)>0, "NVVM Missing"
os.environ['NUMBAPRO_LIBDEVICE'] = dev_lib_path[0]
os.environ['NUMBAPRO_NVVM'] = nvvm_lib_path[0]
import numpy as np
import matplotlib.pyplot as plt
import random
from math import *
from random import *
from numba import jit
n=1000
mu=np.random.uniform(0,1,n)
r=[sqrt(-2*log(1-i)) for i in mu]
eta=np.random.uniform(0,1,n)
theta=2*pi*eta;
cuz=[cos(i) for i in theta]
suz=[sin(i) for i in theta]
Zinitial=[a*b for a,b in zip(r,cuz)];
Pinitial=[a*b for a,b in zip(r,suz)];
class Particle:
def __init__(self, pos, mom, spin):
self.pos = pos
self.mom = mom
self.spin = spin
SP = sorted(np.array([Particle(pos = i, mom = j, spin = choice([1, 0])) for i,j in zip(Zinitial,Pinitial)]),key=lambda x:x.pos)
Upi=[];
Downi=[];
count_plot=[];
for j in range(len(SP)):
if SP[j].spin == 1:
Upi.append(SP[j].pos)
else:
Downi.append(SP[j].pos)
Zavgi=sum(Zinitial)/len(Zinitial)
Zreli=sum(Upi)/len(Upi)-sum(Downi)/len(Downi)
"Observables"
"Time"
iter=10**(5);
dt=1/(2*n);
alf=sqrt(n);
"Dynamics"
@jit(nopython=True)
def f():
counter=0;
sum1,sum2=0,0;
Zavg=[Zavgi];
Zrelm=[Zreli];
T_plot=[0];
for i in range(1,iter 1):
t=i*dt;
T_plot.append(t)
Z=[];
Up=[];
Down=[];
c,s=cos(t),sin(t);
c1,s1=cos(t-dt),sin(t-dt);
for j in range(n-1):
collchk=((c*(SP[j].pos) s*(SP[j].mom))-(c*(SP[j 1].pos) s*(SP[j 1].mom)))*(c1*(SP[j].pos) s1*(SP[j].mom)-(c1*(SP[j 1].pos) s1*(SP[j 1].mom)));
prel=((c*(SP[j].mom)-s*(SP[j].pos))-(c*(SP[j 1].mom)-s*(SP[j 1].pos)))/2;
rcoeff=1/(1 (prel*alf)**2);
rand_value=random();
if collchk<0:
SP[j], SP[j 1]=SP[j 1],SP[j];
if rcoeff>rand_value:
counter=counter 1
SP[j].spin,SP[j 1].spin=SP[j 1].spin,SP[j].spin;
if SP[j].spin == 1:
Up.append(c*(SP[j].pos) s*(SP[j].mom))
else:
Down.append(c*(SP[j].pos) s*(SP[j].mom))
Z.append(c*(SP[j].pos) s*(SP[j].mom))
Zrel=sum(Up[0:])/len(Up) - sum(Down[0:])/len(Down);
Zrelm.append(Zrel)
Zm=sum(Z)/len(Z)
Zavg.append(Zm)
return [Zavg, Zrelm, counter]
我在下面給出的 Vandan 代碼中遇到的錯誤:
Failed in nopython mode pipeline (step: nopython frontend)
Untyped global name 'sum': cannot determine Numba type of <class 'builtin_function_or_method'>
File "<ipython-input-1-cddc88c01635>", line 52:
def f(SP, Zavgi, Zreli, alf, dt, n):
<source elided>
Zrel = sum(Up[0:]) / len(Up) - sum(Down[0:]) / len(Down);
^
最后,我想繪制我回傳的串列。任何幫助將不勝感激,如果有一種方法可以使用 Numba,即使是對于類定義也會很棒。
編輯:
import numpy as np
import matplotlib.pyplot as plt
import random
from math import *
from random import *
from numba import jit
"Dynamics"
@jit(nopython=True)
def f(SP, Zavgi, Zreli, alf, dt, n):
"Time"
counter = 0;
sum1, sum2 = 0, 0;
Zavg = np.array([Zavgi]);
Zrelm = np.array([Zreli]);
T_plot = [0];
for i in range(1, iter 1):
t = i * dt;
T_plot.append(t)
Z = [];
Up = [];
Down = [];
c, s = cos(t), sin(t);
c1, s1 = cos(t - dt), sin(t - dt);
for j in range(n - 1):
collchk = ((c * (SP[j][0]) s * (SP[j][1])) - (c * (SP[j 1][0]) s * (SP[j 1][1]))) * (
c1 * (SP[j][0]) s1 * (SP[j][1]) - (c1 * (SP[j 1][0]) s1 * (SP[j 1][1])));
prel = ((c * (SP[j][1]) - s * (SP[j][0])) - (c * (SP[j 1][1]) - s * (SP[j 1][0]))) / 2;
rcoeff = 1 / (1 (prel * alf) ** 2);
rand_value = random();
if collchk < 0:
SP[j], SP[j 1] = SP[j 1], SP[j];
if rcoeff > rand_value:
counter = counter 1
SP[j][2], SP[j 1][2] = SP[j 1][2], SP[j][2];
if SP[j][2] == 1:
Up.append(c * (SP[j][0]) s * (SP[j][1]))
else:
Down.append(c * (SP[j][0]) s * (SP[j][1]))
Z.append(c * (SP[j][0]) s * (SP[j][1]))
Zrel = sum(Up[0:]) / len(Up) - sum(Down[0:]) / len(Down);
Zrelm = np.append(Zrelm, Zrel)
Zm = sum(Z) / len(Z)
Zavg = np.append(Zavg, Zm)
return Zavg, Zrelm, counter,T_plot
if __name__ == '__main__':
n = 1000
mu = np.random.uniform(0, 1, n)
r = [sqrt(-2 * log(1 - i)) for i in mu]
eta = np.random.uniform(0, 1, n)
theta = 2 * pi * eta;
cuz = [cos(i) for i in theta]
suz = [sin(i) for i in theta]
Zinitial = [a * b for a, b in zip(r, cuz)];
Pinitial = [a * b for a, b in zip(r, suz)];
iter = 10 ** (6);
dt = 1 / (100 * n);
alf = sqrt(n);
SP = np.array(sorted(np.array([ np.array([i,j,choice([0,1])]) for i, j in zip(Zinitial, Pinitial)]),
key=lambda x: x[0]))
Upi = [];
Downi = [];
count_plot = [];
for j in range(len(SP)):
if SP[j][2] == 1:
Upi.append(SP[j][0])
else:
Downi.append(SP[j][0])
Zavgi = sum(Zinitial) / len(Zinitial)
Zreli = sum(Upi) / len(Upi) - sum(Downi) / len(Downi)
Zavg, Zrelm, counter,T_plot = f(SP, Zavgi, Zreli, alf, dt, n)
plt.plot(T_plot, Zrelm)
uj5u.com熱心網友回復:
我稍微修改了您的代碼,并且能夠運行該功能。我洗掉了 Particle 類并將所有串列實體更改為 numpy 陣列。
這是 Zavg、Zrelm 和計數器的輸出:
Zavg: [0.07047501 0.06735052 0.06728123 ... 0.39516435 0.3947497 0.39433495]
Zrelm: [-0.04179043 -0.04461464 -0.0394889 ... -0.11080628 -0.11087257
-0.11093883]
Counter: 538
這是修改后的代碼:
import numpy as np
import matplotlib.pyplot as plt
import random
from math import *
from random import *
from numba import jit
"Dynamics"
@jit(nopython=True)
def f(SP, Zavgi, Zreli, alf, dt, n):
"Time"
counter = 0;
sum1, sum2 = 0, 0;
Zavg = np.array([Zavgi]);
Zrelm = np.array([Zreli]);
T_plot = [0];
for i in range(1, iter 1):
t = i * dt;
T_plot.append(t)
Z = [];
Up = [];
Down = [];
c, s = cos(t), sin(t);
c1, s1 = cos(t - dt), sin(t - dt);
for j in range(n - 1):
collchk = ((c * (SP[j][0]) s * (SP[j][1])) - (c * (SP[j 1][0]) s * (SP[j 1][1]))) * (
c1 * (SP[j][0]) s1 * (SP[j][1]) - (c1 * (SP[j 1][0]) s1 * (SP[j 1][1])));
prel = ((c * (SP[j][1]) - s * (SP[j][0])) - (c * (SP[j 1][1]) - s * (SP[j 1][0]))) / 2;
rcoeff = 1 / (1 (prel * alf) ** 2);
rand_value = random();
if collchk < 0:
SP[j], SP[j 1] = SP[j 1], SP[j];
if rcoeff > rand_value:
counter = counter 1
SP[j][2], SP[j 1][2] = SP[j 1][2], SP[j][2];
if SP[j][2] == 1:
Up.append(c * (SP[j][0]) s * (SP[j][1]))
else:
Down.append(c * (SP[j][0]) s * (SP[j][1]))
Z.append(c * (SP[j][0]) s * (SP[j][1]))
Zrel = np.sum(np.array(Up)) / len(Up) - np.sum(np.array(Down)) / len(Down);
Zrelm = np.append(Zrelm, Zrel)
Zm = np.sum(np.array(Z)) / len(Z)
Zavg = np.append(Zavg, Zm)
return Zavg, Zrelm, counter, T_plot
if __name__ == '__main__':
n = 1000
mu = np.random.uniform(0, 1, n)
r = [sqrt(-2 * log(1 - i)) for i in mu]
eta = np.random.uniform(0, 1, n)
theta = 2 * pi * eta;
cuz = [cos(i) for i in theta]
suz = [sin(i) for i in theta]
Zinitial = [a * b for a, b in zip(r, cuz)];
Pinitial = [a * b for a, b in zip(r, suz)];
iter = 10 ** (5);
dt = 1 / (2 * n);
alf = sqrt(n);
SP = np.array(sorted(np.array([ np.array([i,j,choice([0,1])]) for i, j in zip(Zinitial, Pinitial)]),
key=lambda x: x[0]))
Upi = [];
Downi = [];
count_plot = [];
for j in range(len(SP)):
if SP[j][2] == 1:
Upi.append(SP[j][0])
else:
Downi.append(SP[j][0])
Zavgi = sum(Zinitial) / len(Zinitial)
Zreli = sum(Upi) / len(Upi) - sum(Downi) / len(Downi)
Zavg, Zrelm, counter, T_plot = f(SP, Zavgi, Zreli, alf, dt, n)
print(Zavg, Zrelm, counter)
plt.plot(T_plot, Zrelm)
plt.show()
這是情節的樣子:

uj5u.com熱心網友回復:
出現錯誤是因為 Numba 嘗試訪問在編譯時型別未知的全域變數。實際上,SP是一個純 Python 串列,稱為反射串列,它可以包含不同型別的專案。Numba 不再支持這種串列。相反,Numba 支持與反射串列兼容的型別化串列。這意味著您需要構建一個新的型別串列(具有明確定義的型別)并將反映的串列項復制到型別串列中。與整體計算相比,此程序可能非常昂貴。因此,當可以使用陣列代替時(通常當您不知道最終串列的大小時),通常最好不要使用串列:Numpy 陣列明顯更快,更緊湊,使用它們的函式可以更快地編譯。
此外,Numba 不知道 was 是型別Particle。Numba 默認只支持 Numpy 內置型別。有對jitted 類的實驗性支持,但我建議您使用基本陣列,因為它通常更快且更靈活,因為您可以在目標陣列上使用 Numpy 矢量化函式,而不是基于物件的陣列(AFAIK 效率低下存盤在 Numpy 陣列中并且速度很慢)。
此外,您應該真正避免使用全域變數,尤其是那些變異的變數。全域變數在 CPython 中訪問速度較慢,通常被視為一種糟糕的軟體工程實踐。對于 Numba,它們被視為編譯時間常數,因此如果變數在運行時發生突變,可能會導致一些令人驚訝的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/484055.html
