Why the figure plotted by my code only shows the blank? - python

Here is the attachment of the python code:
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
import math
def V(S0):
# nx = norm.cdf(x)
K = 1.5
T = 1
sigma = 0.1
rd = 0.03
ry = 0.02
e = math.e
d1 = (math.log((S0 * e ** ((rd - ry) * T)) / K) + (sigma ** 2 * T) / 2) / (sigma * math.sqrt(T))
d2 = (math.log((S0 * e ** ((rd - ry) * T)) / K) - (sigma ** 2 * T) / 2) / (sigma * math.sqrt(T))
nd1 = norm.cdf(d1)
nd2 = norm.cdf(d2)
V = e ** (-rd * T) * (S0 * e ** ((rd - ry) * T) * nd1 - K * nd2)
V2 = np.vectorize(V)
S0 = np.arange(1, 1000, 1)
plt.title('V as a function of S0')
plt.xlabel('S0')
plt.ylabel('V')
plt.plot(S0, V2(S0))
plt.show()
And the code with such a result:
How can I fix it?

There are two issues
math.log only accepts size-1 arrays
Removed the math module and switched to numpy methods
Nothing is returned by the function V
Added return V
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
def V(S0):
# nx = norm.cdf(x)
K = 1.5
T = 1
sigma = 0.1
rd = 0.03
ry = 0.02
e = np.e
d1 = (np.log((S0 * e ** ((rd - ry) * T)) / K) + (sigma ** 2 * T) / 2) / (sigma * np.sqrt(T))
d2 = (np.log((S0 * e ** ((rd - ry) * T)) / K) - (sigma ** 2 * T) / 2) / (sigma * np.sqrt(T))
nd1 = norm.cdf(d1)
nd2 = norm.cdf(d2)
V = e ** (-rd * T) * (S0 * e ** ((rd - ry) * T) * nd1 - K * nd2)
return V # return V added
V2 = np.vectorize(V)
S0 = np.arange(1, 1000, 1)
plt.title('V as a function of S0')
plt.xlabel('S0')
plt.ylabel('V')
plt.plot(S0, V2(S0))
plt.show()

Related

Numpy refuses to display vectorized function

I've got a code that runs as follows:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pyXSteam.XSteam
from pyXSteam.XSteam import XSteam
steamTable = XSteam(XSteam.UNIT_SYSTEM_MKS) # m/kg/sec/°C/bar/W
A = 3000 #define the heat exchange area
d_in = 20 #define the inner diameter of HE tubes
CF = 0.85 #define the cleanliness factor of SC.
w = 2.26 #define the water velocity within the tubes
Dk=np.arange(27.418,301.598,27.418) #define the range of steam loads
dk = (Dk * 1000 / (A * 3.600)) #calculate the relative steam load
Tcwin=20
def Cp():
return steamTable.CpL_t(Tcwin)
Gw = 13000 #define the flow of CW, t/hr
e = 2.718281828
f_velocity = w * 1.1 / (20 ** 0.25)
f_w=0.12 * CF * (1 + 0.15 * Tcwin)
Ф_в = f_velocity ** f_w
K = CF * 4070 * ((1.1 * w / (d_in ** 0.25)) ** (0.12 * CF * (1 + 0.15 * Tcwin))) * (1 - (((35 - Tcwin) ** 2) * (0.52 - 0.0072 * dk) * (CF ** 0.5)) / 1000)
n = (K * A) / (Cp() * Gw * 1000)
Tcwout_theor = Tcwin + (Dk * 2225 / (Cp() * Gw))
Subcooling_theor = (Tcwout_theor - Tcwin) / (e ** (K * A / (Cp() * (Gw * 1000 / 3600) * 1000)))
TR_theor = (Tcwout_theor - Tcwin)
Tsat_theor = (Tcwout_theor + Subcooling_theor)
def Ts():
return np.vectorize(Tsat_theor)
def Psat_theor():
return steamTable.psat_t(Tsat_theor)
print(Dk)
print(Tsat_theor)
print(Psat_theor)
While it does calculate Tsat_theor, it fails to print Psat_theor.
The output goes like this:
<function Psat_theor at 0x000002A7C29F0D30>
How can I obtain the actual value of Psat_theor?
You need to call mentioned function, change
print(Psat_theor)
to
print(Psat_theor())

Solving a double integral with scipy dblquad

