How can I make my plot smoother in Python? - python

I have a function called calculate_cost which calculates the performance of supplier for different S_range (stocking level). The function works but the plots are not smooth, is there a way to smooth it in Python?
import numpy
import scipy.stats
import scipy.integrate
import scipy.misc
import matplotlib
import math
import pylab
from scipy.stats import poisson
def calculate_cost(s, h, d, r, k, alphaR):
cost = 0.0
for i in range(0, alphaR + 1):
#i = i-1
binom = math.factorial(r) / ((math.factorial(i)) * (math.factorial(r - i)))
func = scipy.stats.poisson.cdf(s, d)
cost += ((k/r) * binom * (func ** i) * ((1.0-func) ** (r-i)))
for p in range (s):
cost += h*(s-p)*scipy.stats.poisson.pmf(p, d) #This a formula
return cost
graphs = []
class Graph:
def __init__(self):
self.label = ""
self.h = 0
self.d = 0
self.r = 0
self.k = 0
self.alphaR = 0
graph = Graph()
graph.label = "A"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 283.0
graph.alphaR = 23
graphs.append(graph)
graph = Graph()
graph.label = "B"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 146.0
graph.alphaR = 24
#graph.LineStyle = '*-'
graphs.append(graph)
graph = Graph()
graph.label = "C"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 92.0
graph.alphaR = 25
#graph.LineStyle = '*-'
graphs.append(graph)
graph = Graph()
graph.label = "D"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 80.0
graph.alphaR = 26
#graph.LineStyle = '*-'
graphs.append(graph)
graph = Graph()
graph.label = "E"
graph.h = 1.0
graph.d = 10
graph.r = 30
graph.k = 77.0
graph.alphaR = 27
#graph.LineStyle = '*-'
graphs.append(graph)
s_range = numpy.arange(0,21,1)
for graph in graphs:
cost = []
for s in s_range:
cost.append(calculate_cost(s, graph.h, graph.d, graph.r, graph.k, graph.alphaR))
matplotlib.pyplot.plot(s_range, cost, label = graph.label)
pylab.legend()
matplotlib.pyplot.xlabel(' S_range')
matplotlib.pyplot.ylabel('Cost')
pylab.show()

One solution would be to use the scipy.iterp1D function with a 'cubic' type :
from scipy import interpolate
....
s_range = numpy.arange(0,21,1)
for graph in graphs:
cost = []
for s in s_range:
cost.append(calculate_cost(s, graph.h, graph.d, graph.r, graph.k, graph.alphaR))
f = interpolate.interp1d(s_range, cost, kind='cubic')
s_range_new = np.arange(0,20, 0.1)
cost_new = f(s_range_new)
matplotlib.pyplot.plot(s_range_new, cost_new, label = graph.label)
pylab.legend()
matplotlib.pyplot.xlabel(' S_range')
matplotlib.pyplot.ylabel('Cost')
pylab.show()
This gives you :
Be careful in how you use this as this is only interpolated points and not real data points.
Hope this helps

Related

GEKKO error in model expression with array of variables and intermediates

