def fit2DnormalDistribution(detector, fitFlag): X, Z = getDetectorHitData(detector) # Descriptive statistics skew_x_dim = skew(X) skew_z_dim = skew(Z) med = [np.median(X), np.median(Z)] if fitFlag == 1: # Bivariate normal fit (mu_nr, sigmaX_nr, sigmaZ_nr, alpha_nr) = fit_bivariate_normal(X, Z, robust=True) elif fitFlag == 0: sigmaX_nr = np.std(X) sigmaZ_nr = np.std(Z) alpha_nr = None mu_nr = [np.mean(X), np.mean(Z)] Gauss2D_dist = {'Mean': mu_nr, 'Median': med, 'Sigma X': sigmaX_nr, 'Sigma Z': sigmaZ_nr, 'Alpha': alpha_nr, 'Skew X': skew_x_dim, 'Skew Z': skew_z_dim} return Gauss2D_dist
def check_fit_bivariate_normal(sigma1, sigma2, mu, alpha, N=1000): # poisson stats rtol = 2 * np.sqrt(N) / N x, y = bivariate_normal(mu, sigma1, sigma2, alpha, N).T mu_fit, sigma1_fit, sigma2_fit, alpha_fit = fit_bivariate_normal(x, y) if alpha_fit > np.pi / 2: alpha_fit -= np.pi elif alpha_fit < -np.pi / 2: alpha_fit += np.pi # Circular degeneracy in alpha: test sin(2*alpha) instead assert_allclose(np.sin(2 * alpha_fit), np.sin(2 * alpha), atol=2 * rtol) assert_allclose(mu, mu_fit, rtol=rtol) assert_allclose(sigma1_fit, sigma1, rtol=rtol) assert_allclose(sigma2_fit, sigma2, rtol=rtol)
def calc(camera_id, frames): pc = np.zeros((3, 5, 5)) fig, ax = plt.subplots() for r in range(3): print(r) for c in range(5): X = [] Y = [] for index in range(150): iteration = int(index // 15) row = int((index % 15) // 5) col = int(index % 5) if row == r and col == c: [frame, x, y] = frames[index] X.append(x) Y.append(y) n_std = 3 xc, x_std = np.mean(X), np.std(X) yc, y_std = np.mean(Y), np.std(Y) pack = zip(X.copy(), Y.copy()) X = [] Y = [] for x, y in pack: if abs(x-xc) <= n_std * x_std and abs(y-yc) <= n_std * y_std: X.append(x) Y.append(y) X = np.array(X) Y = np.array(Y) assert(len(X) > 0) print('R = %d, C = %d, NUM = %d' % (r,c,len(X))) (center, a, b, theta) = fit_bivariate_normal(X, Y, robust=True) xc, yc = center ell = Ellipse(center, a * n_std, b * n_std, (theta * 180. / np.pi), ec='k', fc='none', color='red') index = r * 5 + c + 1 plt.scatter(X, Y, color=('C'+str(index)), s = 5) plt.scatter(xc, yc, color='red', s = 10) ax.add_patch(ell) pc[r,c] = [xc, yc, a, b, theta] plt.show() pickle.dump(pc, open('models/' + str(camera_id) + '.regist', 'wb'))
def fitBinsRobust(u, o): gaussSamples = 5000 noiseSamples = 500 #Draw random samples np.random.seed(1) gauss = np.random.multivariate_normal(u, o, gaussSamples) noise = np.random.multivariate_normal([0,8], [[2, 1],[1,2]], noiseSamples) #Add noise and flatten data xData = np.concatenate((gauss.ravel()[::2], noise.ravel()[::2])) yData = np.concatenate((gauss.ravel()[1::2], noise.ravel()[1::2])) data = [xData, yData] #Non-Robust Stats #stats = ast.fit_bivariate_normal(xData, yData) #Robust stats stats = ast.fit_bivariate_normal(xData, yData, robust=True) return data, stats
sigfit2_nonrob = np.ones(n_els) alpfit_rob = np.ones(n_els) alpfit_nonrob = np.ones(n_els) ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 3) ax3 = fig.add_subplot(2, 2, 2) for i, f in enumerate(cont_frac): # add outliers distributed using a bivariate normal. X[:int(f * N)] = bivariate_normal((10, 10), 2, 4, 45 * np.pi / 180., int(f * N)) x, y = X.T # compute the non-robust statistics (mu_nr, sigma1_nr, sigma2_nr, alpha_nr) = fit_bivariate_normal(x, y, robust=False) sigfit_nonrob[i] = sigma1_nr sigfit2_nonrob[i] = sigma2_nr alpfit_nonrob[i] = alpha_nr # compute the robust statistics (mu_r, sigma1_r, sigma2_r, alpha_r) = fit_bivariate_normal(x, y, robust=True) sigfit_rob[i] = sigma1_r sigfit2_rob[i] = sigma2_r alpfit_rob[i] = alpha_r # scatter the points for i in range(n_els): print "%g\t%g\t%g" %(cont_frac[i], sigfit_rob[i], alpfit_rob[i]) ax1.plot(cont_frac, sigfit_rob, '-k', label='Robust')
# Create the figure showing the fits fig = plt.figure(figsize=(10, 5)) fig.subplots_adjust(left=0.07, right=0.95, wspace=0.05, bottom=0.1, top=0.95) # We'll create two figures, with two levels of contamination for i, f in enumerate([0.05, 0.15]): ax = fig.add_subplot(1, 2, i + 1) # add outliers distributed using a bivariate normal. X[:int(f * N)] = bivariate_normal((10, 10), 2, 5, 45 * np.pi / 180., int(f * N)) x, y = X.T # compute the non-robust statistics (mu_nr, sigma1_nr, sigma2_nr, alpha_nr) = fit_bivariate_normal(x, y, robust=False) # compute the robust statistics (mu_r, sigma1_r, sigma2_r, alpha_r) = fit_bivariate_normal(x, y, robust=True) # scatter the points ax.scatter(x, y, s=4, lw=0, c='k', alpha=0.5) # Draw elipses showing the fits for Nsig in [1, 3]: # True fit E = Ellipse((10, 10), sigma1 * Nsig, sigma2 * Nsig,
# is drawn upon the data. from astroML.stats import fit_bivariate_normal import numpy as np import matplotlib.pyplot as plt import gauss # Produce a number of points in x-y from 1 bi-variate gaussian # distribution. mean = [1,1] cov = [[3,1],[1,3]] N = 1000 x,y = np.random.multivariate_normal(mean,cov,N).T # Fit method provided by astroML mean_est,sigma1,sigma2,alpha = fit_bivariate_normal(x,y) # Plot bi-variate gaussian with parameters and determine # variances in x-y. The covariance and variances should # approximate the original distribution drawn from. domain = 10; xCord = np.linspace(-domain,domain,N/domain) yCord = np.linspace(-domain,domain,N/domain) A = 1; X,Y,Z,varx,vary,cov,rho,P1,P2,P = gauss.mult_gaussPrincipal(A,xCord,yCord,mean[0],mean[1],sigma1**2,sigma2**2,alpha) sigma_x = np.sqrt(varx); sigma_y = np.sqrt(vary) V = [cov, 2*cov] plt.figure(1) plt.xlabel('x'); plt.ylabel('y'); plt.title('Distribution of Points with Gaussian Fit (As Contours)') lab = r'Estimated Parameters: $\sigma_x=%.2f$,$\sigma_y=%.2f$,$\sigma_{xy}=%.2f$,$\alpha=%.2f$' % (sigma_x,sigma_y,cov,alpha) p1, = plt.plot(x,y,'x'); plt.axis('equal')