Not understandable variable output - python

I was writing code to calculate the average angle method. But the problem came when I tried to initialize a variable called i_. Have a look at my code.
import numpy as np
def delta_north(md1, md2, i1, i2, az1, az2):
md = md2 - md1
i = (i1 + i2)/2
az = (az1 + az2)/2
return md * np.sin(np.radians(i)) * np.cos(np.radians(az))
def delta_east(md1, md2, i1, i2, az1, az2):
md = md2 - md1
i = (i1 + i2)/2
az = (az1 + az2)/2
return md * np.sin(np.radians(i)) * np.sin(np.radians(az))
def delta_tvd(md1, md2, i1, i2):
md = md2 - md1
i = (i1 + i2)/2
return md * np.cos(np.radians(i))
def arc(q, i):
return np.degrees(30/q) * np.radians(i)
# Input variables
kick_off = 200
hold = 500
i1 = 15
step = 5
q = 3
# Initialize start points
md_ = 0
i_ = 0
az_ = 0
# Initialize end points
_md = md_ - kick_off
_i = i_
_az = az_
# Initialize md, i and az arrays
_md_ = np.linspace(md_, _md, 100)
_i_ = np.linspace(i_, _i, 100)
_az_ = np.linspace(az_, _az, 100)
# Initialize empty arrays for east, north and tvd
_east_ = np.array([])
_north_ = np.array([])
_tvd_ = np.array([])
# Calculate average angle on each array
for j in range(99):
_east_ = np.append(_east_, delta_east(_md_[j], _md_[j+1], _i_[j], _i_[j+1], _az_[j], _az_[j+1]))
_north_ = np.append(_north_, delta_north(_md_[j], _md_[j+1], _i_[j], _i_[j+1], _az_[j], _az_[j+1]))
_tvd_ = np.append(_tvd_, delta_tvd(_md_[j], _md_[j+1], _i_[j], _i_[j+1]))
Under Initialize start points comment I created this variable. But after the code ran successfully, I got such an output from thei_ variable:
'import numpy as np\nimport pandas as pd\n\ndef delta_north(md1, md2, i1, i2, az1, az2):\n md = md2 - md1\n i = (i1 + i2)/2\n az = (az1 + az2)/2\n return md * np.sin(np.radians(i)) * np.cos(np.radians(az))\n\ndef delta_east(md1, md2, i1, i2, az1, az2):\n md = md2 - md1\n i = (i1 + i2)/2\n az = (az1 + az2)/2\n return md * np.sin(np.radians(i)) * np.sin(np.radians(az))\n\ndef delta_tvd(md1, md2, i1, i2):\n md = md2 - md1\n i = (i1 + i2)/2\n return md * np.cos(np.radians(i))\n\ndef arc(q, i):\n return np.degrees(30/q) * np.radians(i)\n\n# Input variables\nkick_off = 200\nhold = 500\ni1 = 15\nstep = 5\nq = 3\n\n# Initialize start points\nmd_ = 0\ni_ = 0\naz_ = 0\n\n# Initialize end points\n_md = md_ - kick_off\n_i = i_\n_az = az_\n\n# Initialize md, i and az arrays\n_md_ = np.linspace(md_, _md, 100)\n_i_ = np.linspace(i_, _i, 100)\n_az_ = np.linspace(az_, _az, 100)\n\n# Initialize empty arrays for east, north and tvd\n_east_ = np.array([])\n_north_ = np.array([])\n_tvd_ = np.array([])\n\n# Calculate average angle on each array\nfor j in range(99):\n _east_ = np.append(_east_, delta_east(_md_[j], _md_[j+1], _i_[j], _i_[j+1], _az_[j], _az_[j+1]))\n _north_ = np.append(_north_, delta_north(_md_[j], _md_[j+1], _i_[j], _i_[j+1], _az_[j], _az_[j+1]))\n _tvd_ = np.append(_tvd_, delta_tvd(_md_[j], _md_[j+1], _i_[j], _i_[j+1]))'
I tried to rename the variable, and it works. But I need to keep my previous name. I want to get a normal variable output—some number.

Related

Conjugate gradient with tensorflow and sparse tensor runs slower than scipy with sparse matrices