I am trying to use GEKKO for fitting and function parameters estimation.
I need to use arrays of variables and arrays of intermediate-type variables because of changing number of parameters to fit.
And got an error I think in a model.
apm some_ip_here_gk_model14 <br><pre> ----------------------------------------------------------------
APMonitor, Version 1.0.1
APMonitor Optimization Suite
----------------------------------------------------------------
--------- APM Model Size ------------
Each time step contains
Objects : 0
Constants : 2
Variables : 15
Intermediates: 22
Connections : 0
Equations : 24
Residuals : 2
#error: Model Expression
*** Error in syntax of function string: Invalid element: none
Position: 1
none
?
how to check what is this error?
I am running this code in jupyter notebook and I tried to look apm file - didn't find it in the folder where this jupyter notebook is situated. Where should I search?
Here is the code.
import numpy as np
from gekko import GEKKO
import math
M = 10; m = 1; gj =1; n = 1
num_pulses_in_window = 4
сonstant = 1; ac = 1
el_init_guess = [1,2,3,4]
borders_left = [1,2,3,4]
borders_right = [1,2,3,4]
A1_c = (M/(M+m))*сonstant
gj_c = gj
# using GEKKO for preliminary estomation
xData = np.array([1,2,3,4])
yData = np.array([2.5,1.2,3.2,1.1])
model = GEKKO()
# parameters
x = model.Param(value = xData)
z = model.Param(value = yData)
# constants
A1 = model.Const(A1_c)
gj = model.Const(gj_c)
# variables
E = model.Array(model.Var, num_pulses_in_window)
G1 = model.Array(model.Var, num_pulses_in_window)
G2 = model.Array(model.Var, num_pulses_in_window)
Gg = model.Array(model.Var, num_pulses_in_window)
#Intermediates
k_alfa = model.Intermediate(A1*model.sqrt(x))
ro = model.Intermediate(k_alfa*ac)
phi = model.Intermediate(ro)
G = model.Array(model.Intermediate, num_pulses_in_window, equation=None)
d = model.Array(model.Intermediate, num_pulses_in_window, equation=None)
f = model.Array(model.Intermediate, num_pulses_in_window, equation=None)
for i in range(0, num_pulses_in_window):
E[i].value = el_init_guess[i]
E[i].lower = borders_left[i]
E[i].upper = borders_right[i]
#G1
G1[i].lower = 0.0000001
G1[i].upper = 1
#G2
G2[i].lower = 0
G2[i].upper = 0
#Gg
Gg[i].lower = 0.0000001
Gg[i].upper = 1
G[i] = model.Intermediate(G1[i]+G2[i]+Gg[i])
d[i] = model.Intermediate((E[i]-x)**2+(G[i]/2)**2)
f[i] = model.Intermediate((1-(1-(G[i]*G1[i]/(2*d[i])))*model.cos(2*phi)-((E[i]-x)*G[i]/d[i])*model.sin(2*phi)))
sigma_sum = model.Intermediate(2*math.pi*gj/k_alfa * (model.sum(f)))
y = model.Var()
model.Equation(y == model.exp(-n*sigma_sum))
model.Minimize(((y-z))**2)
model.options.IMODE = 2
model.options.SOLVER = 3
model.options.MAX_ITER = 1000
model.solve(disp=1)
Intermediates are not defined with m.Array() because they are defined with the m.Intermediate() method. Try using an empty list instead:
G = [None]*num_pulses_in_window
d = [None]*num_pulses_in_window
f = [None]*num_pulses_in_window
For troubleshooting, open the run folder with model.open_folder() and inspect gk_model0.apm with a text editor. This is a plain text version of the model. The 4th and onward intermediates are not defined correctly.
Model
Constants
i0 = 0.9090909090909091
i1 = 1
End Constants
Parameters
p1
p2
End Parameters
Variables
v1 = 1, <= 1, >= 1
v2 = 2, <= 2, >= 2
v3 = 3, <= 3, >= 3
v4 = 4, <= 4, >= 4
...
v13 = 0, <= 1, >= 1e-07
v14 = 0, <= 1, >= 1e-07
v15 = 0, <= 1, >= 1e-07
v16 = 0, <= 1, >= 1e-07
v17 = 0
End Variables
Intermediates
i2=((i0)*(sqrt(p1)))
i3=((i2)*(1))
i4=i3
i5=None
i6=None
i7=None
i8=None
i9=None
...
Here is a script that runs successfully:
import numpy as np
from gekko import GEKKO
import math
M = 10; m = 1; gj =1; n = 1
num_pulses_in_window = 4
сonstant = 1; ac = 1
el_init_guess = [1,2,3,4]
borders_left = [1,2,3,4]
borders_right = [1,2,3,4]
A1_c = (M/(M+m))*сonstant
gj_c = gj
# using GEKKO for preliminary estomation
xData = np.array([1,2,3,4])
yData = np.array([2.5,1.2,3.2,1.1])
model = GEKKO()
# parameters
x = model.Param(value = xData)
z = model.Param(value = yData)
# constants
A1 = model.Const(A1_c)
gj = model.Const(gj_c)
# variables
E = model.Array(model.Var, num_pulses_in_window)
G1 = model.Array(model.Var, num_pulses_in_window)
G2 = model.Array(model.Var, num_pulses_in_window)
Gg = model.Array(model.Var, num_pulses_in_window)
#Intermediates
k_alfa = model.Intermediate(A1*model.sqrt(x))
ro = model.Intermediate(k_alfa*ac)
phi = model.Intermediate(ro)
G = [None]*num_pulses_in_window
d = [None]*num_pulses_in_window
f = [None]*num_pulses_in_window
for i in range(0, num_pulses_in_window):
E[i].value = el_init_guess[i]
E[i].lower = borders_left[i]
E[i].upper = borders_right[i]
#G1
G1[i].lower = 0.0000001
G1[i].upper = 1
#G2
G2[i].lower = 0
G2[i].upper = 0
#Gg
Gg[i].lower = 0.0000001
Gg[i].upper = 1
G[i] = model.Intermediate(G1[i]+G2[i]+Gg[i])
d[i] = model.Intermediate((E[i]-x)**2+(G[i]/2)**2)
f[i] = model.Intermediate((1-(1-(G[i]*G1[i]/(2*d[i])))*model.cos(2*phi)-((E[i]-x)*G[i]/d[i])*model.sin(2*phi)))
sigma_sum = model.Intermediate(2*math.pi*gj/k_alfa * (model.sum(f)))
y = model.Var()
model.Equation(y == model.exp(-n*sigma_sum))
model.Minimize(((y-z))**2)
model.options.IMODE = 2
model.options.SOLVER = 3
model.options.MAX_ITER = 1000
model.solve(disp=1)
Don't forget to include dummy values in your script so that it runs and produces the error. I edited the question to include sample values in your question:
M = 10; m = 1; gj =1; n = 1
num_pulses_in_window = 4
сonstant = 1; ac = 1
el_init_guess = [1,2,3,4]
borders_left = [1,2,3,4]
borders_right = [1,2,3,4]
A1_c = (M/(M+m))*сonstant
gj_c = gj
# using GEKKO for preliminary estomation
xData = np.array([1,2,3,4])
yData = np.array([2.5,1.2,3.2,1.1])

