# these 4 are from exer1 # for comparison X1 = np.polyfit(layer_x, ytrack1, 1)[1] X2 = np.polyfit(layer_x, ytrack2, 1)[1] Xav = (X1 + X2) / 2 - X0 histXav[i] = Xav # convert units to micrometer histConst *= 10**4 # histPull *= 10**4 histXav *= 10**4 # set up bins and scale after observation binEdges = np.linspace(-500, 500, 100) ax[0].hist(histConst, bins=binEdges, align="left", label="Constrained fit") statBox(ax[0], histConst, binEdges, name="Constrain") ax[0].set_title("X0 - Xf with constrain") ax[0].set(xlabel="$\Delta$ X ($\mu m$)") # ax[1].hist(histPull, bins=binEdges, log=True, align="left") pullbinEdges = np.linspace(-5, 5, 100) ax[1].hist(histPull, bins=pullbinEdges, log=True, align="left") ax[1].set_title("Pull of constrained fit") ax[1].set(xlabel="$\Delta$ X ($\mu m$)") # ----------------un-comment and change line 7 to compare to average method --- # ax[2].hist(histXav, bins=binEdges, align="left") # ax[2].set_title("Xav - X0") # # label everything # ax[2].set(xlabel="$\Delta$ X ($\mu m$)") # # add claudio's box # statBox(ax[2], histXav, binEdges, name="Average")
import matplotlib.pyplot as plt from ccHistStuff import statBox, plotErr #dataSet = np.load("dataSet.npy")#Loads numpy data set # need to load a txt file, simply a list of numbers!! not too bad hopefully dataSet = np.loadtxt('mass.txt') #print(dataSet) dataArray = np.array(dataSet) #creats a 1D array populated with dataSet data bins = 17# binEdges = [0,20] # Plot histogram of data and log scale on y axis. fig = plt.figure() # create a plot object ax = fig.add_subplot(1,1,1) # Add a plot space (in this case the whole window) hist = plt.hist(dataArray, bins = bins, normed=True) # histogram plot ax.set_yscale('log') #linear to log on y (allows us to visualize distribution better) statBox(ax, dataArray, binEdges) # adds statistics box to graph plt.show() # have to tell python to show the plot!! ## Problem: this is not ploting a histogram at the moment, # Good: Numpy array is imported correctly # Good: a figure is being created # Bad: histo bars are not showinup on graph
#------------------------------------------------------------ # Conner Addison 8984874 # Physics 129L #------------------------------------------------------------ # Homework 4, Exercise 1 import numpy as np import matplotlib.pyplot as plt import math as m from ccHistStuff import statBox # Loading data x = np.load('dataSet.npy') # Setting up figure fig = plt.figure() ax = fig.add_subplot(111) ax.set_yscale('log') ax.set(title='Data set array frequency, semi-log', xlabel='Value of x', ylabel='Frequency of value, log scale') # Finishing fig ax.hist(x, m.floor(max(x) * 3)) statBox(ax, x, x) plt.savefig('datavis.png') plt.show()
intercept1 = popt1[1] diff0 = intercept0 - x0 diff1 = intercept1 - x0 diffav = np.mean([intercept0,intercept1]) - x0 difference0.append(diff0) difference1.append(diff1) differenceav.append(diffav) #Plotting fig, ax = plt.subplots() binEdges = np.linspace(-500,500,100) ax.hist([difference0,difference1],bins=binEdges,label=['X1-X0', 'X2-X0']) cc.statBox(ax, difference0, binEdges, x=.21, y=.98,label='Track 1') cc.statBox(ax, difference1, binEdges, x=.98, y=.98,label='Track 2') plt.legend(loc='center right') plt.xlabel('Intercept Difference [micrometers]') plt.ylabel('Number of Occurences') fig.show() input('Press <Enter> to continue') fig, ax = plt.subplots() binEdges = np.linspace(-500,500,100) ax.hist(differenceav,bins=binEdges,label='Xav-X0',edgecolor='black') cc.statBox(ax,differenceav,binEdges,label='Average of Tracks') plt.legend(loc='center right') plt.xlabel('Average Intercept Difference [micrometers]') plt.ylabel('Number of Occurences') fig.show()
# Since we are just making a plot it does not matter. # If we were to use x for some real work we would # reshuffle the elements with np.random.shuffle #------------------------------------------------ # Plot the histogram and the line #------------------------------------------------ fig, ax, = plt.subplots() # the histogram contents, binEdges, _ = ax.hist(x, np.linspace(0., 1., nbins + 1), histtype='step', log=False, color='blue') cc.statBox(ax, x, binEdges, x=0.3) # cc.plotErr(ax, contents, binEdges, color='blue') # the line (mind the normalization!!!!) xl = np.array([0., 1.]) # straight line, 2 points are enough!!! yl = (1. / 3) * (1. + 4 * xl) * (n / nbins) ax.plot(xl, yl, color='orange', linestyle='dashed') # make it prettier ax.set_xlim(binEdges[0], binEdges[-1]) ax.tick_params("both", direction='in', length=10, right=True) ax.set_xticks(binEdges, minor=True) ax.tick_params("both", direction='in', length=7, right=True, which='minor') ax.set_xlabel("Linear random variable") ax.set_ylabel("Number of entries")
#------------------------------------------------------------ # Conner Addison 8984874 # Physics 129L #------------------------------------------------------------ # Homework 5, Exercise 3 import math import numpy as np import matplotlib.pyplot as plt from ccHistStuff import statBox # Loading data txt_file = 'mass.txt' bins = 20 data = np.loadtxt(txt_file) # Setting up figure fig = plt.figure() ax = fig.add_subplot(111) ax.hist(data, bins) ax.set(title='Mass frequency distribution', xlabel='Mass', ylabel='Frequency of value') statBox(ax, data, data) plt.show()
step4 = np.matmul(step3, At) step5 = np.matmul(step4, W) dp = np.matmul(step5, dy) # Reassigning guess, must have lost negative sign somewhere because this only works with the minus p[0] -= dp[0][0] p[1] -= dp[1][0] print(f"---------- ITERATION {j + 1} ----------") print(f" p = {p}") print("") # Printing results print("") print("-------------------- FINAL RESULTS (BLUE) --------------------") print(f"p = {p}") y_f = np.array([exponential_fit(i, p) for i in x]) chi = chiSquared(y_f, y0) print(f"Chi squared = {chi}") print("") # Finishing fig ax.set_yscale('log') ax.set(title='Log data fit, Gaussian regime', xlabel='X', ylabel='Count', xlim=(bin_centers[0], bin_centers[N - 1])) cc.statBox(ax, x, bins) ax.plot(x, y, color='b') #plt.savefig('chifit.png') plt.show()
#!/usr/bin/python3 #Zipeng Wang #3909934 #read data from .npy file and plot a semilog histogram import ccHistStuff as cc import numpy as np import matplotlib.pyplot as plt data = np.load('dataSet.npy')#import data print(min(data),max(data)) #for test purposes #histogram nbins = 24 bins = np.linspace(0,24,nbins+1)#get these numbers from trial fig,ax = plt.subplots() contents,binEdges,_, = ax.hist(data,bins,log = True,color = 'b',rwidth = 0.85) cc.statBox(ax,data,binEdges)# add cc's stat box #Fig config stuffs ax.set_xlim(binEdges[0],binEdges[-1]) ax.set_xticks(binEdges,minor = True) ax.tick_params("both",direction = 'in') ax.set_xlabel('x') ax.set_ylabel('count') plt.show()
xlist.append(xlist[-1]) # put list into array removing the burn in part xr = np.array(xlist[nBurn:]) # now plot it...go out to 4 sigma low = mean - 4 * sigma high = mean + 4 * sigma nbins = 100 bins = np.linspace(low, high, nbins + 1) fig, ax = plt.subplots() contents, bins, _ = ax.hist(xr, bins, histtype='step', color='blue') # Add a stats box at the top right edge (CUSTOM CODE) cc.statBox(ax, xr, bins) # Add errors (CUSTOM CODE) # cc.plotErr(ax, contents, bins, color='blue') # The default is to *not* have the x axis run from # the lowest bin edge to the highest bin edge. # This seems pretty silly, so override this ax.set_xlim(bins[0], bins[-1]) # I do not like the defaults.... # I want the ticks to be into the plot, also on the right of the plot ax.tick_params("both", direction='in', length=10, right=True) # Also show a gaussian curve of correct mean,sigma. # Properly normalized given number of entries and binsize.
fig = plt.figure(figsize=(14, 6)) plot = fig.add_subplot(131) fig.subplots_adjust(wspace=.5) for n in range(10): plot.plot(data[n][0][1], data[n][1][0], color='.6', linestyle='--') plot.plot(data[n][1][1], data[n][1][0], color='.6', linestyle='--') plot.set(title='First 10 collisions', xlabel=r'Sensor $x$ position', ylabel=r'Sensor $y$ position') # Adding histogram of error hist1 = fig.add_subplot(132) hist2 = fig.add_subplot(133) (n1, bins1, patches1) = hist1.hist((x1_x0, x2_x0), 20, stacked=True) (n2, bins2, patches2) = hist2.hist(xa_x0, 20) hist1.set(xlim=(-.05, .05), title=r'$(x_1/x_2 - x_0 )$', xlabel=r'$\Delta x$', ylabel='Counts') hist2.set(xlim=(-.05, .05), title=r'$x_a - x_0$', xlabel=r'$\Delta x$', ylabel='Counts') # Adding stat box cc.statBox(hist1, x1_x0, bins1) cc.statBox(hist2, xa_x0, bins2) # Saving/showing figure #plt.savefig('tracks.png') plt.show()
print(" ") population[i] = blah #------------------------------------------------------------------- # extract the first digit, as a number, from the population string #------------------------------------------------------------------ digit = np.array([]) for entry in population: digit = np.append(digit, int(entry[0])) #------------------------------------------------ # Plot the digit now #------------------------------------------------ fig, ax, = plt.subplots() contents, binEdges, _ = ax.hist(digit, np.linspace(0.5, 9.5, 10), histtype='step', log=False, color='black') # Make it prettier, add the stat box cc.statBox(ax, digit, binEdges) # cc.plotErr(ax, contents, binEdges, color='blue') ax.set_xlim(binEdges[0], binEdges[-1]) # ax.set_ylim(0. , 1.4*np.max(contents)) ax.tick_params("both", direction='in', length=10, right=True) ax.set_xticks(binEdges, minor=True) # ax.tick_params("both", direction='in', length=7, right=True, which='minor') fig.show() input("Press any key to continue")
####################################### end of fit 3 print('end of fit 3') # Histogram configuration x1 = 100. x2 = 200. nb = 20 bins = np.linspace(x1, x2, nb+1) # plot the histogram # plot fitted curve1 f1, a1 = plt.subplots() c, b, _ = a1.hist(mass, bins, histtype='step') cc.statBox(a1, mass, b) a1.set_xlim(b[0], b[-1]) a1.tick_params("both", direction='in', length=10, right=True) a1.set_xticks(b, minor=True) a1.tick_params("both", direction='in', length=7, right=True, which='minor') plot_x = np.linspace(100,200,1001) plot_y = fittedB1*B_1(plot_x,fitteda)+fittedS1*S_pdf(plot_x) a1.plot(plot_x,plot_y*5,label='exponential fit') # have this *5 factor because the #area of the # histogram is not 200 but 200*5(bin width) a1.set_xlabel('mass[GeV]') a1.set_ylabel('count') a1.legend(loc = 'upper left') # plot fitted curve2
#Chi-Squared Calculation (if desired) y0_theory = popt[0]*(x_data - intercept) y1_theory = popt[1]*(x_data - intercept) y_theory = np.concatenate((y0_theory,y1_theory)) y_data = np.concatenate((y0_data,y1_data)) chi = chisquare(y_data, y_theory)[0] chi_squ.append(chi) #Plotting fig, ax = plt.subplots() binEdges = np.linspace(-500,500,100) ax.hist(difference, bins=binEdges, label='Difference', edgecolor='black') cc.statBox(ax, difference, binEdges, label='Constrained Fit') plt.legend(loc='center right') plt.xlabel('Intercept Difference [micrometers]') plt.ylabel('Number of Occurences') fig.show() input('Press <Enter> to continue') fig, ax = plt.subplots() binEdges = np.linspace(-.02,.02,100) ax.hist(pull_values, bins=binEdges, label='Pull', edgecolor='black',log=True) cc.statBox(ax, pull_values, binEdges, label='Pull') plt.legend(loc='center right') plt.xlabel('Pull') plt.ylabel('Number of Occurences') fig.show() input('Press <Enter> to continue')
# Plotting stuff (default: one subplot in x and one in y) thisFigure, thisAxes = plt.subplots() # the bin edges (nbins + 1 because of lower and upper edge) nbins = 40 bins = np.linspace(0, 20, nbins+1) # the histogram fig, ax = plt.subplots() contents, binEdges, _ = ax.hist(data, bins, histtype='step', log=True, color='black',label='Raw Data') # We were asked to add labels and stat box ax.set_xlabel('X') ax.set_ylabel('Entries per 0.5') cc.statBox(ax, data, binEdges) # This is purely esthetics (personal preference) ax.tick_params("both", direction='in', length=10, right=True) ax.set_xticks(binEdges, minor=True) ax.tick_params("both", direction='in', length=7, right=True, which='minor') ax.set_xlim(0, 20) plt.plot(data, f(data,p_0,p_1),label='Chi-Squared Fit' ) plt.legend(loc='center left') fig.show() input('Press <Enter> to continue')
from scipy import special import ccHistStuff as cc # Read the masses into an array mass = np.loadtxt("mass.txt") # How many do we have, what is the max and min # print( len(mass) ) # m1 = np.amax(mass) # m2 = np.amin(mass) # print(m1,m2) # From te tests above, looks like 200 entries # between 100 and 200? # A reasonable binning may be 20 bisn x1 = 100. x2 = 200. nb = 20 bins = np.linspace(x1, x2, nb + 1) # plot now f, a = plt.subplots() c, b, _ = a.hist(mass, bins, histtype='step') cc.statBox(a, mass, b) a.set_xlim(b[0], b[-1]) a.tick_params("both", direction='in', length=10, right=True) a.set_xticks(b, minor=True) a.tick_params("both", direction='in', length=7, right=True, which='minor') f.show() input("Carriage return to continue....")
X0 = np.array(X0) X1 = np.array(X1) X2 = np.array(X2) low = -500*10**(-4) high = -low nbins = 100 bins = np.linspace(low,high,nbins+1) fig1,ax1 = plt.subplots() c1,b1,_, = ax1.hist((X1-X0),bins, histtype = 'step',color= 'b',label = 'X1-X0') c2,b2,_, = ax1.hist((X2-X0),bins,histtype = 'step',color = 'r',label = 'X2-X0') #cc.statBox(ax1,(X1-X0),b1) #ccStatBoxes will stack together if multiples are in the #graph. Only show (X2-X0) since they are more or less the same cc.statBox(ax1,(X2-X0),b1) ax1.set_xlim(b1[0],b1[-1]) ax1.legend(loc = 'upper left') ax1.set_xlabel('X_fitted - X0[cm]') ax1.set_ylabel('count') fig2,ax2 = plt.subplots() Xav = (X1+X2)/2 c3,b3,_, = ax2.hist((Xav-X0),bins,histtype = 'step',color = 'k',label = 'Xav-X0') cc.statBox(ax2,(Xav-X0),b1) ax2.set_xlim(b1[0],b1[-1]) ax2.legend(loc = 'upper left') ax2.set_xlabel('X_fitted - X0[cm]') ax2.set_ylabel('count')
chisq = ((N - y0)**2 / N).sum() print(' ') print('interation No.', iteration) print('Chisq is', chisq) print('p0=', p[0]) print('p1=', p[1]) #print final parameters and chisq print('') print('final values') print('Chisq is', chisq) print('p0=', p[0]) print('p1=', p[1]) #plot fitted functions (extend to the full range of graph) y_long = f(x_long, p[0], p[1]) ax.plot(x_long, y_long, '--r') # We were asked to add labels and stat box ax.set_xlabel('X') ax.set_ylabel('Entries per 0.5') cc.statBox(ax, X, binEdges) # This is purely esthetics (personal preference) ax.tick_params("both", direction='in', length=10, right=True) ax.set_xticks(binEdges, minor=True) ax.tick_params("both", direction='in', length=7, right=True, which='minor') ax.set_xlim(0, 20) plt.show()
# Extract the arguments seed = args['seed'] N = args['nEvents'] tau = args['tau'] nbins = args['bins'] tmax = args['maxHist']*tau # Initialize random number np.random.seed(seed) # the times (could have used np.random.exponential instead) times = -tau * np.log(np.random.rand(N)) # Plotting stuff (default: one subplot in x and one in y) fig, ax = plt.subplots(1,1) # the bin edges (nbins + 1 because of lower and upper edge) bins = np.linspace(0, tmax, nbins+1) # the histogram contents, binEdges, _ = ax.hist(times, bins, histtype='step', log=True, color='black') cc.statBox(ax, times, binEdges) ax.set_xlim(binEdges[0], binEdges[-1]) ax.tick_params("both", direction='in', length=10, right=True) # show the figure fig.show() # plt.show() (this would pause automatically) input("Press any key to continue")