Can't find the cause of a SyntaxError in matplotlib - python

I'm currently trying to plot an integral equation in Python. It suposed to give the of the functions for three different values of parameter gama. There is gama depedency of the parameter beta and in the wave function itself. Here is the code:
from scipy.integrate import quad
import numpy as np
from scipy.special import gamma
from scipy.constants import alpha
import matplotlib.pyplot as plt
#Constants
epsilon = 13.1 #dielectric constant of the material
gamma_C = 0.5 # donor impurity linewidth
nr = 3.2 #refractive index of semiconductor
flux = 0.0 # Phi in eqn 8 magnetic flux
R = 5.0 #radius of the quantum ring in nm
r = np.linspace(0, 6 * R)
rho = r / R
m_0 = 0.0067*0.511 # electron effective mass
h = 4.13e-15 # Planck constant in eV
hbar = 6.58e-16 # reduced Planck constant in eV
#Photon energy
hnu = np.linspace(0, 100) #in eV
#Function that calculates the integrand
def func(rho, theta):
betai = gama**2/2
betaf = np.sqrt(1+gama**4/2)
return (R *(gama * rho)**(betai + betaf) *
np.exp(-1/2*(gama * rho)**2) *
(gama*rho)**2/2 )
def cross_section(hnu, gama):
#function that calculates the photoionisation cross section
betai = gama**2/2
betaf = np.sqrt(1+gama**4/2)
Ei = gama**2*(1+betai)-gama**4/2
Ef = gama**2*(3+betaf)-gama**4/2
delta = hbar * gamma_C/(Ef - Ei - hnu)**2 + ( hbar * gamma_C)**2
return (nr/epsilon * 4*np.pi/3 * alpha * hnu *
(abs( np.sqrt(1/2**betai*gamma(betai + 1))*
np.sqrt(1/2**betaf*gamma(betaf + 2)) *
quad(func, 0, np.infty) [0] * delta))
#Plot
plt.figure();plt.clf()
for gama in [1.0, 1.5, 2.0]:
plt.plot(hnu, (cross_section(hnu, gama))
plt.legend(['$\gamma = 1.0$', '$\gamma = 1.5$', '$\gamma = 2.0$'] )
plt.ylabel('Photoionization cross\n section $\sigma (10^{-14}cm^{2}$)')
plt.xlabel('Photon energy $h\\nu (meV)$ ')
But I'm getting a unexpected syntax error on a line of the code:
runfile('/home/daniel/Arquivos_Python/crosssection.py', wdir='/home/daniel/Arquivos_Python')
File "/home/daniel/Arquivos_Python/crosssection.py", line 49
plt.figure();plt.clf()
^
SyntaxError: invalid syntax

Its because your bracket at return of the Cross_section
I've run it and got another error XD
func() missing 1 required positional argument: 'theta'
, at least the Syntax error are known and resolve
here is your edited code:
from scipy.integrate import quad
import numpy as np
from scipy.special import gamma
from scipy.constants import alpha
import matplotlib.pyplot as plt
#Constants
epsilon = 13.1 #dielectric constant of the material
gamma_C = 0.5 # donor impurity linewidth
nr = 3.2 #refractive index of semiconductor
flux = 0.0 # Phi in eqn 8 magnetic flux
R = 5.0 #radius of the quantum ring in nm
r = np.linspace(0, 6 * R)
rho = r / R
m_0 = 0.0067*0.511 # electron effective mass
h = 4.13e-15 # Planck constant in eV
hbar = 6.58e-16 # reduced Planck constant in eV
#Photon energy
hnu = np.linspace(0, 100) #in eV
#Function that calculates the integrand
def func(rho, theta):
betai = gama**2/2
betaf = np.sqrt(1+gama**4/2)
return (R *(gama * rho)**(betai + betaf) *
np.exp(-1/2*(gama * rho)**2) *
(gama*rho)**2/2 )
def cross_section(hnu, gama):
#function that calculates the photoionisation cross section
betai = gama**2/2
betaf = np.sqrt(1+gama**4/2)
Ei = gama**2*(1+betai)-gama**4/2
Ef = gama**2*(3+betaf)-gama**4/2
delta = hbar * gamma_C/(Ef - Ei - hnu)**2 + ( hbar * gamma_C)**2
return (nr/epsilon * 4*np.pi/3 * alpha * hnu *
(abs( np.sqrt(1/2**betai*gamma(betai + 1))*
np.sqrt(1/2**betaf*gamma(betaf + 2)) *
quad(func, 0, np.infty) [0] * delta)))
#Plot
plt.figure()
plt.clf()
for gama in [1.0, 1.5, 2.0]:
plt.plot(hnu, (cross_section(hnu, gama)))
plt.legend(['$\gamma = 1.0$', '$\gamma = 1.5$', '$\gamma = 2.0$'] )
plt.ylabel('Photoionization cross\n section $\sigma (10^{-14}cm^{2}$)')
plt.xlabel('Photon energy $h\\nu (meV)$ ')

Related

How could I make a line which is inverted to the original

At the moment this is my code:
import scipy
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import EventCollection
import math
from scipy import integrate
from scipy import constants
K_b = 1.380649e-23 # Boltzmanns Constant
a_n = 6.022e23 # Avogrados Number
T = 10 # Kelvin
mass = 28
a = 10e-5
def mantleEvolution(tMax, dt) :
N = int(tMax/dt) + 1
timeArray = np.zeros(N)
numberArray = np.zeros(N)
t = 0
n_m = 1 #per cubic centimeter
n_s = 0
i = 0
while i < N:
m_m = float(mass) / a_n
V_m = math.sqrt((8.0 * K_b * float(T)) / (math.pi * float(m_m)))
R = math.pi * pow(float(a), 2) * n_m * V_m
ρ_d = 3 # g/cm^3
μ_g = 2 * 1.67e-23
m_d = (4 / 3) * math.pi * pow(float(a), 3)
n_g = 10e4
d_g = 0.01 # 1% mass density of gas
n_d = (d_g * n_g * μ_g) / (m_d * float(ρ_d))
n_s = n_s + R * dt
n_m = n_m - R * n_d * dt
timeArray[i] = t
numberArray[i] = n_m
t = t + dt
i = i + 1
return [timeArray, numberArray, n_s]
timeArray, numberArray, n_s = mantleEvolution(5.0 * 10**15, 5.0 * 10**9)
fig = plt.figure(figsize=(6.4, 6.4))
ax1 = plt.subplot(111)
ax1.plot(timeArray, numberArray)
ax1.set_xlabel('time, seconds', fontsize=20)
ax1.set_ylabel('number', fontsize=20)
plt.setp(ax1.get_xticklabels(), fontsize=16)
plt.setp(ax1.get_yticklabels(), fontsize=16)
fig.subplots_adjust(left=.18)
plt.savefig('mantleEvolution.pdf')
This is the graph I recieve from graphing my code:
What I wish to find out is how I could plot a second line which behaves the exact opposite where it grows at the same rate the other declines
So for example, something that ressembles this:
If you look at the graph you'll see that the value on the y axis is for both graphs the same for two opposite x values at the x axis. That means that all you want to do is invert the x axis. That is fairly easy done using the formula:
new_x = -1 * (old_x - 2.5) + 2.5
By the way, I see some interesting comments in your code. What is it that you are trying to do here if I may ask?

How can I solve a contourf array problem?

I have trouble with plt.contourf.
The program is supposed to calculate the distance between s1 and m called s1m and S2 and m called s2m than using s1m and s2m we calculate the wave functions psi and psiP than we multiply them to get the intensity of light, we use what we get in contourf to see the results in a screen.
When I run the program I
import numpy as np
import matplotlib.pyplot as plt
S1 = np.array([100,0,-1])
S2 = np.array([-100,0,-1])
M = np.array([1,1,0])
Lambda = 633
s1m= np.substract(m,S1)#vector S1M
s2m= np.substract(m,S2)#vector S2M
SM1= np.multiply(s1m,s1m)
SM2= np.multiply(s2m,s2m)
S1M= np.sqrt(SM1)#distance s1m
S2M= np.sqrt(SM2)#distance s2m
def intensity (S1M,S2M):
Phi1=(2 * np pi * S1M)/lambda
Phi2=(2 * np.pi * S2M)/lambda
Tet1=(-2 * np.pi * S1M)/lambda
Tet2=(-2 * np.pi * S2M)/lambda
Psi1 = np.exp(Phi1)
Psi2 = np.exp(Phi2)
Psi1P = np.exp(Tet1)
Psi2P = np.exp(Tet2)
Psi = Psi1 + Psi2
PsiP = Psi1P + Psi2P
I = Psi * PsiP
x = np.linspace(1,5,5)
y = np.linspace(1,5,5)
XX,YY = np.meshgrid(x,y)
ZZ = intensity (S1M, S2M)
plt.contourf (XX, YY, ZZ)
plt.show()

Integrale value decreases when I increase range of integration using mpmath (positive function)

I am using mpmath library on python to compute this integral :
The issue is that when I increase the range of integration, my integral value slowly decreases to 0.. while the integrand is positive!! I give you some values :
integration range : [-1.17,-1.11], integral value : 1.28479400889196e-8
integration range : [-1.2,0], integral value : 2.87226592130464e-29
integration range : [-10,10], integral value : 0.0
What's going on and how to solve issue besides selecting only the range where my integrand is not 0 ?
Here is my code (fermi dirac stat and conductivity have been adapted for pmos so it's not exactly the integral i've shown)
import numpy as np
from math import pi, sqrt, exp, log
from scipy.integrate import quad
import scipy.constants as phys
import matplotlib.pyplot as plt
from decimal import Decimal, getcontext
getcontext().prec = 1000
import mpmath as mp
k = (phys.Boltzmann) # Boltzmann constant
#Parenthesis left due to previous decimal conversion
m = (9.1094e-31) #electron mass
h = (phys.Planck) #Planck constant
h_b = h/(2 * pi) #reduced
q = (1.602176634e-19)
e = (1)
dE = 3e-3 * e
pi = (pi)
m_e = m * (1.06) #electron effective mass
m_h = m * 0.59 #hole effective mass
A_2D = m_h / (pi*h_b**2)
###### INPUTS
T = (4.2)
V_d = (0.02)
chi = (4.05)*e
E_g = (1.16)*e
g = 4 #degeneracy
μ = (1e3) #mobility, cm**2/Vs
A = A_2D
W = 1.00E-05
L = 1.00E-07
#########
E_c = 0
E_v = E_c - E_g
Phi_f = (0.55)
E_f = ( E_c - E_g/2 - e*Phi_f)
Ef_d = ( E_f - e * V_d)
#######
def fd(E,E_f): #Fermi-Dirac distribution for holes
res = 1/(1 + mp.exp(((E - E_f)*q/(k*T))))
return 1-res
def sigma(E):
if E_v-E < 2 :
res = q * A * μ *1e-4 * dE*q * log( 1 + mp.exp((E_v-E)/ dE))
else:
res = - q * A * μ *1e-4 *q *(E-E_v)
return res
def integrand(E):
return sigma(E)*( fd(E,Ef_d) -fd(E,E_f))
X = np.linspace(E_v-5.05,5,1000)
FD = np.vectorize(fd)
Sigma = np.vectorize(sigma)
Integrand = np.vectorize(integrand)
#mp.quad
Int = mp.quad(integrand, [-10,10])
I_c = W/(q*L)*Int
fig, ax1 = plt.subplots()
ax1.plot(X,FD(X,Ef_d) - FD(X,E_f), color = 'g', label='fd stat');
ax2 = ax1.twinx()
ax2.semilogy() ;
ax2.plot(X,Sigma(X), label='sigma');
ax2.plot(X,Integrand(X), label='integrand');
ax1.legend()
ax2.legend(loc='lower right')
print('Int = ',Int)
Thanks

Error: TypeError: can't multiply sequence by non-int of type 'numpy.float64' <Figure size 432x288 with 0 Axes> (don't know what to do)

I'm trying to plot an equation that contains and definite integral. It is a photoionisation cross section associated with the intersubband transitions in a two-dimensional quantum ring. I made the angular part analytically, and I'm trying to calculate numerically the radial part.
Here's my attempt to implement this in a Python code:
from scipy.integrate import quad
import numpy as np
from scipy.special import gamma
from scipy.constants import alpha
import matplotlib.pyplot as plt
#Constants
epsilon = 13.1 #dielectric constant of the material
gamma_C = 0.5 # donor impurity linewidth
nr = 3.2 #refractive index of semiconductor
flux = 0 # Phi in eqn 8 magnetic flux
R = 5 #radius of the qunatum ring in nm
r = np.linspace(0, 6 * R)
rho = r / R
m_0 = 0.0067*0.511 # electron effective mass
h = 4.13e-15 # Planck constant in eV
hbar = 6.58e-16 # reduced Planck constant in eV
#Photon energy
hnu = np.linspace(0, 100) #in eV
#Function that calculates the integrand
def func(rho):
betai = np.sqrt( gama**4/4)
betaf = np.sqrt(1+gama**4/2)
return ((gama * rho)**(betai + betaf) *
np.exp(-1/2*(gama * rho)**2)
* (gama * rho)**2/2 )
def cross_section(hnu, gama):
#function that calculates the photoionisation cross section
betai = np.sqrt( gama**4/4)
betaf = np.sqrt(1+gama**4/2)
Ei = gama**2*(1+betai)-gama**4/2
Ef = gama**2*(3+betaf)-gama**4/2
return (nr/epsilon * 4*np.pi/3 * alpha * hnu *
(abs(R * np.sqrt(1/2**betai*gamma(betai + 1))*
np.sqrt(1/2**betaf*gamma(betaf + 1)) *
quad(func, 0, np.infty))**2 *
hbar * gamma_C/(Ef - Ei - hnu)**2 + ( hbar * gamma_C)**2))
#Plot
plt.figure();plt.clf()
for gama in [1.0, 1.5, 2.0]:
plt.plot(hnu, cross_section(hnu, gama))
But I keep receiving this error
TypeError: can't multiply sequence by non-int of type 'numpy.float64'
Anyone knows the cause and how can avoid this?
Take another look at the docstring for scipy.integrate.quad. In particular, look at the 'Returns' section. You'll see that it returns multiple values. More precisely, it returns a tuple of values. The actual number of values depends on the parameter full_output, but it always includes at least two values, the numerically computed integral and the error estimate.
In this code
return (nr/epsilon * 4*np.pi/3 * alpha * hnu *
(abs(R * np.sqrt(1/2**betai*gamma(betai + 1))*
np.sqrt(1/2**betaf*gamma(betaf + 1)) *
quad(func, 0, np.infty))**2 *
hbar * gamma_C/(Ef - Ei - hnu)**2 + ( hbar * gamma_C)**2))
you use the return value of quad, but that is a tuple, so it won't work correctly in that expression. To fix it, just pull out the first value of the tuple returned by quad. That is, replace quad(func, 0, np.infty) with quad(func, 0, np.infty)[0]:
return (nr/epsilon * 4*np.pi/3 * alpha * hnu *
(abs(R * np.sqrt(1/2**betai*gamma(betai + 1))*
np.sqrt(1/2**betaf*gamma(betaf + 1)) *
quad(func, 0, np.infty)[0])**2 *
hbar * gamma_C/(Ef - Ei - hnu)**2 + ( hbar * gamma_C)**2))

Implementation of the Fourier transform of the option price as a function of the characteristic function Carr Madan method

Psi in the Carr Madan method of option pricing is the Fourier transform of the option price as a function of the characteristic function.
The function psi should return a scalar as opposed to a vector which is causing me the problem. So I am looking for suggestions of alternative implementation.
import numpy as np
from scipy.special import gamma
param = [24.79, 94.45, 95.79, 0.2495, 0]
alpha = 1.1
lnS = 4.142976
r = 0.05
Sigma = 0.25
scale = 1
FFT_N = int(np.power(2,15))
uvec = np.linspace(1,FFT_N,FFT_N)
vj = (uvec-1) * 0.5
Tmt = 1/12
def psi(CF, vj, alpha, lnS, T=Tmt):
u=vj-(alpha*1j+1j)
denom = alpha**2 + alpha - Sigma**2 + vj * 2 * alpha * 1j + 1j * vj
return CF(u,lnS, Tmt)/denom
CF=lambda u, lnS, T: cf_log_cgmy(u=u, lnS=lnS, T=Tmt, mu=r, half_etasq=param[4],C=param[0], G=param[1], M=param[2], Y=param[3])
def cf_log_cgmy(u, lnS, T, mu ,half_etasq, C, G, M, Y):
omega = -C*gamma(-Y)*(np.power(M-1,Y)-np.power(M,Y)+np.power(G+1,Y)-np.power(G,Y ))
phi_CGMY = C*T*gamma(-Y)*(np.power(M-1j*u,Y)-np.power(M,Y)+np.power(G+1j*u,Y)- np.power(G,Y))
phi = 1j*u*(lnS + (mu+omega-half_etasq)*T) + phi_CGMY - half_etasq*np.power(u,2)
return np.exp(scale*phi)
psi(CF, vj, alpha, lnS, T=Tmt)
The psi function stands for equation (6) on page 64 of the attached below paper
https://engineering.nyu.edu/sites/default/files/2018-08/CarrMadan2_0.pdf

Categories

Resources