Python function calling with variable vs raw numbers

I am trying to implement a pso algorithm from Wikipedia https://en.wikipedia.org/wiki/Particle_swarm_optimization.
My problem is that when I am calling the cost function with a variable (Gbest), and then manually calling the cost function (with the Gbest data) I get a different output (cost) like the image bellow:
Code fault
I am new to python so thank you for any suggestions.
Here is the complete code:
import matplotlib.pyplot as plt
import numpy as np
from control.matlab import *
A = np.array([[0,0,1],[0,1,0],[1,2,-2]])
B = np.array( [[0],[1],[0]])
C = np.array([[0, 1,0]])
D = np.zeros([C.shape[0],B.shape[1]])
sys = ss(A,B,C,D)
sys_tf = tf(sys)
s = tf('s')
def cost(kp,ki):
global sys_tf, G, y, t, r
G = kp + ki/s
C = feedback(sys_tf*G, 1)
y, t = step(C, linspace(0,100))
r = np.ones(len(t))
return np.sum(y-r)**2
part = 100
ite = 10000
dim = 2
w = 0.001
wdamp = 0.99
phip = 0.9
phig = 0.1
blo, bup = -10,10
x = np.zeros([dim, part])
v = np.zeros([dim, part])
pbest = np.zeros([dim, part])
gbest = np.array([1000000,1000000])
for i in range(part):
for k in range(dim):
x[k][i] = pbest[k][i] = np.random.uniform(blo, bup)
v[k][i] = np.random.uniform(-np.abs(bup - blo), np.abs(bup - blo))
if cost(pbest[0][i], pbest[1][i]) < cost(gbest[0], gbest[1]):
gbest = np.array([pbest[0][i], pbest[1][i]])
for it in range(ite):
for i in range(part):
for k in range(dim):
rp = np.random.uniform(0,1)
rg = np.random.uniform(0,1)
v[k,:] = w*v[k,:] + phip*rp*(pbest[k,:] - x[k,:]) + phig*rg*(gbest[k] - x[k,:])
x[k,:] = x[k,:] + v[k,:]
w = w*wdamp
if cost(x[0][i], x[1][i]) < cost(pbest[0][i], pbest[1][i]):
pbest[:,i] = x[:,i]
if cost(pbest[0][i], pbest[1][i]) < cost(gbest[0], gbest[1]):
gbest = np.array([pbest[0][i], pbest[1][i]])
plt.plot(t, y, 'ro')
plt.plot(t, r, 'x')
plt.pause(0.005)
plt.title(gbest)
print([gbest, cost(gbest[0], gbest[1])])

MPC with python and Error ValueError: `f0` passed has more than 1 dimension