I implemented the conjugate gradient method using TensorFlow to invert a sparse matrix.
The matrix I used to test the method is well-conditioned, as it is the sum of a mass matrix and a stiffness matrix obtained with finite elements.
I compared with the same method implemented using scipy and on the same data.
The solutions obtained with either methods are the same, however, TensorFlow is 5 times slower (I tested under colab environment).
Under colab environment, scipy ran in 0.27 s, while TensorFlow required 1.37 s
Why the algorithm is so slow under TensorFlow?
I can not cast to dense matrices, as I want to use the formula with matrices of large size (100k X100k or more).
Thanks,
Cesare
Here is the code I used to test this:
import tensorflow as tf
import numpy as np
from scipy.sparse import coo_matrix,linalg
import os
import sys
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from time import time
from scipy.spatial import Delaunay
def create_mesh(Lx=1,Ly=1,Nx=100,Ny=100):
mesh0=dict()
dx = Lx/Nx
dy = Ly/Ny
XX,YY=np.meshgrid(np.arange(0,Lx+dx,dx),np.arange(0,Ly+dy,dy))
points=np.vstack((XX.ravel(),YY.ravel())).T
#np.random.shuffle(points)
tri = Delaunay(points)
mesh0['Pts']=np.copy(points).astype(np.float32)
mesh0['Tria']=np.copy(tri.simplices).astype(int)
return(mesh0)
def eval_connectivity(mesh0):
print('computing mesh connectivity')
npt=mesh0['Pts'].shape[0]
connectivity = {}
for jpt in range(npt):
connectivity[jpt] = []
for Tria in mesh0['Tria']:
for ilpt in range(3):
iglobalPt=Tria[ilpt]
for jlpt in range(1+ilpt,3):
jglobalPt=Tria[jlpt]
connectivity[iglobalPt].append(jglobalPt)
connectivity[jglobalPt].append(iglobalPt)
for key,value in connectivity.items():
connectivity[key]=np.unique(np.array(value,dtype=int))
return(connectivity)
def eval_local_mass(mesh0,iTri):
lmass = np.zeros(shape=(3,3),dtype=np.float32)
Tria=mesh0['Tria'][iTri]
v10 = mesh0['Pts'][Tria[1],:]-mesh0['Pts'][Tria[0],:]
v20 = mesh0['Pts'][Tria[2],:]-mesh0['Pts'][Tria[0],:]
N12 = np.cross(v10,v20)
Tsurf = 0.5*np.linalg.norm(N12)
for ipt in range(3):
lmass[ipt,ipt]=1.0/12.0
for jpt in range(1+ipt,3):
lmass[ipt,jpt] = 1.0/24.0
lmass[jpt,ipt] = lmass[ipt,jpt]
lmass = 2.0*Tsurf*lmass
return(lmass)
def eval_local_stiffness(mesh0,iTri):
Tria = mesh0['Tria'][iTri]
v10 = mesh0['Pts'][Tria[1],:]-mesh0['Pts'][Tria[0],:]
v20 = mesh0['Pts'][Tria[2],:]-mesh0['Pts'][Tria[0],:]
N12 = np.cross(v10,v20)
Tsurf = 0.5*np.linalg.norm(N12)
covbT = np.zeros(shape=(3,3),dtype=np.float32)
covbT[0,:2] = v10
covbT[1,:2] = v20
covbT[2,2] = N12/(2*Tsurf)
contrb = np.linalg.inv(covbT)
v1 = contrb[:,0]
v2 = contrb[:,1]
a = np.dot(v1,v1)
b = np.dot(v1,v2)
c = np.dot(v2,v2)
gij_c = np.array([[a,b],[b,c]],dtype=np.float32)
lgrad = np.array([[-1.0,1.0,0.0], [-1.0,0.0,1.0] ],dtype=np.float32)
lstif = Tsurf*np.matmul( np.matmul(lgrad.T,gij_c), lgrad )
return(lstif)
def compute_vectors_sparse_matrices(mesh0):
npt = mesh0['Pts'].shape[0]
connect = eval_connectivity(mesh0)
nzero = 0
for key,value in connect.items():
nzero += (1+value.shape[0])
I = np.zeros(shape=(nzero),dtype=int)
J = np.zeros(shape=(nzero),dtype=int)
VM = np.zeros(shape=(nzero),dtype=np.float32)
VS = np.zeros(shape=(nzero),dtype=np.float32)
k0 = np.zeros(shape=(npt+1),dtype=int)
k0[0] = 0
k = -1
for jpt in range(npt):
loc_con = connect[jpt].tolist()[:]
loc_con.append(jpt)
loc_con = np.sort(loc_con)
k0[jpt+1]=k0[jpt]+loc_con.shape[0]
for jloc in range(loc_con.shape[0]):
k=k+1
I[k]= jpt
J[k]= loc_con[jloc]
for iTr, Tria in enumerate(mesh0['Tria']):
lstiff = eval_local_stiffness(mesh0,iTr)
lmass = eval_local_mass(mesh0,iTr)
for iEntry,irow in enumerate(Tria):
loc_con = connect[irow].tolist()[:]
loc_con.append(irow)
loc_con = np.sort(loc_con)
for jEntry,jcol in enumerate(Tria):
indexEntry = k0[irow]+np.where(loc_con==jcol)[0]
VM[indexEntry] = VM[indexEntry]+lmass[iEntry,jEntry]
VS[indexEntry] = VS[indexEntry]+lstiff[iEntry,jEntry]
return(I,J,VM,VS)
def compute_global_sparse_matrices(mesh0):
I,J,VM,VS = compute_vectors_sparse_matrices(mesh0)
npt = mesh0['Pts'].shape[0]
MASS = coo_matrix((VM,(I,J)),shape=(npt,npt))
STIFF = coo_matrix((VS,(I,J)),shape=(npt,npt))
return(MASS,STIFF)
def compute_global_sparse_tensors(mesh0):
I,J,VM,VS = compute_vectors_sparse_matrices(mesh0)
npt = mesh0['Pts'].shape[0]
indices = np.hstack([I[:,np.newaxis], J[:,np.newaxis]])
MASS = tf.sparse.SparseTensor(indices=indices, values=VM.astype(np.float32), dense_shape=[npt, npt])
STIFF = tf.sparse.SparseTensor(indices=indices, values=VS.astype(np.float32), dense_shape=[npt, npt])
return(MASS,STIFF)
def compute_matrices_scipy(mesh0):
MASS,STIFF = compute_global_sparse_matrices(mesh0)
return(MASS,STIFF)
def compute_matrices_tensorflow(mesh0):
MASS,STIFF = compute_global_sparse_tensors(mesh0)
return(MASS,STIFF)
def conjgrad_scipy(A,b,x0,niter=100,toll=1.e-5):
x = np.copy(x0)
r = b - A * x
p = np.copy(r)
rsold = np.dot(r,r)
for it in range(niter):
Ap = A * p
alpha = rsold /np.dot(p,Ap)
x += alpha * p
r -= alpha * Ap
rsnew = np.dot(r,r)
if (np.sqrt(rsnew) < toll):
break
p = r + (rsnew / rsold) * p
rsold = rsnew
return([x,it,np.sqrt(rsnew)])
def conjgrad_tensorflow(A,b,x0,niter=100,toll=1.e-5):
x = x0
r = b - tf.sparse.sparse_dense_matmul(A,x)
p = r
rsold = tf.reduce_sum(tf.multiply(r, r))
for it in range(niter):
Ap = tf.sparse.sparse_dense_matmul(A,p)
alpha = rsold /tf.reduce_sum(tf.multiply(p, Ap))
x += alpha * p
r -= alpha * Ap
rsnew = tf.reduce_sum(tf.multiply(r, r))
if (tf.sqrt(rsnew) < toll):
break
p = r + (rsnew / rsold) * p
rsold = rsnew
return([x,it,tf.sqrt(rsnew)])
mesh = create_mesh(Lx=10,Ly=10,Nx=100,Ny=100)
x0 = tf.constant( (mesh['Pts'][:,0]<5 ).astype(np.float32) )
nit_time = 10
dcoef = 1.0
maxit = x0.shape[0]//2
stoll = 1.e-6
print('nb of nodes:\t{}'.format(mesh['Pts'].shape[0]))
print('nb of trias:\t{}'.format(mesh['Tria'].shape[0]))
t0 = time()
MASS0,STIFF0 = compute_matrices_scipy(mesh)
elapsed_scipy=time()-t0
print('Matrices; elapsed: {:3.5f} s'.format(elapsed_scipy))
A = MASS0+dcoef*STIFF0
x = np.copy(np.squeeze(x0.numpy()) )
t0 = time()
for jt in range(nit_time):
b = MASS0*x
x1,it,tol=conjgrad_scipy(A,b,x,niter=maxit,toll=stoll)
x=np.copy(x1)
print('time {}; iters {}; resid: {:3.2f}'.format(1+jt,it,tol) )
elapsed_scipy=time()-t0
print('elapsed, scipy: {:3.5f} s'.format(elapsed_scipy))
t0 = time()
MASS,STIFF =compute_matrices_tensorflow(mesh)
elapsed=time()-t0
print('Matrices; elapsed: {:3.5f} s'.format(elapsed))
x = None
x1 = None
A = tf.sparse.add(MASS,tf.sparse.map_values(tf.multiply, STIFF, dcoef))
x = tf.expand_dims(tf.identity(x0),axis=1)
t0 = time()
for jt in range(nit_time):
b = tf.sparse.sparse_dense_matmul(MASS,x)
x1,it,tol=conjgrad_tensorflow(A,b,x,niter=maxit,toll=stoll)
x = x1
print('time {}; iters {}; resid: {:3.2f}'.format(1+jt,it,tol) )
elapsed_tf=time()-t0
print('elapsed, tf: {:3.2f} s'.format(elapsed_tf))
print('elapsed times:')
print('scipy: {:3.2f} s\ttf: {:3.2f} s'.format(elapsed_scipy,elapsed_tf))

