My global variables are not working in my code. I'm fairly new to this and I can't seem to figure this out: I have set variables (only showing gna for this), which can be manipulated by an entry field, triggered by a corresponding button. For some reason, it's not taking the changes within the loop. I'm trying to make it to where the changed variable can be graphed as well, but it gives me the following error:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args) File "G:/PYTHON/Eulers.py", line 64, in graph
v[i + 1] = 1 / c * (gna * f[i] - gk * u[i]) * del_t + v[i]
TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('< U32') dtype('< U32') dtype('< U32')
Here is the code:
gna = 0.9
gnalabel = Label(topFrame, text="gna = %s" % gna)
gnalabel.pack()
gnaEntry = Entry(topFrame, justify=CENTER)
gnaEntry.pack()
def gnacallback():
global gna
gna = gnaEntry.get()
gnalabel.config(text="C = %s" % gna)
gnaButton = Button(topFrame, text="Change", width=10, command=gnacallback)
gnaButton.pack()
def graph():
global c, gna, gk, beta, gamma
for i in range(0, len(t)-1):
stinum = np.floor(i / 3000)
stimt = 3000 + 3000 * (stinum - 1)
f[i] = v[i] * (1 - (((v[i]) ** 2) / 3))
v[i + 1] = 1 / c * (gna * f[i] - gk * u[i]) * del_t + v[i]
if(i == stimt):
v[i + 1] = v[i + 1] + v_stim
u[i + 1] = (v[i] + beta - gamma * u[i]) * del_t + u[i]
plt.plot(v)
plt.show()
gna = gnaEntry.get()
Entry.get returns a string, which is probably an unsuitable type for the arithmetic you're doing in graph. Try converting to a number first.
gna = float(gnaEntry.get()) #or perhaps `int` if it's always an integer
Related
I'm currently trying to run this block of code.
# %% Imports
import numpy as np
import sympy as sy
import scipy as sc
alpha = sy.Symbol('alpha', real=True)
beta = sy.Symbol('beta', real=True)
s_0 = sy.Symbol('s_0', real=True)
s_1 = sy.Symbol('s_1', real=True)
s_2 = sy.Symbol('s_2', real=True)
t = sy.Symbol('t', real=True)
#run checks on S(t) whether S(t) > S0 for current iteration
def main():
# A. Defining equations to constant variables to be called later
#S(t) > S0, (S(t) + β/α)*S(t) > 0
MODEL_1_1 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) > S0, (S(t) + β/α)*S(t) < 0
MODEL_1_2 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(beta*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(beta*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_3 = ((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 - (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#S(t) < S0, (S(t) + β/α)*S(t) > 0
MODEL_1_4 = -((beta/alpha) * (1/sy.Abs((s_0 + beta/alpha)/s_0)) * sy.exp(-sy.Abs(beta)*t)) / (1 + (1/sy.Abs((s_0 + beta/alpha)/s_0) * sy.exp(-sy.Abs(beta)*t)))
#---------------------------------------------------------------
# B. Initializing values
stock_price = [25725, 25600, 24600]
#---------------------------------------------------------------
# C. Get 2 functions for every t = 1 and t = 2
## C.1. processing t1
if (stock_price[1] > stock_price[0]):
eq1 = MODEL_1_1.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_2.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq1 = MODEL_1_3.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq2 = MODEL_1_4.subs([(t,1),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq1)
#print(eq2)
## C.2. processing t2
if (stock_price[2] > stock_price[0]):
eq3 = MODEL_1_1.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_2.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
else:
eq3 = MODEL_1_3.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) > 0
eq4 = MODEL_1_4.subs([(t,2),(s_0,stock_price[0])]) #(S(t) + β/α)*S(t) < 0
#print(eq3)
#print(eq4)
#------------------------------------------------
# D. Run 4 different solution, get 4 sets of possible (α,β) pair
## D.1. eq1 vs. eq3 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) > 0
print(eq1)
print(eq3)
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
print(sol1)
## D.2. eq2 vs. eq3 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) > 0
## D.3. eq1 vs. eq4 -- (S(1) + β/α)*S(1) > 0, (S(2) + β/α)*S(2) < 0
## D.4. eq2 vs. eq4 -- (S(1) + β/α)*S(1) < 0, (S(2) + β/α)*S(2) < 0
#check for contradictions against initial condition
#return values that satisfies all condition
#run t = 3 based on the iteration
#repeat
main()
However it keeps throwing
Could not find root within given tolerance. (655317900.776688019361 >
2.16840434497100886801e-19) Try another starting point or tweak arguments.
or
matrix is numerically singular
whenever I try to tweak around the initial starting point.
Could anyone help / suggest alternatives to nsolve for this particular function?
Edit 1:
adding tracebacks
Traceback (most recent call last):
File "D:\SKRIPSI ANDREE\Code\model1.py", line 76, in <module>
main()
File "D:\SKRIPSI ANDREE\Code\model1.py", line 64, in main
sol1 = sy.solvers.nsolve([sy.Eq(eq1,stock_price[1]), sy.Eq(eq3,stock_price[2])],[alpha,beta],[-1,1])
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\utilities\decorator.py", line 88, in func_wrapper
return func(*args, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\solvers\solvers.py", line 2954, in nsolve
x = findroot(f, x0, J=J, **kwargs)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 969, in findroot
for x, error in iterations:
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\calculus\optimization.py", line 660, in __iter__
s = self.ctx.lu_solve(Jx, fxn)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 226, in lu_solve
A, p = ctx.LU_decomp(A)
File "C:\Users\Andre\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\matrices\linalg.py", line 136, in LU_decomp
raise ZeroDivisionError('matrix is numerically singular')
ZeroDivisionError: matrix is numerically singular
I currently have the below as my Euler function but i would like to try this same function using the Runge-Kutta method as i believe it is more accurate
def Euler(U,V,n,dt):
images = []
for i in range(n):
Uc = U[1:-1, 1:-1]
Vc = V[1:-1, 1:-1]
U[1:-1, 1:-1]=Uc + dt * (Du * laplace(U,hx,ht) + F(Uc,Vc))
V[1:-1, 1:-1]=Vc + dt * (Dv * laplace(V,hx,ht) + G(Uc,Vc))
U=periodic(U)
V=periodic(V)
if i % 500 == 0:
images.append(V)
return images
I have tried to do this below however i can't get this to run at all
def RK4_2_d(U,V,t,c):
for k in range(len(t)-1):
uu=np.zeros((U.shape[0],V.shape[0]))
K1=ht*c*laplace(U[k,:,:],hx,hy);uu[1:-1,1:-1]=K1
K2=ht*c*laplace(U[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K2
K3=ht*c*laplace([U[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K3
K4=ht*c*laplace(U[k,:,:]+uu,hx,hy)
K1=ht*c*laplace(V[k,:,:],hx,hy);uu[1:-1,1:-1]=K1
K2=ht*c*laplace(V[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K2
K3=ht*c*laplace(V[k,:,:]+uu/2,hx,hy);uu[1:-1,1:-1]=K3
K4=ht*c*laplace(V[k,:,:]+uu,hx,hy)
U[1:-1, 1:-1]=Uc + dt * (Du * laplace(U,hx,ht) + F(Uc,Vc))
V[1:-1, 1:-1]=Vc + dt * (Dv * laplace(V,hx,ht) + G(Uc,Vc))
U=periodic(U)
V=periodic(V)
if i % 500 == 0:
images.append(V)
return images
Am i going the right way about this?
I am trying to solve a PDE using odeint and the method of lines. My code is definitely wrong - and I'm trying to figure out where it is going wrong.
I am calling the ode solver using odeint(odefunc,y0,tspan) where tspan = np.linspace(0.0, 0.5, 5) & y0 = 1.0*np.ones(3).
I tried printing t within odefunc and am confused by the output. Despite the fact that I am solving up to t=0.5, the last t-value to print is 0.015081203121127767. The number of outputs matches tspan, but I cannot see how it could possibly be solving up to t = 0.5 when the last time in the de function is 0.015. What am I missing?
My DE is time dependent - so this is making it very hard to figure out where things are going wrong because I don't seem to be seeing the times where everything fails.
ETA - this is failing, but running this without some of the irrelevant stuff I am getting the warning ODEintWarning: Excess work done on this call (perhaps wrong Dfun type). Run with full_output = 1 to get quantitative information., which I'm assuming is part of the issue - but it doesn't appear to be halting the code.
MWE
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
import sys
plt.interactive(False)
sigma = 2320
rho = 1000
gravity = 9.81 # [m/s^2]
g = gravity*3600*3600 # [m/hour^2]
S = 0.01
settlingVelocity = 0.02 # [m/s]
ws = settlingVelocity*3600 # [m/hour]
n = 0.04 # [SI]
J = 400 # [Ws/m]
k = 0.02
Cstar = 0.2 * sigma # [kg/m^3]
W = 2 # [m]
D0 = 1.2
Lw = 20
L = 100
tend = 0.5 # in hours
tspan = np.linspace(0.0, tend, 5)
def d(t): # metres
if t < 50: # hours
return 0.5
else:
return 0.05
def Q(t):
return 3600 * (math.sqrt(S)/n)*((W*d(t))**(5/3))/((2*d(t) + W)**(2/3))
def h(t):
return d(t)/2
def beta(t):
return (sigma - rho) * g * h(t)/sigma
def Omega(t):
return rho * g * S * Q(t) # [W/m]
def PsiTime(t):
return rho * g * Q(t) * (D0 - d(t))/(Lw)
N = 10
X = np.linspace(0, L, N)
delX = L/ (N-1)
def odefunc(y, t):
def zetaEh(t):
return k * (PsiTime(t) + Omega(t)) / (J + beta(t))
def zetaEW(t):
return (2*d(t)/(W + 2*d(t))) * k * Omega(t)/(J + beta(t))
def zetaR(t):
return (W/(W + 2*d(t))) * k*Omega(t)/(beta(t))
def zetaEF(t,i):
return (W/(W + 2*d(t))) * k * Omega(t) / (J + beta(t))
C = y[:N]
M = y[N:]
print("time: ", t)
dCdt = np.zeros(X.shape)
dMdt = np.zeros(X.shape)
dCdt[0] = ( # forward difference for dCdx
-Q(t) / (W*d(t)) * (C[1] - C[0]) / delX
+ (zetaEh(t) / (W * d(t))) * ((Cstar - C[0]) / Cstar)
- (ws * C[0] * (beta(t))) / (d(t) * (J + beta(t)))
)
dMdt[0] = 0
# gully channel
for i in range (1, N-1): # central difference
if M[i] + W *C[i] * ws - zetaR(t) * (Cstar - C[i]) / Cstar < 0:
reMass = M[i] + W * C[i] * ws
dCdt[i] = (
-Q(t) / (W*d(t)) * (C[i+1] - C[i - 1]) / (2*delX)
+ 1 / (W * d(t)) * ((zetaEW(t) + zetaEF(t,i)) * (Cstar - C[i]) / Cstar
+ reMass * (1 - (beta(t))/ (J + beta(t))))
- C[i] * ws/d(t)
)
dMdt[i] = -M[i]
else:
dCdt[i] = (
-Q(t) / (W*d(t)) * (C[i+1] - C[i - 1]) / (2*delX)
+ 1 / (W * d(t)) * (zetaEW(t) + zetaR(t)) * (Cstar - C[i]) / Cstar
- C[i] * ws / d(t)
)
dMdt[i] = W * C[i] * ws - zetaR(t) * (Cstar - C[i]) / Cstar
# Final node - backward difference
if M[N-1] + W * C[N-1] * ws - zetaR(t) * (Cstar - C[N-1]) / Cstar < 0:
reMass = M[N-1] + W * C[N-1] * ws
dCdt[N-1] = (
-Q(t) / (W * d(t)) * (C[N-1] - C[N-2]) / delX
+ 1 / (W * d(t)) * ((zetaEW(t) + zetaEF(t, i)) * (Cstar - C[N-1]) / Cstar
+ reMass * (1 - (beta(t)) / (J + beta(t))))
- C[i] * ws / d(t)
)
dMdt[N-1] = -M[N-1]
else:
dCdt[N-1] = (
-Q(t) / (W * d(t)) * (C[N-2] - C[N - 1]) / delX
+ 1 / (W * d(t)) * (zetaEW(t) + zetaR(t)) * (Cstar - C[N-1]) / Cstar
- C[N-1] * ws / d(t)
)
dMdt[N-1] = W * C[N-1] * ws - zetaR(t) * (Cstar - C[N-1]) / Cstar
dydt = np.ravel([dCdt, dMdt])
return dydt
init_C = 0.0 * np.ones(X.shape)
init_M = 0.0 * np.ones(X.shape)
init= np.ravel([init_C, init_M])
sol = odeint(odefunc, init, tspan)
conc = sol[:, :N]
I have an ODE system. I'm looking for a solution of the system using PyDSTool. I try to put the integration step, but I get an error.
import PyDSTool as ds
from PyDSTool import Par, Var
import time
from PyDSTool import *
# Declare names and initial values for (symbolic) parameters
varepsilon = pow(10, -2)
j = 2.5*pow(10, -5)
e = 3.0
y8 = lambda y1,y5,y7: 1 / (1 - 2 / y1) * math.sqrt(y5 ** 2 + (1 - 2 / y1) * (1 + y1 ** 2 * y7 ** 2))
E0 = lambda y1,y8: (1 - 2 / y1) * y8
Phi0 = lambda y1,y7: y1 ** 2 * y7
# Compute nontrivial boundary equilibrium initial condition from parameters (see reference for derivation)
u0 = -math.sqrt(-1 + math.sqrt(varepsilon ** 2 + 12) / varepsilon) * math.sqrt(2) / 6
v0 = 1 / (1 - 2 / e) * math.sqrt(j ** 2 + (1 - 2 / e) * (e ** 2 * u0 ** 2 + 1))
y08 = y8(y1=e, y5=j, y7=u0);
E = E0(y1=e, y8=y08); Phi = Phi0(y1=e, y7=u0)
z01, z03, z04, z05, z07, z08 = e, 0.0, 0.0, j, u0, v0
# Declare symbolic variables
z1, z3, z4, z5, z7, z8 = Var('z1'), Var('z3'), Var('z4'), Var('z5'), Var('z7'), Var('z8')
# Create Symbolic Quantity objects for definitions
p1 = -z1*z5/(z1 - 2);
p3 = -z1**2 *z7;
p4 = z8*(1 - 2/z1);
Q1 = -z5**2/(z1*(z1 - 2)) + (z8**2/z1**3 - z7**2)*(z1 - 2);
Q3 = 2*z5*z7/z1;
Q4 = 2*z5*z8/(z1*(z1 - 2));
c1 = z1*z7*varepsilon;
c3 = -z1*z5*varepsilon;
C = z7*varepsilon/z1 - z8*(1 - 2/z1);
d1 = -z1*z8*varepsilon;
d3 = z1*z5*varepsilon;
B = z1**2*z7 - z8*varepsilon*(1 - 2/z1);
Omega = 1/(c1*d3*p3+c3*d1*p4-c3*d3*p1);
# differential equations
z1dot = z5;
z3dot = z7;
z4dot = z8;
z5dot = Omega*(-Q1*c1*d3*p3 - Q1*c3*d1*p4 + Q1*c3*d3*p1 + B*c3*p4 + C*d3*p3 + E*d3*p3 - Phi*c3*p4);
z7dot = -Omega*(Q3*c1*d3*p3 + Q3*c3*d1*p4 - Q3*c3*d3*p1 + B*c1*p4 - C*d1*p4 + C*d3*p1 - E*d1*p4 + E*d3*p1 - Phi*c1*p4);
z8dot = Omega*(-Q4*c1*d3*p3 - Q4*c3*d1*p4 + Q4*c3*d3*p1 + B*c1*p3 - B*c3*p1 - C*d1*p3 - E*d1*p3 - Phi*c1*p3 + Phi*c3*p1);
# Build Generator
DSargs = args(name='Sining particle')
#print(dir(DSargs))
#DSargs.pars = [varepsilon, j, e]
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
DSargs.tdata = [0.0, 0.1]
DSargs.varspecs = args(z1=z1dot, z3=z3dot, z4=z4dot, z5=z5dot, z7=z7dot, z8=z8dot)
# Use eval method to get a float value from the symbolic definitions given in
# terms of parameter values
DSargs.ics = args(z1=z01, z3=z03, z4=z04, z5=z05, z7=z07, z8=z08)
ode = Generator.Vode_ODEsystem(DSargs)
t = time.time()
result = ode.compute('test')
print("time for integration: %f" %(time.time() - t))
pts = result.sample()
plt.plot(pts['t'], pts['z7'], label='x')
plt.legend()
plt.xlabel('t')
plt.show()
Through the next lines I get an the error:
DSargs.MaxNumPoints = 450
DSargs.MaxStepSize = 2e-2
DSargs.MinStepSize = 1e-5
DSargs.StepSize = e-2
Traceback (most recent call last):
File "C:\Users\mykola\Downloads\pydstool.py", line 65, in <module>
ode = Generator.Vode_ODEsystem(DSargs)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\Vode_ODEsystem.py", line 47, in __init__
ODEsystem.__init__(self, kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\ODEsystem.py", line 61, in __init__
self.checkArgs(kw)
File "C:\Users\mykola\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PyDSTool\Generator\baseclasses.py", line 1069, in checkArgs
raise PyDSTool_KeyError('Invalid keyword arguments for this class')
PyDSTool.errors.PyDSTool_KeyError: 'Invalid keyword arguments for this class'
The library PyDSTool has very little training information in internet.
What I do wrong?. And how to correctly determine the step of integration?
I have some code that I would like to run.
Im new to python, as well as stackoverflow
Here is the python program:
# Circle Inversion Fractals (Apollonian Gasket) (Escape-time Algorithm)
# FB36 - 20131031
import math
import random
from collections import deque
from PIL import Image
imgx = 512; imgy = 512
image = Image.new("RGB", (imgx, imgy))
pixels = image.load()
n = random.randint(3, 6) # of main circles
a = math.pi * 2.0 / n
r = math.sin(a) / math.sin((math.pi - a) / 2.0) / 2.0 # r of main circles
h = math.sqrt(1.0 - r * r)
xa = -h; xb = h; ya = -h; yb = h # viewing area
cx = [0.0]; cy = [0.0]; cr = [1.0 - r] # center circle
for i in range(n): # add main circles
cx.append(math.cos(a * i))
cy.append(math.sin(a * i))
cr.append(r)
maxIt = 64 # of iterations
for ky in range(imgy):
print str(100 * ky / (imgy - 1)).zfill(3) + "%"
for kx in range(imgx):
x = float(kx) / (imgx - 1) * (xb - xa) + xa
y = float(ky) / (imgy - 1) * (yb - ya) + ya
queue = deque([])
queue.append((x, y, 0))
while len(queue) > 0: # iterate points until none left
(x, y, i) = queue.popleft()
for k in range(n + 1):
dx = x - cx[k]; dy = y - cy[k]
d = math.hypot(dx, dy)
if d <= cr[k]:
dx = dx / d; dy = dy / d
dnew = cr[k] ** 2.0 / d
xnew = dnew * dx + cx[k]
ynew = dnew * dy + cy[k]
if xnew >= xa and xnew <= xb and ynew >= ya and ynew <= yb:
if i + 1 == maxIt: break
queue.append((xnew, ynew, i + 1))
pixels[kx, ky] = (i % 16 * 16 , i % 8 * 32, i % 4 * 64)
image.save("CircleInversionFractal_" + str(n) + ".png", "PNG")
When I run it, I get an error message but I don't know how to resolve it.
Traceback (most recent call last):
File "U:\Personal\PythonFiles\Python Program Examples\Circle Inversion Fractals.py", line 9, in <module>
image = Image.new("RGB", (imgx, imgy))
AttributeError: 'module' object has no attribute 'new'
What does this traceback mean?
It means that you are trying to use the name new on a module object:
>>> import sys
>>> sys.new
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'new'
It means the sys module has no attribute new here. It doesn't matter if you are treating new as a callable (function, method, class, etc.), in the expression sys.new() the name new will first be looked up as an attribute.
If you are trying to use a module that is documented to have a .new() method (such as sha.new() or hashlib.new(), then make sure you don't have another module by the same name in your path. Don't name your own script sha.py when you try to import the standard library module sha!
You can check where a module was imported from by printing the .__file__ filename:
print sha.__file__
and if it is not a filename in your Python installation you perhaps need to investigate why you have an extra file in your path and rename that file or move it aside.