I am trying to solve the double integral of this complicated function. The function contains 3 symbolic variables which are defined with sympy.symbols. My goal is to integrate the function with respect to only two of the variables. sym.integrate run for 2 hours with no results to show. I tried numerical integration with scipy.integrate.dblquad. But I am having troubles which I suspect is due to the third symbolic variable. Is there a way to do this.
Problem summarized.
sym.symbols('x y z')
My_function(x,y,z)
Integrate My_function with respect to x and y (Both from 0 to inf i.e. definite integral).
Thank you in advance
h, t, w, r, q = sym.symbols('h t w r q') # Define symbols
wn = 2.0
alpha = 1.76
beta = 1.59
a0 = 0.7
a1 = 0.282
a2 = 0.167
b0 = 0.07
b1 = 0.3449
b2 = -0.2073
psi = 0.05
F_H = 1.0 - sym.exp(-(h / alpha) ** beta)
mu_h = a0 + a1 * h ** a2
sig_h = b0 + b1 * sym.exp(b2 * h)
F_TIH = (1 / 2) * (1 + sym.erf((sym.log(t) - mu_h) / (sig_h * sym.sqrt(2))))
f_h = sym.diff(F_H, h)
f_tzIhs = sym.diff(F_TIH, t)
f_S = f_h * f_tzIhs
H = (1.0 - (w / wn) ** 2.0 + 1.0j * 2.0 * psi * w / wn) ** (-1.0)
S_eta_h_t = h ** 2.0 * t / (8.0 * pi ** 2.0) * (w * t / (2.0 * pi)) ** (-5.0) * sym.exp(-1.0 / pi * (w * t / (2.0 * pi)) ** (-4.0))
S_RIS_hu_tu = abs(H) ** 2.0 * S_eta_h_t
m0_s = sym.integrate((w ** 0 * S_RIS_hu_tu), (w, 0, np.inf))
m0_s.doit()
m2_s = sym.integrate((w ** 2 * S_RIS_hu_tu), (w, 0, np.inf))
m2_s.doit()
v_rIs = 1 / (2 * pi) * sym.sqrt(m2_s / m0_s) * sym.exp(-r ** 2 / (2 * m0_s))
fun = v_rIs * f_S
# The integral I am trying to solve is a function of h,t and r.
integ_ht = sym.integrate(fun,(h,0,np.inf),(t,0,np.inf))

trying to solve differential equations simultaneously

I am trying to build a code for chemical reactor design which is able to solve for the pressure drop, conversion, and temperature of a reactor. All these parameters have differential equations, so i tried to define them inside a function to be able to integrate them using ODEINT. However it seems that the function i've built has an error which i can't figure out which held me back from integration it.
the error that i'm encountering:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-63c706e84be5> in <module>
1 X0=[0.05,1200,2]
----> 2 y=func(X0,0)
<ipython-input-27-6cfd4fef5ee2> in func(x, W)
8 kp=np.exp(((42311)/(R*T))-11.24)
9 deltah=-42471-1.563*(T-1260)+0.00136*(T**2 -1260**2)- 2,459*10e-7*(T**3-1260**3)
---> 10 ra=k*np.sqrt((1-X)/X)*((0.2-0.11*X)/(1-0.055*X)*(P/P0)-(x/(kp*(1-x)))**2)
11 summ = 57.23+0.014*T-1.94*10e-6*T**2
12 dcp=-1.5625+2.72*10e-3*T-7.38*10e-7*T**2
TypeError: unsupported operand type(s) for -: 'int' and 'list'
and here is the full code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
fi = 0.45
gas_density = 0.054 #density
Pres0 = 2 #pressure
visc = 0.09
U = 10
Ac = 0.0422
T0 = 1400 #and 1200 also
gc = 4.17 * 10**8
bed_density = 33.8
Ta = 1264.6 #wall temp
fa0 = 0.188
def func(x,W):
X = x[0]
T = x[1]
P = x[2]
P0 = 2
R = 0.7302413
k = np.exp((-176008 / T) - (110.1 * np.log(T) + 912.8))
kp = np.exp(((42311) / (R * T)) - 11.24)
deltah = -42471 - 1.563 * (T - 1260) + 0.00136 * (T**2 - 1260**2) - 2,459 * 10e-7 * (T**3 - 1260**3)
ra = k * np.sqrt((1 - X) / X) * ((0.2 - 0.11 * X) / (1 - 0.055 * X) * (P / P0) - (x / (kp * (1 - x)))**2)
summ = 57.23 + 0.014 * T - 1.94 * 10e-6 * T**2
dcp = -1.5625 + 2.72 * 10e-3 * T - 7.38 * 10e-7 * T**2
dxdw = 5.31 * k * np.sqrt((1 - X) / X) * ((0.2 - 0.11 * X) / (1 - 0.055 * X) * (P / P0) - (x / (kp * (1 - x)))**2)
dpdw = (((-1.12 * 10**-8) * (1 - 0.55 * X) * T) / P) * (5500 * visc + 2288)
dtdw = (5.11 * (Ta - T) + (-ra) * deltah) / (fa0 * (summ + x * dcp))
return [dxdw, dpdw, dtdw]
X0 = [0.05, 1200, 2]
y = func(X0, 0)
thanks in advance
Inside line
ra=k*np.sqrt((1-X)/X)*((0.2-0.11*X)/(1-0.055*X)*(P/P0)-(x/(kp*(1-x)))**2)
you probably want to use ...X/(kp*(1-X))... instead of ...x/(kp*(1-x))... (i.e. use upper X), lower x is list type.
If you want to use some list variable l as multiple values somewhere then convert it to numpy array la = np.array(l) and use la in numpy vectorized expression.