Solve waterhammer PDE in numpy/scipy

I’ve been trying to solve the water hammer PDE’s from the Maple example linked below in python (numpy/scipy). I’m getting very unstable results. Can anyone see my mistake? Guessing something is wrong with the boundary conditions.
https://www.maplesoft.com/support/help/view.aspx?path=applications/WaterHammer
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
## Parameters
Dia = 0.1
V = 14.19058741 # Stead state
p = 1000 # Liquid density
u = 0.001 # Viscosity
L = 25
e = 0.0001 # Roughness
Psource = 0.510E6
thick = 0.001
E= 7010*10**9
K=20010E6
Vsteady= 14.19058741
Ks = 1/((1/K)+(Dia/E*thick))
# Darcy-Weisbach
def Friction(V):
Rey = ((Dia*V*p)/u)
fL = 64/Rey
fT = 1/((1.8*np.log10((6.9/Rey) + (e/(3.7*Dia))**1.11))**2)
if Rey >= 0 and Rey < 2000:
return fL
if Rey >= 2000 and Rey<4000:
return fL + ((fT-fL)*(Rey-2000))/(4000-2000)
if Rey >= 4000:
return fT
return 0
def model(D, t):
V = D[:N]
P = D[N:]
dVdt = np.zeros(N)
for i in range(1, len(dVdt)-1):
dVdt[i] = -(1/p)*((P[i+1]-P[i-1])/2*dx)-((Friction(np.abs(V[i]))*(np.abs(V[i])**2))/(2*Dia))
dPdt = np.zeros(N)
for i in range(1, len(dPdt)-1):
dPdt[i] = -((V[i+1]-V[i-1])/(2*dx))*Ks
if t < 2:
dVdt[29] = 0
else:
dVdt[29] = -1
dPdt[29] = 0
dVdt[0] = dVdt[1]
return np.append(dVdt,dPdt)
N = 30
x = np.linspace(0, L, N)
dx = x[1] - x[0]
## Initial conditions
Vi_0 = np.ones(N)*Vsteady
Pi_0 = np.arange(N)
for i in Pi_0:
Pi_0[i] = Psource - (i*dx/L)*Psource
# initial condition
y0 = np.append(Vi_0, Pi_0)
# time points
t = np.linspace(0,3,10000)
# solve ODE
y = odeint(model,y0,t)
Vr = y[:,0:N]
Pr = y[:,N:]
plt.plot(t,Pr[:,5])