I wrote a MPC with Python and it worked before. After a long time I want to use it again but I got this Error
f0 passed has more than 1 dimension.
But I didn't change anything on my code. It is some kind of strange.
Here is my code:
import numpy as np
import numpy.linalg as npl
import matplotlib.pyplot as plt
from scipy.optimize import minimize
def mpcAugment(Am, Bm, Cm ):
"Function for Augmented Model"
nx, nu = Bm.shape
ny = Cm.shape[0]
A = np.zeros((nx+ny,nx+ny))
A[0:nx,0:nx] = Am
A[nx:nx+ny,0:nx] = Cm#Am
A[nx:nx+ny,nx:nx+ny] = np.eye(ny)
B = np.zeros((nx+ny,nu))
B[0:nx,:nu] = Bm
B[nx:nx+ny,:nu] = Cm#Bm
C = np.zeros((ny,nx+ny))
C[:ny,nx:nx+ny] = np.eye(ny)
return A, B, C
'Define Parameters'
k = 0.4
AICB = 153.8
mcp = 8.8e4
vamb1 = 30
vamb2 = 45
a = -k*AICB/mcp
b = -1/mcp
Ts = 20
VICBref = -5.0
Am = np.array([[1+Ts*a]])
Bm = np.array([[Ts*b]])
Gm = np.array([[-Ts*a]])
Cm = np.array([[1]])
A, B, C = mpcAugment(Am,Bm,Cm)
A, G, C = mpcAugment(Am,Gm,Cm)
nx, nu = B.shape
ny = C.shape[0]
nd = G.shape[1]
Np = 20
Nu = 5
F = np.zeros((Np*ny,nx))
PHI = np.zeros((Np*ny,Nu*nu))
PHIw = np.zeros((Np*ny,Np*nd))
for i in range(0,Np):
Ai = npl.matrix_power(A, i+1)
F[i*ny:(i+1)*ny,:] = C#Ai
for j in range(0, Nu):
if j <= i:
Aij = np.linalg.matrix_power(A, i-j)
PHI[i*ny:(i+1)*ny, j*nu:(j+1)*nu] = C#Aij#B
for j in range(0, Np):
if j <= i:
Aij = np.linalg.matrix_power(A, i-j)
PHIw[i*ny:(i+1)*ny, j*nd:(j+1)*nd] = C#Aij#G
umax = 3100
umin = 0
Q = np.eye(Np*ny)
R = 1e-2*np.eye(Nu*nu)
Rs = VICBref*np.ones((Np*ny,1))
Ainq = np.zeros((2*Nu*nu,Nu*nu))
binq = np.zeros((2*Nu*nu,1))
cinq = np.zeros((2*Nu*nu,1))
for i in range(0,Nu):
binq[i*nu:(i+1)*nu] = umax
binq[(i+Nu)*nu:(Nu+i+1)*nu] = 1
cinq[i*nu:(i+1)*nu] = 1
cinq[(i+Nu)*nu:(Nu+i+1)*nu] = -1
for j in range(0,i+1):
Ainq[i*nu:(i+1)*nu,j*nu:(j+1)*nu] = np.eye(nu)
Ainq[(i+Nu)*nu:(Nu+i+1)*nu,j*nu:(j+1)*nu] = np.eye(nu)
u0 = 0
def objective(du):
dU = np.array(du).reshape((len(du),1))
Y = F#x + PHI#dU + PHIw#w
return np.transpose((Rs-Y))#(Rs-Y)+np.transpose(dU)#R#(dU)
def constraint1(du):
dU = np.array(du).reshape((len(du),1))
return (binq - Ainq#dU - cinq*u0)[0]
#print(objective([1,1,1]))
ulim = (umin, umax)
bnds = np.kron(np.ones((Nu,1)),ulim)
#print(bnds)
Um = np.ones((nu*Nu,1))
Tsim = 5e4
time = np.arange(0,Tsim,Ts)
Nt = len(time)
xm = np.zeros((Nt,1))
um = np.zeros((Nt,nu))
ym = np.zeros((Nt,ny))
xm[0] = 0
ym[0] = Cm.dot(xm[0])
w = np.zeros((Np*nd,1))
print('Am = ',Am)
print('Bm = ',Bm)
print('Cm = ',Cm)
x = np.zeros((nx,1))
x[1] = xm[0]
vamb = vamb1
Vamb = np.zeros((Nt,1))
Ns = int(np.floor(Nt/2))
Vamb[0:Ns] = vamb1*np.ones((Ns,1))
Vamb[Ns:Nt] = vamb2*np.ones((Nt-Ns,1))
Vref = VICBref*np.ones((Nt,1))
con = {'type':'ineq','fun':constraint1}
for i in range(0,Nt-1):
sol = minimize(objective, Um, method = 'SLSQP',constraints = con)
if sol.success == False:
print('Error Cant solve problem')
exit()
Um = sol.x
um[i+1] = um[i] + Um[0]
u0 = um[i+1]
xm[i+1] = Am.dot(xm[i])+Bm.dot(um[i+1])+Gm.dot(Vamb[i])
ym[i+1] = Cm.dot(xm[i+1])
for j in range(0,Np):
if i+j < Nt:
Rs[j] = Vref[i+j]
w[j] = Vamb[i+j]-Vamb[i+j-1]
else:
Rs[j] = Vref[Nt-1]
w[j] = 0
x[0] = xm[i+1] - xm[i]
x[1] = xm[i+1]
print('Q = ',um[i+1],' , VICB = ',xm[i+1], ' vamb = ', Vamb[i])
hour = 60*60
plt.figure()
plt.subplot(2,1,1)
plt.plot(time/hour,ym)
plt.plot(time/hour,Vref,'--')
plt.xlabel('time(hours)')
plt.xlim([0, Tsim/hour])
plt.subplot(2,1,2)
plt.plot(time/hour,um)
plt.xlim([0, Tsim/hour])
plt.show()
It about a controller, which control the temperature of a cool box.
Is that possible that anything changed in main simply code?
I think the problem is now in minimizations part.
I reinstalled all of my libraries and it worked

GMRES residual plotting

I'm trying to do a plot of convergence of this GMRES alghorithm. I managed to create a class that make me print the residual at each iteration but I can't find a way to extract this data into an array so that i can plot it with matplotlib.
Here is my code:
matrixSize = 25
A = Atridiag(2, -1, -1, matrixSize)
A = scipy.sparse.csc_matrix (A)
b = np.matrix(np.ones((matrixSize, 1)))
x1 = np.matrix(np.ones((matrixSize, 1)))
M_i=scipy.sparse.linalg.spilu(A)
M2=scipy.sparse.linalg.LinearOperator((matrixSize,matrixSize),M_i.solve)
nmax_iter = 1
rstart = 1
tol = 1e-12
e = np.zeros((nmax_iter + 1, 1))
rr = 1
class gmres_counter(object):
def __init__(self, disp=True):
self._disp = disp
self.niter = 0
self.callbacks = []
def __call__(self, rk=None):
self.callbacks.append(str(rk))
self.niter += 1
if self._disp:
print('%s' %(str(rk)))
counter = gmres_counter()
x, info = scipy.sparse.linalg.gmres(A, b, x0=x1, tol=tol, restart=rstart,
M=M2, callback=counter)

Unable to run Numba on finished code

What am I doing wrong below? I have installed Anaconda on my Mac and Numba along with it. I am trying to run Numba on my Python code, following the instructions given in the section Python with Numba here: https://www.continuum.io/blog/developer/accelerating-python-libraries-numba-part-1
I need to run this code overnight by changing zzzz from 5 to 40. I am just using zzzz = 5 now as a test case. Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from numba import double
from numba.decorators import jit, autojit
#jit
def Kcrit():
# The data of the plot will be added in these lists
x_data_plot=[]
y_data_plot=[]
zzzz = 5
for N in range(2,zzzz,2):
#Constants and parameters
epsilon = 0.01
if N in range(2,11,2):
K00 = np.logspace(0,3,100,10)
elif N in range(12,21,2):
K00 = np.logspace(3,3.75,100,10)
elif N in range(22,31,2):
K00 = np.logspace(3.75,4.15,100,10)
else:
K00 = np.logspace(4.15,4.5,100,10)
len1 = len(K00)
y0 = [0]*(3*N/2+3)
Kplot = np.zeros((len1,1))
Pplot = np.zeros((len1,1))
S = [np.zeros((len1,1)) for kkkk in range(N/2+1)]
KS = [np.zeros((len1,1)) for kkkk in range(N/2)]
PS = [np.zeros((len1,1)) for kkkk in range(N/2)]
Splot = [np.zeros((len1,1)) for kkkk in range(N/2+1)]
KSplot = [np.zeros((len1,1)) for kkkk in range(N/2)]
PSplot = [np.zeros((len1,1)) for kkkk in range(N/2)]
for series in range(0,len1):
K0 = K00[series]
Q = 10
r1 = 0.0001
r2 = 0.001
a = 0.001
d = 0.001
k = 0.999
S10 = 1e5
P0 = 1
tf = 1e10
time = np.linspace(0,tf,len1)
#Defining dy/dt's
def f(y,t):
for alpha in range(0,(N/2+1)):
S[alpha] = y[alpha]
for beta in range((N/2)+1,N+1):
KS[beta-N/2-1] = y[beta]
for gamma in range(N+1,3*N/2+1):
PS[gamma-N-1] = y[gamma]
K = y[3*N/2+1]
P = y[3*N/2+2]
# The model equations
ydot = np.zeros((3*N/2+3,1))
B = range((N/2)+1,N+1)
G = range(N+1,3*N/2+1)
runsumPS = 0
runsum1 = 0
runsumKS = 0
runsum2 = 0
for m in range(0,N/2):
runsumPS = runsumPS + PS[m]
runsum1 = runsum1 + S[m+1]
runsumKS = runsumKS + KS[m]
runsum2 = runsum2 + S[m]
ydot[B[m]] = a*K*S[m]-(d+k+r1)*KS[m]
for i in range(0,N/2-1):
ydot[G[i]] = a*P*S[i+1]-(d+k+r1)*PS[i]
for p in range(1,N/2):
ydot[p] = -S[p]*(r1+a*K+a*P)+k*KS[p-1]+d*(PS[p-1]+KS[p])
ydot[0] = Q-(r1+a*K)*S[0]+d*KS[0]+k*runsumPS
ydot[N/2] = k*KS[N/2-1]-(r2+a*P)*S[N/2]+d*PS[N/2-1]
ydot[G[N/2-1]] = a*P*S[N/2]-(d+k+r2)*PS[N/2-1]
ydot[3*N/2+1] = (d+k+r1)*runsumKS-a*K*runsum2
ydot[3*N/2+2] = (d+k+r1)*(runsumPS-PS[N/2-1])- \
a*P*runsum1+(d+k+r2)*PS[N/2-1]
ydot_new = []
for j in range(0,3*N/2+3):
ydot_new.extend(ydot[j])
return ydot_new
# Initial conditions
y0[0] = S10
for i in range(1,3*N/2+1):
y0[i] = 0
y0[3*N/2+1] = K0
y0[3*N/2+2] = P0
# Solve the DEs
soln = odeint(f,y0,time, mxstep = 5000)
for alpha in range(0,(N/2+1)):
S[alpha] = soln[:,alpha]
for beta in range((N/2)+1,N+1):
KS[beta-N/2-1] = soln[:,beta]
for gamma in range(N+1,3*N/2+1):
PS[gamma-N-1] = soln[:,gamma]
for alpha in range(0,(N/2+1)):
Splot[alpha][series] = soln[len1-1,alpha]
for beta in range((N/2)+1,N+1):
KSplot[beta-N/2-1][series] = soln[len1-1,beta]
for gamma in range(N+1,3*N/2+1):
PSplot[gamma-N-1][series] = soln[len1-1,gamma]
u1 = 0
u2 = 0
u3 = 0
for alpha in range(0,(N/2+1)):
u1 = u1 + Splot[alpha]
for beta in range((N/2)+1,N+1):
u2 = u2 + KSplot[beta-N/2-1]
for gamma in range(N+1,3*N/2+1):
u3 = u3 + PSplot[gamma-N-1]
K = soln[:,3*N/2+1]
P = soln[:,3*N/2+2]
Kplot[series] = soln[len1-1,3*N/2+1]
Pplot[series] = soln[len1-1,3*N/2+2]
utot = u1+u2+u3
#Plot
Kcrit = abs((Q/r2)*(1+epsilon)-utot)
v,i = Kcrit.min(0),Kcrit.argmin(0)
# Save the new points for x and y
x_data_plot.append(N)
y_data_plot.append(K00[i])
# Make the plot of all the points together
plt.plot(x_data_plot,y_data_plot)
plt.xlabel('N', fontsize = 20)
plt.ylabel('$K_{crit}$', fontsize = 20)
plt.show()
This is what I typed in the terminal:
from numba import autojit
numba_k = autojit()(Kcrit)
This is my error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Kcrit' is not defined
Note that I am not asking whether Numba will actually speed up my code (that is an entirely different issue). I am just asking how to run it!
Help appreciated.

Categories