I have an integration equations to calculate key rate and need to convert it into Python.
The equation to calculate key rate is given by:
where R(n) is:
and p(n)dn is:
The key rate should be plotted like this:
I have sucessfully plotted the static model of the graph using following equation:
import numpy as np
import math
from math import pi,e,log
import matplotlib.pyplot as plt
n1=np.arange(10, 55, 1)
n=10**(-n1/10)
Y0=1*(10**-5)
nd=0.25
ed=0.03
nsys=nd*n
QBER=((1/2*Y0)+(ed*nsys))/(Y0+nsys)
H2=-QBER*np.log2(QBER)-(1-QBER)*np.log2(1-QBER)
Rsp=np.log10((Y0+nsys)*(1-(2*H2)))
print (Rsp)
plt.plot(n1,Rsp)
plt.xlabel('Loss (dB)')
plt.ylabel('log10(Rate)')
plt.show()
However, I failed to plot the R^ratewise model. This is my code:
import numpy as np
import matplotlib.pyplot as plt
def h2(x):
return -x*np.log2(x)-(1-x)*np.log2(1-x)
e0=0.5
ed=0.03
Y0=1e-5
nd=0.25
nt=np.linspace(0.1,0.00001,1000)
y=np.zeros(np.size(nt))
Rate=np.zeros(np.size(nt))
eta_0=0.0015
for (i,eta) in enumerate(nt):
nsys=eta*nd
sigma=0.9
y[i]=1/(eta*sigma*np.sqrt(2*np.pi))*np.exp(-(np.log(eta/eta_0)+(1/2*sigma*sigma))**2/(2*sigma*sigma))
Rate[i]=(max(0.0,(Y0+nsys)*(1-2*h2(min(0.5,(e0*Y0+ed*nsys)/(Y0+nsys))))))*y[i]
plt.plot(nt,np.log10(Rate))
plt.xlabel('eta')
plt.ylabel('Rate')
plt.show()
Hopefully that anyone can help me to code the key rate with integration p(n)dn as stated above. This is the paper for referrence:
key rate
Thank you.
I copied & ran your second code block as-is, and it generated a plot. Is that what you wanted?
Using y as the p(n) in the equation, and the Rsp as the R(n), you should be able to use
NumPy's trapz function
to approximate the integral from the sampled p(n) and R(n):
n = np.linspace(0, 1, no_of_samples)
# ...generate y & Rst from n...
R_rate = np.trapz(y * Rst, n)
However, you'll have to change your code to sample y & Rst using the same n, spanning from 0 to 1`.
P.S. there's no need for the loop in your second code block; it can be condensed by removing the i's, swapping eta for nt, and using NumPy's minimum and maximum functions, like so:
nsys=nt*nd
sigma=0.9
y=1/(nt*sigma*np.sqrt(2*np.pi))*np.exp(-(np.log(nt/eta_0)+(1/2*sigma*sigma))**2/(2*sigma*sigma))
Rate=(np.maximum(0.0,(Y0+nsys)*(1-2*h2(np.minimum(0.5,(e0*Y0+ed*nsys)/(Y0+nsys))))))*y
Related
I am trying to code two random variables with a correlation. I have been given $Z_1\tilde N(0,1)$ and $Z_2\tilde N(0,1)$. I is also given $cor(Z_1,Z_2)=\rho$. So I need the formula to get $Z_2$ from $Z_1$. Initially, I was trying this code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
rho=0.5
N=100
Z1=np.random(N)
Z2=np.random(N)
return Z2
However, then I realized that $Z_2$ is now no longer correlated to $Z_1$. So I want to ask how I can get the correct $Z_2$.
Let $\alpha$ such that $\alpha^2+\rho^2 = 1$. Let $X, Y$ be independent $N(0,1)$ distributed variables. Set $Z_1 := \rho * X + \alpha * Y$ and $Z_2:=X$. Now $Z1, Z_2$ should fulfill your requirements.
I want to use the spectral method to solve partial differential equations. The equations like that, formula,the initial condition is u(t=0,x)=(a^2)*sech(x),u'_t (t=0)=0.
To solve it, I use the python with the spectral method. Following is the code,
import numpy as np
from scipy.integrate import solve_ivp
from scipy.fftpack import diff as psdiff
#RHS of equations
def f(t,u):
uxx= psdiff(u[N:],period=L,order=2)
du1dt=u[:N]
du2dt =a**2*uxx
dudt=np.append(du1dt,du2dt)
return dudt
a=1
amin=-40;bmax=40
L=bmax-amin;N=256
deltax=L/N
x=np.arange(amin,bmax,deltax)
u01 = 2*np.cosh(x)**(-1)
u02=np.zeros(N)
# y0
inital=np.append(u01,u02)
sola1 = solve_ivp(f, t_span=[0,40],y0=inital,args=(a,))
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x,sola1.y[:N,5])
plt.show()
Following is my expected result,
expected result.
My python code can run,but I can't get the expected result,and can't find the problem.Following is the result from my python code,
my result
-----------------------------Update----------------------------------------------
I also try a new code,but still can't solve
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from scipy.fftpack import diff as psdiff
from itertools import chain
def lambdifide_odes(y,t,a):
# uxx =- (1j)**2*k**2*u[:N]
u1=y[::2]
u2=y[1::2]
dudt=np.empty_like(y)
du1dt=dudt[::2]
du2dt=dudt[1::2]
du1dt=u2
uxx=psdiff(u1,order=2,period=L)
du2dt=a**2*uxx
return dudt
a=1
amin=-40;bmax=40
L=bmax-amin;N=256
deltax=L/N
x=np.arange(amin,bmax,deltax)
u01 = 2*np.cosh(x)**(-1)
u02=np.zeros(N)
initial=np.array(list(chain.from_iterable(zip(u01,u02))))
t0=np.linspace(0,40,100)
sola1 = odeint(lambdifide_odes,y0=initial,t=t0,args=(a,))
fig, ax = plt.subplots()
ax.plot(x,sola1[20,::2])
plt.show()
You have some slight problem with the design of your state vector and using this in the ODE function. The overall intent is that u[:N] is the wave function and u[N:] its time derivative. Now you want the second space derivative of the wave function, thus you need to use
uxx= psdiff(u[:N],period=L,order=2)
at the moment you use the time derivative, making this a mixed third derivative that does not occur in the equation.
I need the values of the autocorrelation coefficients coming from the autocorrelation_plot(). The problem is that the output coming from this function is not accessible, so I need another function to get such values. That's why I used acf() from statsmodels but it didn't get the same plot as autocorrelation_plot() does. Here is my code:
from statsmodels.tsa.stattools import acf
from pandas.plotting import autocorrelation_plot
import matplotlib.pyplot as plt
import numpy as np
y = np.sin(np.arange(1,6*np.pi,0.1))
plt.plot(acf(y))
plt.show()
So the result is not the same as this:
autocorrelation_plot(y)
plt.show()
This seems to be related to the nlags parameter of acf:
nlags: int, optional
Number of lags to return autocorrelation for.
I don't know what exactly this does but in the source of acf there is a slicing
that shortens the array:
avf = acovf(x, unbiased=unbiased, demean=True, fft=fft, missing=missing)
acf = avf[:nlags + 1] / avf[0]
If you use statsmodels.tsa.stattools.acovf directly the result is the same as with autocorrelation_plot:
avf = acovf(x, unbiased=unbiased, demean=True, fft=fft, missing=missing)
So you can call it like
plt.plot(acf(y, nlags=len(y)))
to make it work.
An explanation of lag: https://math.stackexchange.com/questions/2548314/what-is-lag-in-a-time-series/2548350
I am writing a code about a mono-energetic gamma beam which the dominated interaction is photoelectric absorption, mu=2 cm-1, and i need to generate 50000 random numbers and sample the interaction depth(which I do not know if i did it or not).
I know that the mean free path=mu-1, but I need to find the mean free path from the simulation and from mu and compare them, is what I did right in the code or not?
import random
import matplotlib.pyplot as plt
import numpy as np
mu=(2)
random.seed=()
data = np.random.randn(50000)*10
bins = np.arange(data.min(), data.max()+1e-8, 0.1)
meanfreepath = 1/mu
print(meanfreepath)
plt.hist(data, bins=bins)
plt.show()
Well, interaction depth distribution is Exponential one, not a gaussian.
So code would be
lmbda = 2 # cm^-1
beta = 1.0/lmbda
data = np.random.exponential(scale=beta, size=50000)
mfp = np.mean(data)
print(mfp)
# build histogram
More details at https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.exponential.html
Code above produced
0.4977168417102998
which looks like 2-1 to me
I'm pretty new to python and curve fitting and currently I'm trying to fit the graph below with a Gaussian
I'm following this tutorial and my code looks like this
import numpy as np
import matplotlib.pyplot as plt
from pylab import genfromtxt
from matplotlib import pyplot
from numpy import sqrt, pi, exp, linspace,loadtxt
from lmfit import Model
def gaussian(x,amp,cen,wid):
"1-d gaussian: gaussian(x,amp,cen,wid)"
return (amp/(sqrt(2*pi)*wid))*exp(-(x-cen)**2/(2*wid**2))
filelist=[]
time=[0.00,-1.33,-2.67,-4.00,-5.33,-6.67,1.13,2.67,4.00,5.33,6.67]
index=0
offset=0
filelist.append('0.asc')
for i in range(1,6):
filelist.append("-%s00.asc" %(i))
for i in range(1,6):
filelist.append("+%s00.asc" %(i))
sfgpeaks=[]
for fname in filelist:
data=np.genfromtxt(fname,delimiter=',',unpack=True,skip_footer=20)
SFGX=data[0,500:530]
SFGY=data[1,500:530]
SFGpeakY=np.max(SFGY)
sfgpeaks.append(SFGpeakY)
gmodel = Model(gaussian)
result = gmodel.fit(SFGpeakY, x=time[index], amp=5,cen=5,wid=3)
plt.plot(time[index],sfgpeaks[index],'ro')
plt.plot(time[index],result.init_fit, 'k--',label="Gaussian Fit")
plt.xticks(time)
index=index+1
print(pump2SHGX)
pyplot.title("Time Delay-SFG peak")
plt.xlabel("Timedelay[ps]")
plt.ylabel("Counts[arb.unit]")
plt.savefig("796and804nmtimesfg")
plt.legend(bbox_to_anchor=(1.0,0.5))
plt.show()
However, I'm getting an error when I try to add the data that I have(time delay and the Y value of the graph above) into the gaussian parameters.
The error I'm getting is this
TypeError: Improper input: N=3 must not exceed M=1
Does this error because I'm trying to insert a value from an array into the parameter??
Any help is much appreciated.
You have
result = gmodel.fit(SFGpeakY, x=time[index], amp=5,cen=5,wid=3)
which is passing 1 value as x and 1 value as the data. The model is then evaluated at that 1 point. The error message is the fit is complaining that you have 3 variables and 1 value.
You probably want to fit the data array SFGY with x set to SFGX,
result = gmodel.fit(SFGY, x=SFGX, amp=5,cen=5,wid=3)
though it wasn't clear to me what data is used in the plot you attached.
Also: you probably want to give initial values for amp, cen, and wid based on the data. Your SFGpeakY is probably a decent guess for amp, and SFGX.mean() and SFGX.std() are probably decent guesses or cen and wid.
Also: you plot result.init_fit labeled as "Gaussian Fit". result.init_fit will be the model evaluated with the initial values for the parameters. The best fit with the refined parameters will be in result.best_fit.