Rectifying the image

I have problem in remaping the image, I used my own millimeter sheet which contains coplanar set of points, I applied the method of direct radial alignment still the image is warped not rectified, can someone help me to find where my error is. Xw, Yw, Zw are the real world coordinates, Xf, Yf are the corresponding pixel coordinates. Cx, Cy are the coordinates of the center of distortion.
import cv2
import numpy as np
from scipy.optimize import minimize
Xd = dx*(Xf-Cx)/Sx
Yd = dy*(Yf-Cy)
n1=6
A=np.zeros((N, n1))
for i in range(N):
for j in range(n1):
A[:, 0] = Yd*Xw
A[:, 1] = Yd*Yw
A[:, 2] = Yd
A[:, 3] = -Xd*Xw
A[:, 4] = -Xd*Yw
A[:, 5] = -Xd
X = solution(A)
Sr = r1_prime**2 + r2_prime**2 + r4_prime**2 + r5_prime**2
Ty = np.sqrt(Sr-np.sqrt(Sr**2-4*(r1_prime*r5_prime-r2_prime*r4_prime)**2))/(2*(r1_prime*r5_prime-r2_prime*r4_prime)**2)
#compute the rotation matrix components:
r1 = (X[0]/X[5])*Ty
r2 = (X[1]/X[5])*Ty
r4 = (X[3]/X[5])*Ty
r5 = (X[5]/X[5])*Ty
Tx = (X[2]/X[5])*Ty
s = -np.sign(r1*r4+r2*r5)
r3 = np.sqrt(1-r1**2-r2**2)
r6 = s*np.sqrt(1-r4**2-r5**2)
r7 = np.sqrt(1-(r1**2+r4**2))
r8 = np.sqrt(1-(r2**2+r5**2))
r9 = np.sqrt(-1+Sr*Ty**2)
n11 = 2
A1=np.zeros((N, n11))
for i in range(N):
for j in range(n11):
A1[:, 0] = r4*Xw + r5*Yw +Ty
A1[:, 1] = -Yd
b1 = (r7*Xw + r8*Yw)*Yd
U1, S1, VT1 = np.linalg.svd(A1)
Sigma = np.zeros((A1.shape[0], A1.shape[1]))
Sigma[:A1.shape[1], :A1.shape[1]] = np.diag(S1)
J1 = np.zeros((A1.shape[0], A1.shape[1]))
J1[:A1.shape[1], :A1.shape[1]] = np.linalg.inv(np.diag(S1))
H1 = np.zeros((A1.shape[0], A1.shape[1]))
H1[:A1.shape[0], :A1.shape[0]] = np.linalg.multi_dot([U1, J1, VT1])
H1 = H1.T
x1 = np.dot(H1, b1)
f = x1[0]
Tz = x1[1]
R = np.array([[r1, r2, r3], [r4, r5, r6], [r7, r8, r9]])
def func(guess):
k1 = guess[0]
k2 = guess[1]
f = guess[2]
tz = guess[3]
sx = guess[4]
r = np.sqrt((dx*(Xf-Cx)/sx)**2 + (Yd)**2)
return np.sum((Yd*(1+k1*r**2 + k2*r**4)*(r7*Xw + r8*Yw + r9*Zw + tz)-f*(r4*Xw + r5*Yw + r6*Zw + Ty))**2)
x0 = np.array([0, 0, f, Tz, 1])
i = minimize(func, x0, method='COBYLA', options={'disp': True})
K1 = i.x[0]
K2 = i.x[1]
F = i.x[2]
Pz = i.x[3]
Sx = i.x[4]
dx_new = dx*Sx
nx, ny = img.shape[1], img.shape[0]
X, Y = np.meshgrid(np.arange(0, nx, 1), np.arange(0, ny, 1))
x = X.astype(np.float32)
y = Y.astype(np.float32)
rd = np.sqrt((y-Cy)**2 + (x-Cx)**2)
map_x = y*(1+K11*np.power(rd, 2)+K22*np.power(rd, 4))
map_y = x*(1+K11*np.power(rd, 2)+K22*np.power(rd, 4))
imgg = cv2.remap(img, map_x, map_y, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT_101)
enter image description here

