I use python to calculate the multivariate_gauss distribution, but I don't know what's wrong.
The code is here
# calculate multi-d gaussian pdf
def mul_gauss(x, mu, sigma) -> float:
d = len(x[0])
front = 1 / math.sqrt(((2 * math.pi) ** d) * np.linalg.det(sigma))
tmp = (np.array(x) - np.array(mu))
tmp_T = np.transpose(tmp)
back = -0.5 * (np.matmul(np.matmul(tmp, np.linalg.inv(sigma)), tmp_T))[0][0]
return front * math.exp(back)
I compared the result with scipy.stats.multivariate_normal(x,mu,sigma)
x = [[2,2]]
mu = [[4,4]]
sigma = [[3,0],[0,3]]
ret_1 = mul_gauss(x, mu, sigma)
ret_2 = scipy.stats.multivariate_normal(x[0], mu[0], sigma).pdf(x[0])
print('ret_1=',ret1)
print('ret_2=',ret2)
and output is
ret_1=0.013984262505331654
ret_2=0.03978873577297383
Could anyone help me?
In line 5 of your main you call the .pdf() on the object instead as a method.
Here is a fix:
# calculate multi-d gaussian pdf
import math
import numpy as np
from scipy import stats
def mul_gauss(x, mu, sigma) -> float:
d = x[0].shape[0]
coeff = 1/np.sqrt((2 * math.pi) ** d * np.linalg.det(sigma))
tmp = x - mu
exponent = -0.5 * (np.matmul(np.matmul(tmp, np.linalg.inv(sigma)), tmp.T))[0][0]
return coeff * math.exp(exponent)
x = np.array([[2,2]])
mu = np.array([[4,4]])
sigma = np.array([[3,0],[0,3]])
ret_1 = mul_gauss(x, mu, sigma)
ret_2 = stats.multivariate_normal.pdf(x[0], mu[0], sigma)
print('ret_1=',ret_1)
print('ret_2=',ret_2)
Output:
ret_1= 0.013984262505331654
ret_2= 0.013984262505331658
Cheers.
Related
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()
normal pdf:
import numpy as np
import scipy
def gaussian(x, mu = 0, sigma = 1):
return 1/(np.sqrt(2*np.pi*sigma)) * np.exp(-(x-mu)**2 / (0.5*sigma)**2)
integrate over entire support:
scipy.integrate.quad(gaussian, -np.inf, np.inf)
returns
(0.3535533905932738, 1.4635936470160148e-11)
I know I messed up somewhere in the pdf but i've been starting at it for an hour and i can't see it
Your gaussian function is incorrect. It should be:
def gaussian(x, mu = 0, sigma = 1):
return (1/(sigma * np.sqrt(2 * np.pi))) * np.exp((-(x-mu)**2) / (2 * sigma ** 2))
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)$ ')
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
I came to ask for some help with maths and programming.
What am I trying to do? I'm trying to implement a simulation of a chaotic billiard system, following the algorithm in this excerpt.
How am I trying it? Using numpy and matplotlib, I implemented the following code
def boundaryFunction(parameter):
return 1 + 0.1 * np.cos(parameter)
def boundaryDerivative(parameter):
return -0.1 * np.sin(parameter)
def trajectoryFunction(parameter):
aux = np.sin(beta - phi) / np.sin(beta - parameter)
return boundaryFunction(phi) * aux
def difference(parameter):
return trajectoryFunction(parameter) - boundaryFunction(parameter)
def integrand(parameter):
rr = boundaryFunction(parameter)
dd = boundaryDerivative (parameter)
return np.sqrt(rr ** 2 + dd ** 2)
##### Main #####
length_vals = np.array([], dtype=np.float64)
alpha_vals = np.array([], dtype=np.float64)
# nof initial phi angles, alpha angles, and nof collisions for each.
n_phi, n_alpha, n_cols, count = 10, 10, 10, 0
# Length of the boundary
total_length, err = integrate.quad(integrand, 0, 2 * np.pi)
for phi in np.linspace(0, 2 * np.pi, n_phi):
for alpha in np.linspace(0, 2 * np.pi, n_alpha):
for n in np.arange(1, n_cols):
nu = np.arctan(boundaryFunction(phi) / boundaryDerivative(phi))
beta = np.pi + phi + alpha - nu
# Determines next impact coordinate.
bnds = (0, 2 * np.pi)
phi_new = optimize.minimize_scalar(difference, bounds=bnds, method='bounded').x
nu_new = np.arctan(boundaryFunction(phi_new) / boundaryDerivative(phi_new))
# Reflection angle with relation to tangent.
alpha_new = phi_new - phi + nu - nu_new - alpha
# Arc length for current phi value.
arc_length, err = integrate.quad(integrand, 0, phi_new)
# Append values to list
length_vals = np.append(length_vals, arc_length / total_length)
alpha_vals = np.append(alpha_vals, alpha)
count += 1
print "{}%" .format(100 * count / (n_phi * n_alpha))
What is the problem? When calculating phi_new, the equation has two solutions (assuming the boundary is convex, which is.) I must enforce that phi_new is the solution which is different from phi, but I don't know how to do that. Are there more issues with the code?
What should the output be? A phase space diagram of S x Alpha, looking like this.
Any help is very appreciated! Thanks in advance.
One way you could try would be (given there really are only two solutions) would be
epsilon = 1e-7 # tune this
delta = 1e-4 # tune this
# ...
bnds = (0, 2 * np.pi)
phi_new = optimize.minimize_scalar(difference, bounds=bnds, method='bounded').x
if abs(phi_new - phi) < epsilon:
bnds_1 = (0, phi - delta)
phi_new_1 = optimize.minimize_scalar(difference, bounds=bnds_1, method='bounded').x
bnds_2 = (phi + delta, 2 * np.pi)
phi_new_2 = optimize.minimize_scalar(difference, bounds=bnds_2, method='bounded').x
if difference(phi_new_1) < difference(phi_new_2):
phi_new = phi_new_1
else:
phi_new = phi_new_2
Alternatively, you could introduce a penalty-term, e.g. delta*exp(eps/(x-phi)^2) with appropriate choices of epsilon and delta.