def dchisq(x,df,ncp=0):
    """
    Calculates the density/point estimate of the chi-square distribution
    """
    from scipy.stats import chi2,ncx2
    if ncp==0:
        result=chi2.pdf(x=x,df=df,loc=0,scale=1)
    else:
        result=ncx2.pdf(x=x,df=df,nc=ncp,loc=0,scale=1)
    return result
Exemple #2
0
def lrtc_ber_formula(ebn0_dB, n_bin):
    ebn0 = 10**(0.1 * ebn0_dB)
    cnr = ebn0 * Rb / fs * N_fft
    ber = np.zeros(len(cnr))

    for i in range(len(cnr)):
        y = lambda x: ncx2.pdf(x, 2, cnr[i] * 2) * (chi2.cdf(x, 2)**
                                                    (n_bin - 1))
        p, err = integrate.quad(y, np.NINF, np.PINF)
        ber[i] = (1 - p) * (n_bin / 2) / (n_bin - 1)
    return ber
Exemple #3
0
def fit_func(x, df, nc):
    return ncx2.pdf(x, df, nc)
#ax.plot(bins+dx, np.zeros(bins.shape[0]), 'o')


def fit_func(x, df, nc):
    return ncx2.pdf(x, df, nc)


popt, pcov = curve_fit(fit_func, bins[:-1] + dx, n, p0=(20, 10))
# and overplot the fitted curve
df_fit = popt[0]
nc_fit = popt[1]
df_err = np.sqrt(pcov[0, 0])
nc_err = np.sqrt(pcov[1, 1])
ax.plot(
    x,
    ncx2.pdf(x, df_fit, nc_fit),
    label=
    F'fit, $df={df_fit:1.2f} \pm {df_err:1.2f}, nc={nc_fit:1.2f} \pm {nc_err:1.2f}$',
    linewidth=0.8)
ax_cdf = ax.twinx()
ax_cdf.set_ylabel('cdf')
ax.set_xlim((0, 40))
ax.xaxis.set_major_locator(MultipleLocator(5))
ax.xaxis.set_minor_locator(MultipleLocator(1))
xlim = ax.get_xlim()
ax_cdf.hist(ts_max,
            density=True,
            bins=cum_bins,
            cumulative=True,
            histtype='step',
            color='black',
from scipy.stats import norm
from scipy.stats import chi2

import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.dpi'] = 300

#%%

df = 10_000
theta = 2
nc = np.sqrt(2 * df) * theta

x = np.linspace(ncx2.ppf(0.001, df, nc), ncx2.ppf(0.999, df, nc), 1000)

plt.plot(x, ncx2.pdf(x, df, nc), label='theta = {:.2f}'.format(theta))
plt.legend()
plt.show()

#%%


def sample_nc2x(theta=0, df=100, size=1000):
    nc = theta * np.sqrt(2 * df)
    Y = chi2.rvs(df - 1, size=size)
    Z = norm.rvs(size=size)
    Y += nc + 2 * np.sqrt(nc) * Z + Z**2
    return Y


df = 10_000
def B(t, T):
    return (np.exp(h1 * (T - t)) - 1) / (h2 * (np.exp(h1 * (T - t)) - 1) + h1)


def P(t, T, rt):
    return A(t, T) * np.exp(-B(t, T) * rt)


theta = np.sqrt(k**2 + 2 * s**2)
phi = 2 * theta / (s**2 * (np.exp(theta * T) - 1))
psi = (k + theta) / (s**2)

r_star = np.log(A(T, S) / K) / B(T, S)

CIR_c = (FV*P(0,S,r0)*ncx2.pdf(2*r_star*(phi+psi+B(T,S)), 4*k*r_bar/(s**2), (2*phi**2)*r0*np.exp(theta*T)/(phi+psi+B(T,S))) - \
        0.98*P(0,T,r0)*ncx2.pdf(2*r_star*(phi+psi), 4*k*r_bar/(s**2), (2*phi**2)*r0*np.exp(theta*T)/(phi+psi)))/100

CIR_c

#3
r0 = 0.03
x0 = 0
y0 = 0
phi0 = 0.03
rho = 0.7
a = 0.1
b = 0.3
s = 0.03
e = 0.08
S = 1
Exemple #7
0
rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
rc('text', usetex=True)
nbins = 30
np.random.seed(420)
fig = plt.figure(1, dpi=150)
ax = fig.add_subplot(111)
ax.set_xlim((0, 42))
ax.set_title('Analysis of PE')
ax.set_xlabel('TS')
ax.set_ylabel('pdf, normalized')

# parameters of non central chi squared distribution
df, nc = 10.09, 2.51
# plot the pdf
x = np.linspace(0, 43, num=1000)
y = ncx2.pdf(x, df, nc)
ax.plot(x, y, label=f'pdf, $df={df}, nc={nc}$', color='black', linewidth=0.8)

# generate some random numbers, do some histogram things
random = ncx2.rvs(df, nc, size=1000)
n, bins, patches = ax.hist(random,
                           bins=nbins,
                           label='random numbers',
                           density=True,
                           color='grey')
cum_bins = bins.copy()
cum_bins[-1] = 50
# do fit from random numbers
# get x places:
dx = (bins[1] - bins[0]) / 2
x_r = np.linspace(bins[0] + dx / 2, bins[-1] - dx / 2, num=len(bins))
from scipy.stats import ncx2
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)

# Calculate a few first moments:

df, nc = 21, 1.06
mean, var, skew, kurt = ncx2.stats(df, nc, moments='mvsk')

# Display the probability density function (``pdf``):

x = np.linspace(ncx2.ppf(0.01, df, nc), ncx2.ppf(0.99, df, nc), 100)
ax.plot(x, ncx2.pdf(x, df, nc), 'r-', lw=5, alpha=0.6, label='ncx2 pdf')

# Alternatively, the distribution object can be called (as a function)
# to fix the shape, location and scale parameters. This returns a "frozen"
# RV object holding the given parameters fixed.

# Freeze the distribution and display the frozen ``pdf``:

rv = ncx2(df, nc)
ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

# Check accuracy of ``cdf`` and ``ppf``:

vals = ncx2.ppf([0.001, 0.5, 0.999], df, nc)
np.allclose([0.001, 0.5, 0.999], ncx2.cdf(vals, df, nc))
# True

# Generate random numbers:
rho=-0.9
x1=z1
x2=rho*z1+np.sqrt(1-rho*rho)*z2
print(np.corrcoef(x1,x2))
plt.figure()
plt.subplot(1,2,1)
plt.plot(z1,z2,'.')
plt.subplot(1,2,2)
plt.plot(x1,x2,'.')
plt.show()
## Simulation 4.5 (Noncentral Chi2-distribution)
from scipy.stats import ncx2
x=np.arange(.001,10.01,0.1)
for k in [2,5]:
    for lam in range(1,4):
        y=ncx2.pdf(x,k,lam)
        plt.plot(x,y)
plt.show()

# Chapter 7. Brownian motion
import numpy as np
import matplotlib.pyplot as plt;
## Simulation7.1 (sample paths of Brownian motion)
n=500
t=20
dt=t/n
time=np.arange(0,t+dt*0.1,dt)
m=50 # number of sample paths
w=np.zeros((m,n+1))
dw=np.sqrt(dt)*np.random.randn(m,n)
for i in range(n):