Evaluating Temperature using Antoine Eq with Classes

I need help with getting the temp using Antoine Eq by making use of classes.
My root action is failing and I don't know why.
My code:
from __future__ import division, print_function
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root
class Chemical(object):
def __init__(self, name_1, balance_1, name_2, balance_2):
self.name = name_1 + ' ' + '+' + ' ' + name_2
self.data_1 = []
self.data_2 = []
self.data_1 = balance_1
self.data_2 = balance_2
def __str__(self):
if (self.name):
return "Mixture: %s" % (self.name)
else:
return None
def bubble_solve(self,a,P = 1.01,T = 300):
A1,B1,C1 = self.data_1
A2,B2,C2 = self.data_2
PA = 10**(A1 - B1/(C1+T))
PB = 10**(A2 - B2/(C2+T))
sol = root(lambda T: P - (a*PA + (1-a)*PB),T)
return sol.x[0]
def dew_solve(self, b, P = 1.01, T = 300):
A1,B1,C1 = self.data_1
A2,B2,C2 = self.data_2
PA = 10**(A1 - B1/(C1+T))
PB = 10**(A2 - B2/(C2+T))
sol = root(lambda T: 1 - (b*P/PA + (1-b)*P/PB), T)
return sol.x[0]
mixture = Chemical('benzene', [ 3.98523 , 1184.24 , -55.578], 'toulene',
[4.05043 , 1327.62 , -55.528])
print(mixture)
print()
print(mixture.bubble_solve(0.5)) #at a = 0.5
print(mixture.bubble_solve(0.5,2)) #at a = 0.5 and P = 2
print(mixture.dew_solve(0.5)) #at b = 0.5
print(mixture.dew_solve(0.5,2)) #at b = 0.5 and P = 2
This is what my code is printing:
Mixture: benzene + toulene
300.0
300.0
300.0
300.0
However, the answers need to be:
365.087, 390.14188, 371.7743, 396.688.
Why does the root action fail?
Welcome to StackOverflow, #Nathaniel!
The issue is in your PA, PB, and sol lines in bubble_solve and dew_solve. You seem to be mixing constants with independent variables! For instance, with your bubble solve, you have the default value of 300 set for T. Thus in the PA line, the value 300 is being used for T! One way to fix this would be the following:
...
def bubble_solve(self,a,P = 1.01,T = 300):
A1,B1,C1 = self.data_1
A2,B2,C2 = self.data_2
PA = lambda x: 10**(A1 - B1/(C1+x))
PB = lambda x: 10**(A2 - B2/(C2+x))
sol = root(lambda x: P - (a*PA(x) + (1-a)*PB(x)),T)
return sol.x[0]
def dew_solve(self, b, P = 1.01, T = 300):
A1,B1,C1 = self.data_1
A2,B2,C2 = self.data_2
PA = lambda x: 10**(A1 - B1/(C1+x))
PB = lambda x: 10**(A2 - B2/(C2+x))
sol = root(lambda x: 1 - (b*P/PA(x) + (1-b)*P/PB(x)), T)
return sol.x[0]
...
This will return the values you have expected. Note that I use x as the independent variable for PA and PB, but that it's arbitrary. However, it's probably best to not reuse T for your anonymous functions if you are passing values to it.

