def plot_filter_performance_threshold(self, fname=None): """ Plot filter fake rate and efficiency vs threshold. Parameters ---------- fname : str, optional The filter. Optional if there's only one filter. Return ------ fig : matplotlib figure The figure where the plot is drawn. """ fname = self._fname(fname) figname = 'temps1.Simulation.plot_filter_performance_threshold.' + fname.replace(" ", "_") fig, axs = plt.subplots(2, 1, num=figname, figsize=[6.4, 7.19], clear=True, sharex=True) ax = axs[0] ax.set_ylabel('Rate of S1 candidates [s$^{-1}$]') for k in ['all', 'dcr', 's1']: f, t = self.candidates_above_threshold(fname, k, rate=True) x = np.concatenate([t, t[-1:]]) y = np.concatenate([f(t), [0]]) ax.plot(x, y, drawstyle='steps-pre', **self.plotkw[k]) rate1 = 1 / (self.T * 1e-9) ax.axhspan(0, rate1, color='#ddd', label='$\\leq$ 1 cand. per event') ax.set_yscale('log') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax.legend(loc='upper right', title=fname + ' filter') ax = axs[1] ax.set_ylabel('S1 detection efficiency') ax.set_xlabel('Threshold on filter output') for k in ['all', 's1']: f, t = self.candidates_above_threshold(fname, k, signalonly=True) x = np.concatenate([t, t[-1:]]) y = np.concatenate([f(t), [0]]) ax.plot(x, y, drawstyle='steps-pre', **self.plotkw[k]) textbox.textbox(ax, self.infotext(), fontsize='small') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax.set_ylim(0, max(1, np.max(y))) fig.tight_layout() return fig
def plot_filter_performance(self, filters=None, interp=False): """ Plot filter efficiency vs fake rate. Parameters ---------- filters : (list of) str, optional The filters to plot. All filters if not specified. interp : bool If True, interpolate the fakes and signal counts vs threshold. Default False. Return ------ fig : matplotlib figure The figure where the plot is drawn. """ if filters is None: filters = self.filters elif isinstance(filters, str): filters = [filters] figname = 'temps1.Simulation.plot_filter_performance' fig, ax = plt.subplots(num=figname, clear=True) ax.set_xlabel('Rate of S1 candidates in DCR [s$^{-1}$]') ax.set_ylabel('S1 detection efficiency') for i, fname in enumerate(filters): for k in ['all']: e, r = self.efficiency_vs_rate(fname, k, raw=True, interp=interp) kw = dict(self.plotkw[k]) kw.update(color=f'C{i}', label=fname + ' filter, ' + kw['label']) sel = r != 0 ax.plot(r[sel], e[sel], **kw) textbox.textbox(ax, self.infotext(), fontsize='small', loc='center right') ax.legend(loc='lower right', fontsize='small') ax.minorticks_on() ax.set_xscale('log') ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() return fig
def plot_filter_output_histogram(self, fname=None): fname = self._fname(fname) figname = 'temps1.Simulation.plot_filter_output_histogram.' figname += fname.replace(' ', '_') fig, ax = plt.subplots(num=figname, clear=True) axr = ax.twinx() ax.set_title(fname.capitalize() + ' filter output distribution') ax.set_xlabel('Filter output value') ax.set_ylabel('Rate per bin [s$^{-1}$]') axr.set_ylabel('Fraction of S1 per bin [%]') x = self.values[fname]['dcr'] counts, bins = np.histogram(x, bins='auto') counts = counts / (self.nmc * self.T_sim * 1e-9) linenoise, = plot_histogram(ax, counts, bins, **self.plotkw['dcr']) x = self.values[fname]['s1'][self.signal[fname]['s1']] counts, bins = np.histogram(x, bins='auto') counts = counts * 100 / len(x) linesigpure, = plot_histogram(axr, counts, bins, **self.plotkw['s1']) N = len(x) x = self.values[fname]['all'][self.signal[fname]['all']] counts, bins = np.histogram(x, bins='auto') counts = counts * 100 / N linesig, = plot_histogram(axr, counts, bins, **self.plotkw['all']) textbox.textbox(axr, self.infotext(), loc='upper right') axr.legend([ linenoise, linesigpure, linesig, ], [ 'Fake rate (left scale)', 'Signal % (right scale)', 'Signal within noise (relative)', ], loc='upper left') ax.minorticks_on() axr.minorticks_on() aligntwin.alignYaxes([ax, axr], [0, 0]) ax.set_ylim(0, ax.get_ylim()[1]) axr.set_ylim(0, axr.get_ylim()[1]) ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() return fig
def singleplot(idcr, ivl, inphotons, filter): fig, axs = plt.subplots(3, 1, num='temps1series0227.singleplot', clear=True, figsize=[6.4, 7.19]) axs[0].set_title('Fake rate vs. threshold') axs[1].set_title('Efficiency vs. threshold') axs[2].set_title('Efficiency vs. fake rate') entry = table[idcr, ivl, inphotons] params = entry['parameters'] info = f"""\ DCR={params["DCR"] * 1e9:.3g} cps/pdm S1 {'ER' if params['VL'] < 1 else 'NR'} {params["nphotons"]} p.e. {filter}""" if filter == 'cross correlation': info += f', $\\sigma$ = {params["sigma"]} ns' textbox.textbox(axs[0], info, fontsize='medium', loc='upper right') filt = entry['filters'][filter] trimmedplot(axs[0], entry['threshold'], filt['ratethr']) axs[0].axhline(rate, color='black', linestyle=':') axs[0].set_yscale('log') trimmedplot(axs[1], entry['threshold'], filt['effthr']) trimmedplot(axs[2], entry['rate'], filt['efficiency'], label='interp.', color='#f55') trimmedplot(axs[2], entry['rate'], filt['efficiencynointerp'], label='nointerp.', color='#000', linestyle='--') axs[2].axvline(rate, color='black', linestyle=':') axs[2].set_xscale('log') axs[2].legend() for ax in axs: ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() fig.show() return fig
def plotdist(self): """ Plot some distributions relevant to the problem. Return ------ fig : matplotlib figure The figure where the plot is drawn. """ fig, axs = plt.subplots(2, 2, num='testccfilter.TestCCFilter.plotdist', clear=True, figsize=[8, 7], sharex='col') axs[0, 0].set_ylabel('Missing height to peak') axs[1, 0].set_ylabel('Counts per bin [arb. un.]') axs[1, 0].set_xlabel('Time from peak to closest neighbor') axs[0, 1].set_ylabel('Peak height') axs[1, 1].set_ylabel('Counts per bin [arb. un.]') axs[1, 1].set_xlabel('Missing height to peak') selkw = [(~self.s1, dict(label='noise')), (self.s1, dict(label='signal'))] for sel, kw in selkw: time = self.thit[sel] - self.tpeak[sel] height = self.hpeak[sel] missing = height - self.interp(self.thit[sel]) axs[0, 0].plot(time, missing, '.', **kw) hist(axs[1, 0], time, **kw) axs[0, 1].plot(missing, height, '.', **kw) hist(axs[1, 1], missing, **kw) textbox.textbox(axs[1, 0], self.info, loc='upper left', fontsize='x-small') for ax in axs.reshape(-1): if ax.is_last_col(): ax.legend(loc='upper right', fontsize='medium') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() return fig
def plot_filter_performance_threshold(self, fname=None): fname = self._fname(fname) figname = 'temps1.Simulation.plot_filter_performance_threshold.' + fname.replace( " ", "_") fig, axs = plt.subplots(2, 1, num=figname, figsize=[6.4, 7.19], clear=True, sharex=True) axs[0].set_title(f'{fname.capitalize()} filter detection performance') ax = axs[0] ax.set_ylabel('Rate of S1 candidates [s$^{-1}$]') for k in ['all', 'dcr', 's1']: f, t = self.candidates_above_threshold(fname, k, rate=True) x = np.concatenate([t, t[-1:]]) y = np.concatenate([f(t), [0]]) ax.plot(x, y, drawstyle='steps-pre', **self.plotkw[k]) rate1 = 1 / (self.T_target * 1e-9) ax.axhspan(0, rate1, color='#ddd', label='$\\leq$ 1 cand. per event') ax.set_yscale('log') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax.legend(loc='upper right') ax = axs[1] ax.set_ylabel('True S1 detection probability') ax.set_xlabel('Threshold on filter output') for k in ['all', 's1']: f, t = self.candidates_above_threshold(fname, k, signalonly=True) x = np.concatenate([t, t[-1:]]) y = np.concatenate([f(t), [0]]) ax.plot(x, y, drawstyle='steps-pre', **self.plotkw[k]) textbox.textbox(ax, self.infotext()) ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax.set_ylim(0, max(1, np.max(y))) fig.tight_layout() return fig
def __init__(self, mytab): self.myout = textbox.textbox(mytab, 0, 0) self.myout.readonly(True) mytab.columnconfigure(0, weight=1) mytab.rowconfigure(0, weight=1) clearbutton = Button(mytab, text="Clear", command=self.myout.clear) clearbutton.grid(row=2, column=0, sticky=(E,W))
def __init__(self, mytab, reportTab, mydata): self.myUDF = mytab self.data = mydata self.reportTab = reportTab self.lbox = Listbox(mytab, height=5, selectmode='extended', name="list")#, exportselection=0) self.lbox.my_name = "list" self.lbox.bind('<<ListboxSelect>>',self.curselect) self.s = Scrollbar(mytab, orient=VERTICAL, command=self.lbox.yview) self.lbox.grid(column=0, rowspan=5, columnspan=4, sticky=(N,S,E,W)) self.s.grid(column=5, row=0, rowspan=5, sticky=(N,S)) delmergebtn = ttk.Button(mytab, text="Delete Merge", command= lambda: self.removeUDFS(self.mergedbox)) delmergebtn.grid(column=0, row=6, sticky=(N,S,E,W)) self.mergedUDF = textbox.textbox(mytab, 1, 6, 1,1) self.mergedUDF.readonly(False) mergebtn = ttk.Button(mytab, text="Merge", command= lambda: self.moveUDFSlist(self.lbox, self.mergedbox, self.mergedUDF)) mergebtn.grid(column=2, row=6, sticky=(N,S,E,W)) self.mergedbox = Listbox(mytab, height=5, selectmode='extended', name="merge") self.mergedbox.my_name = "merge" self.mergedbox.bind('<<ListboxSelect>>',self.curselect) self.smerged = Scrollbar(mytab, orient=VERTICAL, command=self.mergedbox.yview) self.mergedbox.grid(column=0, row=7, rowspan=5, columnspan=4, sticky=(N,S,E,W)) self.smerged.grid(column=5, row=7, rowspan=5, sticky=(N,S)) delgroupbtn = ttk.Button(mytab, text="Delete Group", command= lambda: self.removeUDFS(self.groupedbox)) delgroupbtn.grid(column=0, row=13, sticky=(N,S,E,W)) self.groupedUDF = textbox.textbox(mytab, 1, 13, 1,1) self.groupedUDF.readonly(False) groupbtn = ttk.Button(mytab, text="Group", command= lambda: self.moveUDFSlist(self.mergedbox, self.groupedbox, self.groupedUDF)) groupbtn.grid(column=2, row=13, sticky=(N,S,E,W)) self.groupedbox = Listbox(mytab, height=5, selectmode='extended', name="group") self.groupedbox.my_name = "group" self.groupedbox.bind('<<ListboxSelect>>',self.curselect) self.sgrouped = Scrollbar(mytab, orient=VERTICAL, command=self.groupedbox.yview) self.groupedbox.grid(column=0, row=14, rowspan=5, columnspan=4, sticky=(N,S,E,W)) self.sgrouped.grid(column=5, row=14, rowspan=5, sticky=(N,S)) mytab.columnconfigure(0, weight=1) mytab.columnconfigure(1, weight=1) mytab.columnconfigure(2, weight=1) mytab.columnconfigure(3, weight=1) mytab.rowconfigure(0, weight=1) mytab.rowconfigure(7, weight=1)
def newmeth(self, *args, **kw): # TODO this should return the list of figures even when passed axes # maybe figs = [] for i, param in enumerate(figparams): fig = kw.get(param, None) if fig is None: title = meth.__qualname__ if len(figparams) > 1: title += str(i + 1) fig = plt.figure(num=title, clear=True) figs.append(fig) kw[param] = fig vovloc = kw.pop('vovloc', 'lower center') rt = meth(self, *args, **kw) for fig in figs: if hasattr(fig, 'get_axes'): ax, = fig.get_axes() else: ax = fig fig = ax.get_figure() if 'event' not in fig.canvas.get_window_title() and kw.get( 'selection', True): b, t = ax.get_ylim() yscale = ax.get_yscale() if yscale == 'log': b = np.log(b) t = np.log(t) t += (t - b) / 9 if yscale == 'log': b = np.exp(b) t = np.exp(t) ax.set_ylim(b, t) fig.tight_layout() textbox.textbox(ax, f'{self.vov} VoV', fontsize='medium', loc=vovloc) return (fig if len(figparams) == 1 else tuple(figs)) if rt is None else rt
def __init__(self, mytab, maindata): self.mydata = maindata #mytab widgets labelsframe = Frame(mytab) reportsframe = Frame(mytab) button = ttk.Button(mytab, text='Zeh Button', command=lambda: self.printreports()) self.pb2 = ttk.Progressbar(mytab, length=100, mode='determinate') dateframe = Frame(mytab) #Labelframe title = tkFont.Font(size=16, underline=1, weight="bold") reportname = ttk.Label(labelsframe, text="Report", font=title) reportops = ttk.Label(labelsframe, text="Report Options", font=title) reportout = ttk.Label(labelsframe, text="Output", font=title) reportname.grid(column=0, row=0) reportops.grid(column=1, row=0) reportout.grid(column=2, row=0) labelsframe.grid(column=0, row=0, sticky=(N, W), pady=(0, 10)) labelsframe.columnconfigure(0, minsize=100) labelsframe.columnconfigure(1, minsize=150) labelsframe.columnconfigure(2, minsize=300) #reportframe counter = 0 self.reports = {} for myreport in data.getrunnablereports("All"): self.reports[myreport] = rrow.reportrow( reportsframe, myreport, 0, counter, data.getreportoptions(myreport), data.getoutputs(myreport)) counter += 1 reportsframe.grid(column=0, row=1, sticky=(N, W), padx=(10, 0)) #button button.grid(column=0, row=2, sticky=(N, W), padx=(10, 0)) self.pb2.grid(column=0, row=3, sticky=(E, W), padx=(10, 10)) self.update("Describe") #dateframe dateframe.grid(column=0, row=4, sticky=(W), padx=(10, 0)) yearlbl = ttk.Label(dateframe, text="Year", width=10) weeklbl = ttk.Label(dateframe, text="Week", width=10) self.year = Text(dateframe, width=10, height=1) self.week = Text(dateframe, width=10, height=1) self.calendar = textbox.textbox(dateframe, 0, 3, 1, 40) self.calendar.readonly(True) datebutton = ttk.Button(dateframe, text='translate week number', command=lambda: self.transweek()) yearlbl.grid(column=0, row=0, sticky=(W)) weeklbl.grid(column=0, row=1, sticky=(W)) self.year.grid(column=1, row=0, sticky=(W)) self.week.grid(column=1, row=1, sticky=(W)) datebutton.grid(column=0, row=2, sticky=(W))
def check_ps2(p1=0.1, tau1=11, tau2=3200, T=15000, sigma=1000): """ Plot ps2 and ps2gauss. """ fig, ax = plt.subplots(num='ps12.check_ps2', clear=True) ax.set_title('Time distribution of S2 photons') ax.set_xlabel('Time [ns]') ax.set_ylabel('Probability density [arb. un.]') t = np.linspace(-3 * sigma, T + 3 * tau2, 10000) y = ps2(t, p1, tau1, tau2, T) yc = ps2gauss(t, p1, tau1, tau2, T, sigma) tg = np.linspace(-3 * sigma, 3 * sigma) yg = pgauss(tg, sigma) mx = ps2gaussmax(p1, tau1, tau2, T, sigma) my = ps2gauss(mx, p1, tau1, tau2, T, sigma) ax.plot(t, y / np.max(y), label='S2') ax.plot(tg, yg / np.max(yg), label='diffusion') ax.plot(t, yc / np.max(y), label='S2 + diffusion') ax.plot(mx, my / np.max(y), 'xk', label='maximum') textbox.textbox(ax, f"""\ $p_1$ = {p1} $\\tau_1$ = {tau1} ns $\\tau_2$ = {tau2} ns $T$ = {T} ns $\\sigma$ = {sigma} ns""", fontsize='medium', loc='lower center') ax.legend(loc='upper right') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() fig.show() return fig
def __init__(self, mytab, maindata): self.mydata = maindata #mytab widgets labelsframe = Frame(mytab) reportsframe = Frame(mytab) button = ttk.Button(mytab, text='Zeh Button', command=lambda: self.printreports()) self.pb2 = ttk.Progressbar(mytab, length=100, mode='determinate') dateframe = Frame(mytab) #Labelframe title = tkFont.Font(size=16, underline=1, weight="bold") reportname = ttk.Label(labelsframe, text="Report", font=title) reportops = ttk.Label(labelsframe, text="Report Options", font=title) reportout = ttk.Label(labelsframe, text="Output", font=title) reportname.grid(column=0, row=0) reportops.grid(column=1, row=0) reportout.grid(column=2, row=0) labelsframe.grid(column=0, row=0, sticky=(N,W), pady=(0,10)) labelsframe.columnconfigure(0, minsize = 100) labelsframe.columnconfigure(1, minsize = 150) labelsframe.columnconfigure(2, minsize = 300) #reportframe counter = 0 self.reports = {} for myreport in data.getrunnablereports("All"): self.reports[myreport] = rrow.reportrow(reportsframe, myreport, 0, counter, data.getreportoptions(myreport), data.getoutputs(myreport)) counter += 1 reportsframe.grid(column=0, row=1, sticky=(N,W), padx=(10,0)) #button button.grid(column=0, row=2, sticky=(N,W), padx=(10,0)) self.pb2.grid(column=0, row=3, sticky=(E,W),padx=(10,10)) self.update("Describe") #dateframe dateframe.grid(column=0, row=4, sticky=(W), padx=(10,0)) yearlbl = ttk.Label(dateframe, text="Year", width=10) weeklbl = ttk.Label(dateframe, text="Week", width=10) self.year = Text(dateframe, width=10, height=1) self.week = Text(dateframe, width=10, height=1) self.calendar = textbox.textbox(dateframe, 0, 3, 1, 40) self.calendar.readonly(True) datebutton = ttk.Button(dateframe, text='translate week number', command=lambda: self.transweek()) yearlbl.grid(column=0, row=0, sticky=(W)) weeklbl.grid(column=0, row=1, sticky=(W)) self.year.grid(column=1, row=0, sticky=(W)) self.week.grid(column=1, row=1, sticky=(W)) datebutton.grid(column=0, row=2, sticky=(W))
def plot_filter_performance(self, filters=None): if filters is None: filters = self.filters elif isinstance(filters, str): filters = [filters] figname = 'temps1.Simulation.plot_filter_performance' fig, ax = plt.subplots(num=figname, clear=True) ax.set_title(f'Filter detection performance') ax.set_xlabel('Rate of S1 candidates in DC photons [s$^{-1}$]') ax.set_ylabel('S1 loss probability') prop_cycle = plt.rcParams['axes.prop_cycle'] colors = prop_cycle.by_key()['color'] for fname, color in zip(filters, colors): for k in ['all', 's1']: f, r = self.efficiency_vs_rate(fname, k) kw = dict(self.plotkw[k]) kw.update(color=color, label=fname.capitalize() + ' filter, ' + kw['label']) ax.plot(r, 1 - f(r), **kw) textbox.textbox(ax, self.infotext(), loc='lower left') ax.legend(loc='upper right', fontsize='small') ax.minorticks_on() ax.set_xscale('log') ax.set_yscale('log') ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') autolinscale(ax) fig.tight_layout() return fig
for ifig, fax in enumerate(axs): if ifig == 3: legendtitle = 'Nphotons' else: legendtitle = 'Template $\\sigma$ [ns]' fax[0, 0].legend(loc='best', fontsize='small', ncol=2, title=legendtitle) params = table[idcr, 0, inphotons, 0]['parameters'] info = f"""\ DCR = {params['DCR'] * 1e9:.3g} cps/pdm tres = 10 ns nevents = 1000""" if ifig != 3: info = f"nphotons = {params['nphotons']}\n" + info infoheight = 'lower' if ifig in [2, 3] else 'upper' textbox.textbox(fax[0, 1], info, loc=f'{infoheight} right', fontsize='small') if ifig == 1: fax[0, 0].set_yscale('log') if ifig == 2: fax[0, 0].set_xscale('log') for fig in figs: fig.tight_layout() fig.show()
def plot_filter_output_histogram(self, fname=None): """ Plot the histogram of the filter peak value of S1 candidates for noise and signal. Parameters ---------- fname : str, optional The filter. Optional if there's only one filter. Return ------ fig : matplotlib figure The figure where the plot is drawn. """ fname = self._fname(fname) figname = 'temps1.Simulation.plot_filter_output_histogram.' figname += fname.replace(' ', '_') fig, ax = plt.subplots(num=figname, clear=True) axr = ax.twinx() ax.set_title(fname.capitalize() + ' filter output distribution') ax.set_xlabel('Filter output value') ax.set_ylabel('Rate per bin [s$^{-1}$]') axr.set_ylabel('Fraction of S1 per bin [%]') x = self.values[fname]['dcr'] counts, bins = np.histogram(x, bins='auto') counts = counts / (self.nmc * self.T * 1e-9) linenoise, = plot_histogram(ax, counts, bins, **self.plotkw['dcr']) x = self.values[fname]['all'][self.signal[fname]['all']] counts, bins = np.histogram(x, bins='auto') counts = counts * 100 / len(x) linesig, = plot_histogram(axr, counts, bins, **self.plotkw['all']) x = self.values[fname]['s1'][self.signal[fname]['s1']] counts, bins = np.histogram(x, bins='auto') counts = counts * 100 / len(x) linesigpure, = plot_histogram(axr, counts, bins, **self.plotkw['s1']) textbox.textbox(axr, self.infotext(), loc='upper right', fontsize='small') axr.legend([ linenoise, linesig, linesigpure, ], [ 'Fake rate (left scale)', 'Signal % (right scale)', 'Signal without noise', ], loc='upper left') ax.minorticks_on() axr.minorticks_on() aligntwin.alignYaxes([ax, axr], [0, 0]) ax.set_ylim(0, ax.get_ylim()[1]) axr.set_ylim(0, axr.get_ylim()[1]) ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() return fig
def addTextBox(self): # Put into the middle pane pane = self.panes[1] size = [self.height, self.width] textbox.textbox(self.dataset, pane, size)
def plot_filter_performance_threshold(self, fname=None, interp=False): """ Plot filter fake rate and efficiency vs threshold. Parameters ---------- fname : str, optional The filter. Optional if there's only one filter. interp : bool If False (default), count the candidates above threshold. If True, do a linear interpolation of the number of candidates. Return ------ fig : matplotlib figure The figure where the plot is drawn. """ fname = self._fname(fname) figname = 'temps1.Simulation.plot_filter_performance_threshold.' + fname.replace( " ", "_") fig, axs = plt.subplots(2, 1, num=figname, figsize=[6.4, 7.19], clear=True, sharex=True) ax = axs[0] ax.set_ylabel('Rate of S1 candidates [s$^{-1}$]') for k in ['all', 'dcr', 's1']: f, t = self.candidates_above_threshold(fname, k, rate=True, linear=interp) if interp: ax.plot(t, f(t), **self.plotkw[k]) else: x = np.concatenate([t, t[-1:]]) y = np.concatenate([f(t), [0]]) ax.plot(x, y, drawstyle='steps-pre', **self.plotkw[k]) if k == 'dcr' and fname.startswith('coinc'): tcoinc = self.tcoinc if len(fname) == 5 else float(fname[5:]) thr = np.linspace(np.min(t), np.max(t), 1000) rth = coincth.coincrate(mincount=thr, tcoinc=tcoinc, rate=self.DCR * self.npdm) rth = coincth.deadtimerate(rate=rth, deadtime=self.deadradius, restartable=False) rth *= 1e9 # ns^-1 -> s^-1 kw = dict(self.plotkw[k]) kw.update(label=kw['label'] + ' (theory)', alpha=0.3, linestyle='-') ax.plot(thr, rth, **kw) rate1 = 1 / (self.T * 1e-9) ax.axhspan(0, rate1, color='#ddd', label='$\\leq$ 1 cand. per event') ax.set_yscale('log') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax.legend(loc='upper right', title=fname + ' filter') ax = axs[1] ax.set_ylabel('S1 detection efficiency') ax.set_xlabel('Threshold on filter output') for k in ['all', 's1']: f, t = self.candidates_above_threshold(fname, k, signalonly=True) x = np.concatenate([t, t[-1:]]) y = np.concatenate([f(t), [0]]) ax.plot(x, y, drawstyle='steps-pre', **self.plotkw[k]) textbox.textbox(ax, self.infotext(), fontsize='small') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax.set_ylim(0, max(1, np.max(y))) fig.tight_layout() return fig
def infobox(ax, **kw): kwargs = dict(fontsize='medium', loc='lower left', bbox=dict(alpha=0.95)) kwargs.update(kw) textbox.textbox(ax, os.path.split(source)[1], **kwargs)
num='figwindowtempres', clear=True, sharex=True, sharey='row', gridspec_kw=dict(height_ratios=[2, 1]), figsize=[8.18, 10]) for i, n in enumerate(names): for j, center in enumerate([1, 2]): ax = axs[i, j] sim[n].plot_loc_window(itau=itau(384), icenter=center, logscale=False, ax=ax) textbox.textbox(ax, nicenames[n] + ' noise', fontsize='medium', loc='lower left') for ax in axs.reshape(-1): ax.set_title(None) if ax.is_last_row(): ax.set_xlabel('SNR (before filtering)') if ax.is_first_col(): ax.set_ylabel('Temporal resolution [ns]') lims = ax.get_ylim() ax.set_ylim(0, lims[1]) if ax.is_first_row() and ax.is_first_col(): ax.legend(fontsize='medium', title='Window [samples]\n$-$L+R of center', title_fontsize='small', loc='center right')
from matplotlib import pyplot as plt import figlatex import afterpulse_tile21 import textbox for i, vov in enumerate(afterpulse_tile21.AfterPulseTile21.defaultparams): fig = plt.figure(num=f'figbaseline2-{i}', clear=True, figsize=[6.4, 3]) ap21 = afterpulse_tile21.AfterPulseTile21(vov) ap21.sim.hist('baseline', yscale='log', fig=fig) ax, = fig.get_axes() textbox.textbox(ax, f'{vov} VoV', fontsize='medium', loc='lower center') ax.set_xlabel('Baseline [ADC digit]') fig.tight_layout() fig.show() figlatex.save(fig)
def fithistogram( sim, expr, condexpr, prior, pmf_or_cdf, bins='auto', bins_overflow=None, continuous=False, fig=None, errorfactor=None, mincount=3, selection=True, boxloc='center right', fitlabel=None, **kw, ): """ Fit an histogram. Parameters ---------- sim : AfterPulse expr : str condexpr : str The sample is sim.getexpr(expr, condexpr). prior : (list of) array/dictionary of GVar Prior for the fit. If `prior` and `pmf_or_cdf` are lists, a fit is done for each pair in order. pmf_or_cdf : (list of) function The signature must be `pmf_or_cdf(x, params)` where `params` has the same format of `prior`. bins : int, sequence, str Passed to np.histogram. Default 'auto'. bins_overflow : sequence of two elements If None, do not fit the overflow. It is assumed that all the probability mass outside of the bins is contained in the overflow bin. The overflow bin must be to the right of the other bins. continuous : bool If False (default), pmf_or_cdf must be the probability distribution of an integer variable. If True, pmf_or_cdf must compute the cumulative density up to the given point. fig : matplotlib figure or axis, optional If provided, the plot is drawn here. errorfactor : 1D array, optional If provided, the errors on the bin counts are multiplied by these factors. If the array has different length than the number of bins, the factors are applied starting from the first element. mincount : int Bins are grouped starting from the last bin until there at least `mincount` elements in the last bin. (Applies to the overflow if present.) selection : bool If True (default), write `condexpr` on the plot. boxloc : str The location of the text box with the fit information. Default 'center right'. fitlabel : (list of) str, optional Fit names used in the legend and text box. **kw : Additional keyword arguments are passed to lsqfit.nonlinear_fit. Return ------ fit : (list of) lsqfit.nonlinear_fit fig : matplotlib figure """ onefit = not hasattr(pmf_or_cdf, '__len__') if onefit: prior = [prior] pmf_or_cdf = [pmf_or_cdf] if fitlabel is not None: fitlabel = [fitlabel] # histogram sample = sim.getexpr(expr, condexpr) counts, bins = np.histogram(sample, bins) hasoverflow = bins_overflow is not None if hasoverflow: (overflow, ), _ = np.histogram(sample, bins_overflow) else: overflow = 0 if hasoverflow: # add bins to the overflow bin until it has at least `mincount` counts lencounts = len(counts) for i in range(len(counts) - 1, -1, -1): if overflow < mincount: overflow += counts[i] lencounts -= 1 else: break counts = counts[:lencounts] bins = bins[:lencounts + 1] else: # group last bins until there are at least `mincount` counts while len(counts) > 1: if counts[-1] < mincount: counts[-2] += counts[-1] counts = counts[:-1] bins[-2] = bins[-1] bins = bins[:-1] else: break # check total count norm = np.sum(counts) + overflow assert norm == sim.getexpr(f'count_nonzero({condexpr})') # prepare data for fit ucounts = upoisson(counts) if errorfactor is not None: errorfactor = np.asarray(errorfactor) assert errorfactor.ndim == 1, errorfactor.ndim end = min(len(errorfactor), len(ucounts)) ucounts[:end] = scalesdev(ucounts[:end], errorfactor[:end]) y = dict(bins=ucounts) if hasoverflow: y.update(overflow=upoisson(overflow)) # fit x = [] fit = [] for ifit in range(len(prior)): x.append( dict( pmf_or_cdf=pmf_or_cdf[ifit], continuous=continuous, bins=bins, norm=norm, hasoverflow=hasoverflow, )) fit.append(lsqfit.nonlinear_fit((x[ifit], y), fcn, prior[ifit], **kw)) # get figure if hasattr(fig, 'get_axes'): ax = fig.subplots() else: ax = fig fig = ax.get_figure() # plot data center = (bins[1:] + bins[:-1]) / 2 wbar = np.diff(bins) / 2 kw = dict(linestyle='', capsize=4, marker='.', color='k') uerrorbar(ax, center, y['bins'], xerr=wbar, label='histogram', **kw) if hasoverflow: oc = center[-1] + 2 * wbar[-1] ys = y['overflow'] uerrorbar(ax, oc, ys, label='overflow', **kw) # plot fit info = [f'N = {norm}'] styles = [ dict(color='#0004'), dict(color='#f004'), ] for ifit, style in zip(range(len(prior)), itertools.cycle(styles)): thisfit = fit[ifit] yfit = fcn(x[ifit], thisfit.palt) ys = yfit['bins'] ym = np.repeat(gvar.mean(ys), 2) ysdev = np.repeat(gvar.sdev(ys), 2) xs = np.concatenate([bins[:1], np.repeat(bins[1:-1], 2), bins[-1:]]) label = fitlabel[ ifit] if fitlabel is not None else 'fit' if ifit == 0 else f'fit {ifit + 1}' style.update(zorder=1.9) ax.fill_between(xs, ym - ysdev, ym + ysdev, label=label, **style) if hasoverflow: ys = yfit['overflow'] ym = np.full(2, gvar.mean(ys)) ysdev = np.full(2, gvar.sdev(ys)) xs = oc + 0.8 * (bins[-2:] - center[-1]) ax.fill_between(xs, ym - ysdev, ym + ysdev, **style) # write fit results on the plot if fitlabel is not None or ifit > 0: space = 9 * ' ' label = fitlabel[ ifit] if fitlabel is not None else f'Fit {ifit + 1}:' info.append(space + label + space) info.append( f'chi2/dof (pv) = {thisfit.chi2/thisfit.dof:.2g} ({thisfit.Q:.2g})' ) p = thisfit.palt for k, v in p.items(): m = p.extension_pattern.match(k) if m: f = p.extension_fcn.get(m.group(1), None) if f: k = m.group(2) v = f(v) if hasattr(v, '__len__'): for i, vv in enumerate(v): info.append(f'{k}{i+1} = {vv}') else: info.append(f'{k} = {v}') textbox.textbox(ax, '\n'.join(info), loc=boxloc, fontsize='small') # decorations ax.legend(loc='upper right') ax.minorticks_on() ax.grid(which='major', linestyle='--') ax.grid(which='minor', linestyle=':') ax.set_xlabel(expr) ax.set_ylabel('Count per bin') if selection: cond = breaklines.breaklines(f'Selection: {condexpr}', 40, ')', '&|') textbox.textbox(ax, cond, loc='upper left', fontsize='small') fig.tight_layout() _, upper = ax.get_ylim() ax.set_ylim(0, upper) if onefit: fit, = fit return fit, fig
filt = toy.Filter(signal, signal[0, 0]) fsignal = filt.all(templ)[:, 0] fig, ax = plt.subplots(num='plotevent', clear=True) ax.plot(fsignal[0], color='#f55', linewidth=1, label=toy.Filter.name(0)) for i in range(3): ax.plot(fsignal[i + 1], color='black', linestyle=[':', '--', '-'][i], label=toy.Filter.name(i + 1)) textbox.textbox( ax, f'filter length = {args.length} Sa ({args.length * timebase} ns)', loc='lower right', fontsize='small') ax.legend(loc='best') ax.set_title(f'{args.filespec}, event {args.event}') ax.set_xlabel(f'Sample number @ {num2si.num2si(freq)}Sa/s') ax.set_ylabel('ADC scale') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() fig.show()
import colormap length = [128, 64, 64] ################ figs = [] for j, (vov, flen) in enumerate(zip(afterpulse_tile21.AfterPulseTile21.defaultparams, length)): ap21 = afterpulse_tile21.AfterPulseTile21(vov) fig = plt.figure(num=f'figlaserpos2-{j}0', clear=True, figsize=[4.5, 3.5]) ap21.sim.hist('mainpos-offset', 'mainnpe==1', fig=fig, selection=False) ax, = fig.get_axes() textbox.textbox(ax, f'{vov} VoV', fontsize='medium', loc='lower center') ax.set_xlabel('Laser peak position [ns]') row = [fig] fig = plt.figure(num=f'figlaserpos2-{j}1', clear=True, figsize=[4.5, 3.5]) ap21.sim.hist2d('mainpos-offset', 'mainampl', f'(mainnpe==1)&(length=={flen})', fig=fig, cmap=colormap.uniform(), selection=False) ax, _ = fig.get_axes() textbox.textbox(ax, f'{vov} VoV', fontsize='medium', loc='lower center') textbox.textbox(ax, f'{flen} ns filter', fontsize='medium', loc='upper left') ax.set_xlabel('Laser peak position [ns]') ax.set_ylabel('Peak height') row.append(fig)
ax.minorticks_on() ax.grid(True, 'major', linestyle='--') ax.grid(True, 'minor', linestyle=':') info = f"""\ first {nevents} events sampling frequency {num2si.num2si(freq)}Sa/s samples/event {nsamples} effective samples/event {effnsamples} moving average {nsamp} ({nsamp / freq * 1e6:.2g} μs) difference delay {nsamp} ({nsamp / freq * 1e6:.2g} μs) dead time {nsamp} ({nsamp / freq * 1e6:.2g} μs) filter output sdev {sdev:.2g} veto if any sample < {veto} (vetoed {len(data) - nevents})""" textbox.textbox(ax, info, fontsize='small', loc='upper left') fig.tight_layout() fig.show() # def covariance(x, y, axis=-1): # mx = x - np.mean(x, axis=axis, keepdims=True) # my = y - np.mean(y, axis=axis, keepdims=True) # return np.mean(mx * my, axis=axis) # # def autocov20(x): # x0 = x[..., 1:-1] # x2 = x[..., 2:] + x[..., :-2] - 2 * x0 # return covariance(x0, x2)
ax.minorticks_on() ax.grid(True, 'major', linestyle='--') ax.grid(True, 'minor', linestyle=':') k2 = uncertainties.ufloat(k2, errk2) sdev = uncertainties.ufloat(sdev, errsdev) info = f"""\ {nevents} events ({nevents * nsamples / freq * 1e3:.0f} ms) sampling frequency {num2si.num2si(freq)}Sa/s samples/event {nsamples} ({nsamples / freq * 1e6:.0f} µs) effective samples/event {effnsamples} ({effnsamples / freq * 1e6:.0f} µs) moving average {nsamp} Sa ({nsamp / freq * 1e6:.1f} μs) difference delay {nsamp} Sa ({nsamp / freq * 1e6:.1f} μs) dead time {nsamp} Sa ({nsamp / freq * 1e6:.1f} μs) σ = {sdev:S} k2 = –{-k2:S} veto if any sample < {veto} (vetoed {vetocount})""" textbox.textbox(ax, info, fontsize='small', loc='lower center', bbox=dict(alpha=0.8)) fig.tight_layout() fig.show() figlatex.save(fig)
import afterpulse_tile21 import textbox vov = 5.5 low = 955 high = 956 ################ ap21 = afterpulse_tile21.AfterPulseTile21(vov) datalist = ap21.datalist events = ap21.sim.eventswhere(f'(baseline >= {low}) & (baseline <= {high})') assert len(events) >= 2, len(events) figs = [] for i, ievt in enumerate(events[:2]): fig = plt.figure(num=f'figbstail-{i}', clear=True, figsize=[4.5, 3]) ap21.sim.plotevent(datalist, ievt, 2, zoom='all', fig=fig) ax, = fig.get_axes() ax.legend(loc='lower left', fontsize='x-small') textbox.textbox(ax, f'{vov} VoV', fontsize='medium', loc='lower right') fig.tight_layout() fig.show() figs.append(fig) figlatex.save([figs])
def plot_temporal_distribution(self, fname=None): fname = self._fname(fname) figname = 'temps1.Simulation.plot_temporal_distribution.' + fname.replace( " ", "_") fig, axs = plt.subplots(2, 1, num=figname, clear=True, figsize=[6.4, 7.19]) axs[0].set_title( f'{fname.capitalize()} filter\nTemporal distribution of S1 candidates' ) ax = axs[0] ax.set_xlabel('Time relative to true S1 location [ns]') ax.set_ylabel('Inverse of neighbor temporal gap [ns$^{-1}$]') for k in ['all', 'dcr']: time = self.times[fname][k] time = np.sort(time) ddecdf = 1 / np.diff(time) x = time - self.s1loc y = np.concatenate([ddecdf, ddecdf[-1:]]) ax.plot(x, y, drawstyle='steps-post', **self.plotkw[k]) ax.axvspan(-self.deadradius, self.deadradius, color='#eee', zorder=-9, label='$\\pm$ dead radius') ax.axvspan(-self.matchdist, self.matchdist, color='#ccc', zorder=-8, label='$\\pm$ match dist.') ax.legend(loc='upper right') ax.set_xlim(3.5 * max(2 * self.matchdist, self.deadradius) * np.array([-1, 1])) ax.set_yscale('log') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') ax = axs[1] ax.set_xlabel('Time relative to true S1 location [ns]') ax.set_ylabel('Histogram bin density [ns$^{-1}$]') times1 = self.hits1.reshape(-1) - self.s1loc time = self.times[fname]['all'] - self.s1loc time_match = time[np.abs(time) < self.matchdist] idx = np.argsort(np.abs(time)) time_close = time[idx][:self.nmc] # t = np.linspace(..., ..., 1000) # ax.plot(t, pS1.p_S1_gauss(t, self.VL, self.tauV, self.tauL, self.tres), label='S1 pdf') histkw = dict(bins='auto', density=True, histtype='step', zorder=10) ax.hist(times1, label=f'S1 photons ({len(times1)})', linestyle=':', **histkw) ax.hist( time_close, label= f'{self.nmc} closest candidates ($\\sigma_q$={qsigma.qsigma(time_close):.3g})', linestyle='--', **histkw) ax.hist( time_match, label= f'matching candidates ($\\sigma_q$={qsigma.qsigma(time_match):.3g})', **histkw) ax.axvspan(0, self.deadradius, color='#eee', zorder=-9, label='dead radius') ax.axvspan(0, self.matchdist, color='#ccc', zorder=-8, label='match dist.') textbox.textbox(ax, self.infotext(), loc='upper left', zorder=11) ax.legend(loc='upper right', fontsize='small') ax.set_yscale('log') linthreshx = 10**np.ceil(np.log10(15 * qsigma.qsigma(time_match))) ax.set_xscale('symlog', linthreshx=linthreshx) ax.minorticks_on() ax.xaxis.set_minor_locator( symloglocator.MinorSymLogLocator(linthreshx)) ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() return fig
allevents = ap21.sim.eventswhere('all(mainpos < 0, axis=0)') events = gen.choice(allevents, 12, replace=False) for i, event in enumerate(events): fig = plt.figure(num=f'figverymissing-{j}{i}', clear=True, figsize=[3, 2.7]) figs.append(fig) ilen = np.searchsorted(ap21.sim.filtlengths, length) assert ap21.sim.filtlengths[ilen] == length ap21.sim.plotevent(ap21.datalist, event, ilen, zoom='main', fig=fig) ax, = fig.get_axes() ax.legend().set_visible(False) ax.set_xlabel('') textbox.textbox(ax, f'Filter {length} ns', fontsize='medium', loc='lower right') textbox.textbox(ax, f'{vov} VoV', fontsize='medium', loc='lower left') fig.tight_layout() figs = np.array(figs).reshape(4, 3) pages.append(figs) for figs in pages: figlatex.save(figs)
vov = 9.5 ievt = 59689 ################ fig, axs = plt.subplots(1, 2, num='figdectevent', clear=True, figsize=[9, 3], sharey=True, sharex=True) ap21 = afterpulse_tile21.AfterPulseTile21(vov) ilen = np.searchsorted(ap21.sim.filtlengths, ap21.params['aplength']) for ax, apampl in zip(axs, [True, False]): ap21.sim.plotevent(ap21.datalist, ievt, ilen, zoom='main', fig=ax, apampl=apampl) textbox.textbox(axs[0], f'{vov} VoV', fontsize='medium', loc='lower left') fig.tight_layout() fig.show() figlatex.save(fig)
vov = 5.5 length = 128 ################ ap21 = afterpulse_tile21.AfterPulseTile21(vov) fig = plt.figure(num='figpe', clear=True, figsize=[8, 3]) ap21.sim.hist('mainheight', f'~saturated & ~closept & (mainpos >= 0) & (length == {length})', yscale='log', fig=fig, nbins=1000, selection=False) ax, = fig.get_axes() ax.set_xlabel('Laser peak height') textbox.textbox(ax, f'{vov} VoV\nFilter {length} ns', fontsize='medium', loc='center right') ilen = np.searchsorted(ap21.sim.filtlengths, length) boundaries = ap21.sim.computenpeboundaries(ilen) afterpulse_tile21.vlines(ax, boundaries, linestyle=':') fig.tight_layout() fig.show() figlatex.save(fig)
for x in locs: s1 = ps12.ps1gauss(t - x, *params) ax.fill_between(t, np.zeros_like(s1), s1, label='$p_{\\mathrm{S1}}' + f'(t - {x})$', alpha=0.7) sel = hits > x - 3 * sigma ax.plot(hits[sel], ps12.ps1gauss(hits[sel] - x, *params), 'xk') info = f"""\ $p_{{\\mathrm{{fast}}}}$ = {p1} $\\tau_{{\\mathrm{{fast}}}}$ = {tau1} ns $\\tau_{{\\mathrm{{slow}}}}$ = {tau2} ns $\\sigma$ = {sigma} ns DCR = {rate * 1000} $\\mu$s$^{{-1}}$""" textbox.textbox(ax, info, fontsize='medium', loc='center right', bbox=dict(alpha=0.95)) ax.legend(loc='upper right') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() fig.show()
tau1 = 7 tau2 = 1600 sigma = 10 fig, ax = plt.subplots(num='slides-2021-02-16.s1pdf', clear=True) ax.set_xlabel('Time [ns]') ax.set_ylabel('Probability density [ns$^{-1}$]') t = np.linspace(-5 * sigma, tau2 / 2, 1000) s1er = ps12.ps1gauss(t, 0.25, tau1, tau2, sigma) s1nr = ps12.ps1gauss(t, 0.75, tau1, tau2, sigma) ax.plot(t, s1nr, label='NR', color='#f55') ax.plot(t, s1er, label='ER', color='black') info = f"""\ $\\tau_{{\\mathrm{{fast}}}}$ = {tau1} ns $\\tau_{{\\mathrm{{slow}}}}$ = {tau2} ns $\\sigma$ = {sigma} ns""" textbox.textbox(ax, info, fontsize='medium', loc='upper right') ax.legend(title='S1', loc='upper center') ax.minorticks_on() ax.grid(True, which='major', linestyle='--') ax.grid(True, which='minor', linestyle=':') fig.tight_layout() fig.show()
def play_mode(): pygame.init() SWidth = Settings.SWidth SHeight = Settings.SHeight pygame.font.init() myfont = pygame.font.SysFont('Garamond', int(SHeight / 30)) global done done = False pygame.mixer.music.load(track) pygame.mixer.music.play() BLACK = (0, 0, 0) WHITE = (255, 255, 255) mode = 'First' key = '' keylist = [] responselist = [] resultlist = [] wins = 0 losses = 0 winpc = 0 roundx = int(SWidth / 1.5) roundwidth = int(SWidth - roundx - 10) roundheight = int(SHeight / 5) offset = 10 winpclist = [] roundxlist = [ int(roundx + i * (roundwidth / nrounds)) for i in range(nrounds) ] graphframe = [(roundx, offset), (roundx, offset + roundheight), (roundx, offset + roundheight), (roundx + roundwidth, offset + roundheight)] graphmiddle = ((roundx, int(offset + roundheight / 2)), (roundx + roundwidth, int(offset + roundheight / 2))) graphcutoff = ((roundx + int(roundwidth * (cutoff / nrounds)) - int(2 * (roundwidth / nrounds)), offset), (roundx + int(roundwidth * (cutoff / nrounds)) - int(2 * (roundwidth / nrounds)), offset + roundheight)) newresult = False rstring = '' res = '' while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop elif event.type == pygame.MOUSEBUTTONUP: if event.button == 1: pos = pygame.mouse.get_pos() if quitbut.rect().collidepoint(pos): quitbut.function() elif homebut.rect().collidepoint(pos): homebut.function() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: key = 'rock' if event.key == pygame.K_DOWN: key = 'paper' if event.key == pygame.K_RIGHT: key = 'scissors' if not done: screen.fill(home_colour) a = 400 b = 240 screen.blit(rockmini, (120, 0)) screen.blit(papermini, (200, 0)) screen.blit(scissorsmini, (280, 0)) screen.blit(keys, (120, 80)) screen.blit(plat, (int(plat_edge * SWidth), int(plat_height * SHeight))) screen.blit(plat2, (int(SWidth - plat_edge * SWidth - redwidth), int(plat_height * SHeight))) for exp_but in explorer_group.button_list: pygame.draw.rect(screen, BLACK, exp_but.shadow(0.15)) pygame.draw.rect(screen, exp_but.colour, exp_but.rect()) exp_but.caption_print(screen) wtext = 'Wins: ' + str(wins) textbox(screen, wtext, 0.21, 0.2, 30, (SWidth, SHeight), offset=-0.44) ltext = 'Losses: ' + str(losses) textbox(screen, ltext, 0.21, 0.2, 30, (SWidth, SHeight), offset=-0.33) roundtext = 'Round ' + str(len(keylist) + 1) + '/' + str(nrounds) textbox(screen, roundtext, 0.3, 0.2, 45, (SWidth, SHeight), offset=-0.39) pygame.draw.line(screen, (200, 200, 0), graphcutoff[0], graphcutoff[1]) for dat in winpclist: pointlist = [] for i in range(len(winpclist)): pointlist.append( (roundxlist[i], int(roundheight - (roundheight * (winpclist[i] / 100))) + offset)) if len(winpclist) > 1: pygame.draw.lines(screen, (255, 0, 0), False, pointlist) pygame.draw.lines(screen, WHITE, False, graphframe) pygame.draw.line(screen, (100, 100, 100), graphmiddle[0], graphmiddle[1]) wintext = 'W:L ' + keypredict.percent_win(wins, losses) + '%' if float(keypredict.percent_win(wins, losses)) > 50: col = (0, 255, 0) else: col = (255, 0, 0) textbox(screen, wintext, (roundheight + offset + 10) / SHeight, 0.2, 30, (SWidth, SHeight), offset=0.43, colour=col) if mode == 'First': text = 'To start, use the arrow keys to enter your choice, and wait while the computer decides.' textbox(screen, text, 0.01, 0.2, 30, (SWidth, SHeight)) if len(key) > 1: keylist.append(key) mode = 'Response' key = '' elif mode == 'Response': text = 'Please wait while the computer prepares its response... Round: ' + str( len(keylist)) textbox(screen, text, 0.01, 0.2, 30, (SWidth, SHeight)) mode = 'Result' newresult = True key = '' elif mode == 'Result': if newresult == True: response = keypredict.predict(keylist) responselist.append(response) newresult = False selection = keylist[-1] prediction = responselist[-1] res = keypredict.result(selection, prediction) resultlist.append(res) if res == 'win': righteffect.stop() righteffect.play() wins += 1 resultstring = 'Nice work! ' + selection.capitalize( ) + ' beats ' + prediction.capitalize() resultstring += ', giving you the win in round ' + str( len(keylist)) elif res == 'loss': wrongeffect.stop() wrongeffect.play() losses += 1 resultstring = 'Ouch! ' + prediction.capitalize( ) + ' beats ' + selection.capitalize() resultstring += ', giving the computer the victory in round ' + str( len(keylist)) else: resultstring = 'Draw! ' + selection.capitalize( ) + ' met ' + prediction.capitalize() resultstring += ', so in round ' + str( len(keylist)) + ', no points are given.' resultstring += '. Now use the arrow keys to make your next selection.' rstring = resultstring winpclist.append( float(keypredict.percent_win(wins, losses))) if len(keylist) == nrounds: fname = 'keyruns/keyrun' + str(nrounds) + 'n' + str( len(os.listdir('keyruns'))) dump(keylist, open(fname, 'wb')) endloop = True while endloop: overtext = 'Game Over. Press any key to return to the main menu.' textbox(screen, overtext, 0.45, 0.5, 40, (SWidth, SHeight), colour=(123, 222, 255)) for event in pygame.event.get( ): # User did something if event.type == pygame.KEYDOWN: done = True endloop = False pygame.display.flip() clock.tick(60) else: if res == 'loss': pass textbox(screen, rstring, 0.01, 0.2, 30, (SWidth, SHeight)) if keylist[-1] == 'rock': screen.blit(rockmain, (int(plat_edge * SWidth), int(plat_height * SHeight) - imwidth)) if keylist[-1] == 'paper': screen.blit(papermain, (int(plat_edge * SWidth), int(plat_height * SHeight) - imwidth)) if keylist[-1] == 'scissors': screen.blit(scissorsmain, (int(plat_edge * SWidth), int(plat_height * SHeight) - imwidth)) if responselist[-1] == 'rock': screen.blit(rockmain2, (int(SWidth - plat_edge * SWidth - redwidth) + (redwidth - imwidth), int(plat_height * SHeight) - imwidth)) if responselist[-1] == 'paper': screen.blit(papermain2, (int(SWidth - plat_edge * SWidth - redwidth) + (redwidth - imwidth), int(plat_height * SHeight) - imwidth)) if responselist[-1] == 'scissors': screen.blit(scissorsmain2, (int(SWidth - plat_edge * SWidth - redwidth) + (redwidth - imwidth), int(plat_height * SHeight) - imwidth)) if res == 'win': screen.blit(tick, (int((SWidth - iconwidth) * 0.5), int((SHeight - iconwidth) * 0.5))) elif res == 'loss': # if len(resultlist) > 1 and resultlist[-2] == 'loss': # wrongeffect.stop() screen.blit(cross, (int((SWidth - iconwidth) * 0.5), int((SHeight - iconwidth) * 0.5))) else: screen.blit(equal, (int((SWidth - iconwidth) * 0.5), int((SHeight - iconwidth) * 0.5))) if len(key) > 1: keylist.append(key) mode = 'Response' key = '' #print(mode) pygame.display.flip() clock.tick(60)
def __init__(self, mytab, maindata): self.teamOfOne = IntVar() self.recombine = IntVar() self.dateFirst= IntVar() self.Eventcombine = StringVar() self.Eventcombine.set(data.getDepthLevels()[1]) self.recombine.set(1) self.dateFirst.set(1) self.newref = StringVar() self.data = maindata #mytab widgets checkframe = Frame(mytab) refframe = Frame(mytab) sliderframe = Frame(mytab) #checkframe widgets self.CteamOfOne = ttk.Checkbutton(checkframe, text="Count people in Teams of 1 as individuals?", variable = self.teamOfOne, onvalue = 1, offvalue = 0, command=lambda: self.TeamOneIndividual()) self.CteamRecombine = ttk.Checkbutton(checkframe, text="Recombine team donations?", variable = self.recombine, onvalue = 1, offvalue = 0, command=lambda: self.TeamRecombine()) self.CdateFirst = ttk.Checkbutton(checkframe, text="Is day first (DD/MM/YYYY)", variable = self.dateFirst, onvalue = 1, offvalue = 0, command=lambda: self.SetDateFirst()) depthlbl = ttk.Label(checkframe, text="Depth for groupby?") foo = data.getDepthLevels() self.CEventRecombine = ttk.OptionMenu(checkframe, self.Eventcombine, foo[1], *foo, command=self.EventRecombine) #self.CEventRecombine = ttk.Checkbutton(checkframe, text="Combine Events?", variable = self.Eventcombine, onvalue = True, offvalue = False, command=lambda: self.EventRecombine()) #location round error self.sliderlabel = ttk.Label(sliderframe, text="How accurate to rename locations?: ") self.slider = Scale(sliderframe, from_=0, to=50, orient="horizontal") self.slider.bind("<ButtonRelease-1>", self.updateValue) self.myout = textbox.textbox(sliderframe, 0, 2) self.myout.readonly(True) #refframe widgets self.lbox = Listbox(refframe, height=5, selectmode='extended') s = Scrollbar(refframe, orient=VERTICAL, command=self.lbox.yview) self.refbox = ttk.Entry(refframe, textvariable=self.newref) addbutton = ttk.Button(refframe, text="Add", command= lambda: self.addnewref(self.newref.get())) delbutton = ttk.Button(refframe, text="Delete", command=lambda: self.delrefs()) checkframe.grid(column=0, row=0, sticky=(E,W)) #refframe.grid(column=0, row=1, sticky=(E,W)) sliderframe.grid(column=0, row=3, sticky=(E,W)) self.sliderlabel.grid(column=0, row=0, sticky=(E,W)) self.slider.grid(column=0, row=1, sticky=(E,W)) self.lbox.grid(column=0, row=0, rowspan=5, sticky=(N,S,E,W)) s.grid(column=1, row=0, rowspan=6, sticky=(N,S)) delbutton.grid(column=0, row=6, sticky=(N,S,E,W)) self.refbox.grid(column=2, row=0, sticky=(N,S,E,W)) addbutton.grid(column=2, row=1, sticky=(N,S,E,W)) self.CteamRecombine.grid(column=0, row=0, sticky=(W)) self.CteamOfOne.grid(column=0, row=1, sticky=(W)) #self.CdateFirst.grid(column=0, row=2, sticky=(W)) depthlbl.grid(column=0, row=3, sticky=(W)) self.CEventRecombine.grid(column=0, row=4, sticky=(W))