def set_data(self, d): LogLikelihoodBase.set_data(self, d) # Bin the data in the analysis space dimnames, bins = zip(*self.base_model.config['analysis_space']) self.data_events_per_bin = Histdd(bins=bins, axis_names=dimnames) self.data_events_per_bin.add( *self.base_model.to_analysis_dimensions(d))
def xes(request): # warnings.filterwarnings("error") data = pd.DataFrame([ dict(s1=56., s2=2905., drift_time=143465., x=2., y=0.4, z=-20, r=2.1, theta=0.1, event_time=1579784955000000000), dict(s1=23, s2=1080., drift_time=445622., x=1.12, y=0.35, z=-59., r=1., theta=0.3, event_time=1579784956000000000) ]) if request.param == 'ER': x = fd.ERSource(data.copy(), batch_size=2, max_sigma=8) elif request.param == 'NR': x = fd.NRSource(data.copy(), batch_size=2, max_sigma=8) elif request.param == 'WIMP': x = fd.WIMPSource(data.copy(), batch_size=2, max_sigma=8) elif request.param == 'ER_spatial': nbins = 100 r = np.linspace(0, 47.9, nbins + 1) z = np.linspace(-97.6, 0, nbins + 1) theta = np.linspace(0, 2 * np.pi, nbins + 1) # Construct PDF histogram h = Histdd(bins=[r, theta, z], axis_names=['r', 'theta', 'z']) h.histogram = np.ones((nbins, nbins, nbins)) # Calculate bin volumes for cylindrical coords (r dr dtheta) r_c, _, _ = h.bin_centers() bin_volumes = h.bin_volumes() * r_c[:, np.newaxis, np.newaxis] # Convert to events per bin histogram h.histogram *= bin_volumes class ERSpatial(fd.ERSource): spatial_rate_hist = h spatial_rate_bin_volumes = bin_volumes x = ERSpatial(data.copy(), batch_size=2, max_sigma=8) return x
def xes(request): # warnings.filterwarnings("error") data = pd.DataFrame([ dict(s1=56., s2=2905., drift_time=143465., x=2., y=0.4, z=-20, r=2.1, theta=0.1, event_time=1483488000000000000), dict(s1=23, s2=1080., drift_time=445622., x=1.12, y=0.35, z=-59., r=1., theta=0.3, event_time=1483488000000000000) ]) if request.param == 'ER': x = fd.ERSource(data.copy(), batch_size=2, max_sigma=8) elif request.param == 'NR': x = fd.NRSource(data.copy(), batch_size=2, max_sigma=8) elif request.param == 'WIMP': x = fd.WIMPSource(data.copy(), batch_size=2, max_sigma=8) elif request.param == 'ER_spatial': nbins = 100 r = np.linspace(0, 47.9, nbins + 1) z = np.linspace(-97.6, 0, nbins + 1) theta = np.linspace(0, 2 * np.pi, nbins + 1) h = Histdd(bins=[r, theta, z], axis_names=['r', 'theta', 'z']) h.histogram = np.ones((nbins, nbins, nbins)) class ERSpatial(fd.ERSource): spatial_hist = h x = ERSpatial(data.copy(), batch_size=2, max_sigma=8) return x
def build_histogram(self): # Get the events to estimate the PDF dimnames, bins = zip(*self.config['analysis_space']) mh = Histdd(bins=bins, axis_names=dimnames) # Get a generator function which will give us the events get = self.get_events_for_density_estimate if not inspect.isgeneratorfunction(get): def get(): return [self.get_events_for_density_estimate()] n_events = 0 for events, n_simulated in get(): n_events += n_simulated mh.add(*utils._events_to_analysis_dimensions( events, self.config['analysis_space'])) self.fraction_in_range = mh.n / n_events # Convert the histogram to a density estimate # This means we have to divide by # - the number of events IN RANGE received # (fraction_in_range keeps track of how many events were not in range) # - the bin sizes self._pdf_histogram = mh.similar_blank_hist() self._pdf_histogram.histogram = mh.histogram.astype(np.float) / mh.n # For the bin widths we need to take an outer product of several vectors, for which numpy has no builtin # This reduce trick does the job instead, see http://stackoverflow.com/questions/17138393 self._bin_volumes = reduce(np.multiply, np.ix_(*[np.diff(bs) for bs in bins])) self._pdf_histogram.histogram /= self._bin_volumes self._n_events_histogram = mh return mh
def plot_peaks_aft_histogram( context, run_id, peaks, pe_bins=np.logspace(0, 7, 120), rt_bins=np.geomspace(2, 1e5, 120), extra_labels=tuple(), rate_range=(1e-4, 1), aft_range=(0, .85), figsize=(14, 5)): """Plot side-by-side (area, width) histograms of the peak rate and mean area fraction top. :param pe_bins: Array of bin edges for the peak area dimension [PE] :param rt_bins: array of bin edges for the rise time dimension [ns] :param extra_labels: List of (area, risetime, text, color) extra labels to put on the plot :param rate_range: Range of rates to show [peaks/(bin*s)] :param aft_range: Range of mean S1 area fraction top / bin to show :param figsize: Figure size to use """ livetime_sec = straxen.get_livetime_sec(context, run_id, peaks) mh = Histdd(peaks, dimensions=( ('area', pe_bins), ('range_50p_area', rt_bins), ('area_fraction_top', np.linspace(0, 1, 100)) )) f, axes = plt.subplots(1, 2, figsize=figsize) def std_axes(): plt.gca().set_facecolor('k') plt.yscale('log') plt.xscale('log') plt.xlabel("Area [PE]") plt.ylabel("Range 50% area [ns]") labels = [ (12, 8, "AP?", 'white'), (3, 150, "1PE\npileup", 'gray'), (30, 200, "1e", 'gray'), (100, 1000, "n-e", 'w'), (2000, 2e4, "Train", 'gray'), (1200, 50, "S1", 'w'), (45e3, 60, "αS1", 'w'), (2e5, 800, "S2", 'w'), ] + list(extra_labels) for x, w, text, color in labels: plt.text(x, w, text, color=color, verticalalignment='center', horizontalalignment='center') plt.sca(axes[0]) (mh / livetime_sec).sum(axis=2).plot( log_scale=True, vmin=rate_range[0], vmax=rate_range[1], colorbar_kwargs=dict(extend='both'), cblabel='Peaks / (bin * s)') std_axes() plt.sca(axes[1]) mh.average(axis=2).plot( vmin=aft_range[0], vmax=aft_range[1], colorbar_kwargs=dict(extend='max'), cmap=plt.cm.jet, cblabel='Mean area fraction top') std_axes() plt.tight_layout()
def plot_peaks_aft_histogram(context, run_id, peaks, pe_bins=np.logspace(0, 7, 120), width_bins=np.geomspace(2, 1e5, 120), extra_labels=tuple(), rate_range=(1e-4, 1), aft_range=(0, .85), figsize=(14, 5)): """Plot side-by-side (area, width) histograms of the peak rate and mean area fraction top.""" try: md = context.run_metadata(run_id, projection=('start', 'end')) livetime_sec = (md['end'] - md['start']).total_seconds() except strax.RunMetadataNotAvailable: livetime_sec = (strax.endtime(peaks)[-1] - peaks[0]['time']) / 1e9 mh = Histdd(peaks, dimensions=(('area', pe_bins), ('range_50p_area', width_bins), ('area_fraction_top', np.linspace(0, 1, 100)))) f, axes = plt.subplots(1, 2, figsize=figsize) def std_axes(): plt.gca().set_facecolor('k') plt.yscale('log') plt.xscale('log') plt.xlabel("Area [PE]") plt.ylabel("Range 50% area [ns]") labels = [ (12, 8, "AP?", 'white'), (3, 150, "1PE\npileup", 'gray'), (30, 200, "1e", 'gray'), (100, 1000, "n-e", 'w'), (2000, 2e4, "Train", 'gray'), (1200, 50, "S1", 'w'), (45e3, 60, "αS1", 'w'), (2e5, 800, "S2", 'w'), ] + list(extra_labels) for x, w, text, color in labels: plt.text(x, w, text, color=color, verticalalignment='center', horizontalalignment='center') plt.sca(axes[0]) (mh / livetime_sec).sum(axis=2).plot(log_scale=True, vmin=rate_range[0], vmax=rate_range[1], colorbar_kwargs=dict(extend='both'), cblabel='Peaks / (bin * hour)') std_axes() plt.sca(axes[1]) mh.average(axis=2).plot(vmin=aft_range[0], vmax=aft_range[1], colorbar_kwargs=dict(extend='max'), cmap=plt.cm.jet, cblabel='Mean area fraction top') std_axes() plt.tight_layout()
df = aft_peak_cut(df) #Binning window_length = 10**8 t_bins = np.linspace(0, window_length, 201) t_bin_width = t_bins[1:] - t_bins[:-1] r_bins = np.linspace(0, (R_tpc)**2, 101) dist_bins = np.linspace(-R_tpc, R_tpc, 101) s2_bins = np.linspace(2, 6, 51) s2_p_bins = np.linspace(0, 4, 51) #Define Blank Hists livet_histogram = Histdd(bins=[ t_bins, s2_bins, ], axis_names=[ 'delta_T', 's2_area', ]) livet_weights_histogram = Histdd(bins=[ t_bins, s2_bins, ], axis_names=[ 'delta_T', 's2_area', ]) events_histogram = Histdd(bins=[ t_bins,
def setUp(self): self.m = Histdd(range=test_range_2d, bins=test_bins_2d, axis_names=['foo', 'bar'])
for idx, x_edge in tqdm(enumerate(xv[:-1])): for idy, y_edge in enumerate(yv[:-1]): df_xy = df.loc[(df.x_s2_tpf > xv[idx][idy]) & (df.x_s2_tpf < xv[idx][idy + 1]) & (df.y_s2_tpf > yv[idx][idy]) & (df.y_s2_tpf < yv[idx + 1][idy])] unique_s2s = pd.unique(df_xy[['s2_time', 'x_s2_tpf', 'y_s2_tpf']].values) num_events = len(unique_s2s) #Define Blank Hists dt_r2_histogram = Histdd(bins=[ t_reduced_bins, r_bins, ], axis_names=[ 'delta_T', 'r_dist', ]) xy_histogram = Histdd(bins=[ t_reduced_bins, x_bins, y_bins, ], axis_names=[ 'delta_T', 'x_p_pos', 'y_p_pos', ])