Having successfully converted complex Matlab code to Python, how to run the code?

This question is a follow-up to my previous question here: Assistance, tips and guidelines for converting Matlab code to Python
I have converted the Matlab code manually. I am using a MAC OS and running Python from the terminal. But how do I run the code below, for some value of N, where N is an even number? I should get a graph (specified by the plot code).
When I run it as is, I get nothing.
My code is below:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def Array(N):
K00 = np.logspace(0,3,101,10)
len1 = len(K00)
y0 = [0]*(3*N/2+3)
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)]
Kplot = np.zeros((len1,1))
Pplot = np.zeros((len1,1))
for series in range(0,len1):
K0 = K00[series]
Q = 10
r1 = 0.0001
r2 = 0.001
d = 0.001
a = 0.001
k = 0.999
P0 = 1
S10 = 1e5
tf = 1e10
time = np.linspace(0,tf,len1)
y0[0] = S10
y0[3*N/2+1] = K0
y0[3*N/2+2] = P0
for i in range(1,3*N/2+1):
y0[i] = 0
[t,y] = odeint(EqnsArray,y0,time, mxstep = 5000)
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]
for alpha in range(0,(N/2+1)):
Splot[alpha][series] = y[len1-1,alpha]
for beta in range((N/2)+1,N+1):
KSplot[beta-N/2-1][series] = y[len1-1,beta]
for gamma in range(N+1,3*N/2+1):
PSplot[gamma-N-1][series] = y[len1-1,gamma]
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
plt.plot(np.log10(K00),utot)
plt.show()
def EqnsArray(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
You have to call your function, like:
Array(12)
You have to add this at the end of your code.

Categories

Resources