I have a question on extracting variables in def
For example,
def func(z,W):
A = z[1]
B = z[2]
C = z[3]
Var = k*B/C
dAdW = A*3
dBdW = B*2/Var
dCdW = C**2*Var**2
return dAdW, dBdW, dCdw
init = [0,0,1]
W = np.linspace(0,100,1000)
sol = odeint(func, init, W)
plt.plot(W,sol[:,0])
plt.plot(W,Var) # ----> this one
Since Var is not a differential equation,
I can't declare Var as Var = z[4]
I tried using global but it only yields the last value.
How do I get all the values of Var in an array so I can plot the Var?
k is a constant like 1
Thank you for taking a look into this!
Here is a full code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
alpha = 0.0002
Uapb = 0.5
deltaH = -20000
Cpa = Cpb = 20
Cpi = 40
Ea = 25000
Kc1 = 100 # @ T=303
k1 = 0.004 #@ T=310K
CPcool = 20
Fao = 5
Cao = 1
mc = 1000
R = 1.987
To = 330
def func(z,W):
pbar = z[0]
X = z[1]
Ta = z[2]
T = z[3]
k = k1*np.exp(Ea/R*(1/310-1/T))
Kc = Kc1 * np.exp(deltaH / R * (1 / 303 - 1 / T))
Ca = Cao * (1 - X) * To / T * pbar
Cb = Cao*(1-X)*To/T*pbar
Cc = 2*Cao*To/T*pbar
Ci = To/T*pbar
ra = k*(Ca*Cb-Cc**2/Kc)
dxdw = -ra/Fao
dpbardw = -alpha/(2*pbar)*T/To
dTadw = (Uapb)*(T-Ta)/(mc*CPcool)
dTdw = (Uapb*(Ta-T)+ra*deltaH)/(Fao*(Ca+Cb+Ci))
return dxdw, dpbardw, dTadw, dTdw
init = [1, 0, 320, 320]
W = np.linspace(0,4500,1000)
sol = odeint(func, init, W)
#Xe = (2 * Kc - ((2 * Kc) ** 2 - 4 * Kc * (Kc - 4)) ** (1 / 2)) / (2 * (Kc - 4))
plt.plot(W, sol[:,0])
#plt.plot(W, Xe)
To capture the data from each call, you can do something like this:
capture_var = []
def func(z,W):
Var = ...
global capture_var
capture_var.append(Var)
Please note: that this is rather a hack, and if you doing some basic scripting to solve some small problems is likely fine. However, if you are working on a code base of any size, please don't do this sort of thing, as these sorts of practices can be a maintenance nightmare.