Using functions to create Electric Field array for 2d Density Plot and 3d Surface Plot

Below is my code, I'm supposed to use the electric field equation and the given variables to create a density plot and surface plot of the equation. I'm getting "invalid dimensions for image data" probably because the function E takes multiple variables and is trying to display them all as multiple dimensions. I know the issue is that I have to turn E into an array so that the density plot can be displayed, but I cannot figure out how to do so. Please help.
import numpy as np
from numpy import array,empty,linspace,exp,cos,sqrt,pi
import matplotlib.pyplot as plt
lam = 500 #Nanometers
x = linspace(-10*lam,10*lam,10)
z = linspace(-20*lam,20*lam,10)
w0 = lam
E0 = 5
def E(E0,w0,x,z,lam):
E = np.zeros((len(x),len(z)))
for i in z:
for j in x:
E = ((E0 * w0) / w(z,w0,zR(w0,lam)))
E = E * exp((-r(x)**2) / (w(z,w0,zR(w0,lam)))**2)
E = E * cos((2 * pi / lam) * (z + (r(x)**2 / (2 * Rz(z,zR,lam)))))
return E
def r(x):
r = sqrt(x**2)
return r
def w(z,w0,lam):
w = w0 * sqrt(1 + (z / zR(w0,lam))**2)
return w
def Rz(z,w0,lam):
Rz = z * (1 + (zR(w0,lam) / z)**2)
return Rz
def zR(w0,lam):
zR = pi * lam
return zR
p = E(E0,w0,x,z,lam)
plt.imshow(p)
It took me way too much time and thinking but I finally figured it out after searching for similar examples of codes for similar problems. The correct code looks like:
import numpy as np
from numpy import array,empty,linspace,exp,cos,sqrt,pi
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
lam = 500*10**-9 #Nanometers
x1 = linspace(-10*lam,10*lam,100)
z1 = linspace(-20*lam,20*lam,100)
[x,y] = np.meshgrid(x1,z1)
w0 = lam
E0 = 5
r = sqrt(x**2)
zR = pi * lam
w = w0 * sqrt(1 + (y / zR)**2)
Rz = y * (1 + (zR / y)**2)
E = (E0 * w0) / w
E = E * exp((-r**2 / w**2))
E = E * cos((2 * pi / lam) * (y + (r**2 / (2 * Rz))))
def field(x,y):
lam = 500*10**-9
k = (5 * lam) / lam * sqrt(1 + (y / (pi*lam))**2)
k *= exp(((-sqrt(x**2)**2 / (lam * sqrt(1 + (y / pi * lam)**2))**2)))
k *= cos((2 / lam) * (y + ((sqrt(x**2)**2 / (2 * y * (1 + (pi * lam / y)**2))))))
return k
#Density Plot
f = field(x,y)
plt.imshow(f)
plt.show()
#Surface Plot
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x,y,E,rstride=1,cstride=1)
plt.show

How do i use python to plot fouries series graph?

I have no idea about how to plot fourier series graph from equation like this
I try to use matplotlib to plot this but there are so many values. Here are code that I used. Not sure about algorithm.
import numpy as np
import matplotlib.pyplot as plt
x_ = np.linspace(0, 30, 10000)
a0 = 3/5
##an = 1/n * np.pi * (np.sin(0.4 * n * np.pi) + np.sin(0.8 * n * np.pi))
##bn = 1/n * np.pi * (2 - np.cos(0.4 * n * np.pi) - np.cos(0.8 * n * np.pi))
f0 = 5
def a(n):
return 1/n * np.pi * (np.sin(0.4 * n * np.pi) + np.sin(0.8 * n * np.pi))
def b(n):
return 1/n * np.pi * (2 - np.cos(0.4 * n * np.pi) - np.cos(0.8 * n * np.pi))
def s(t, n):
temp = 0
for i in range (1, n + 1):
temp = temp + (a(i) * np.cos(2 * np.pi * i * f0 * t) \
+ b(i) * np.sin(2 * np.pi * n * f0 * t))
temp += a0
return temp
st = []
for i in range (1, 6):
st.append(s(1, 6))
plt.title("Test")
plt.plot(x_, st, color="red")
plt.show()
Tried this then got this error
ValueError: x and y must have same first dimension, but have shapes (10000,) and (5,)
thanks for any help

Categories