aboutsummaryrefslogtreecommitdiff
path: root/utils/plot
blob: fd5ea518d25aaeaa4f53d3311671c6aa1d4295f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python
# Copyright (c) 2019, Anthony Latorre <tlatorre at uchicago>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <https://www.gnu.org/licenses/>.

from __future__ import print_function, division
import yaml
try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml.loader import SafeLoader as Loader

import numpy as np
from scipy.stats import iqr
from matplotlib.lines import Line2D

# on retina screens, the default plots are way too small
# by using Qt5 and setting QT_AUTO_SCREEN_SCALE_FACTOR=1
# Qt5 will scale everything using the dpi in ~/.Xresources
import matplotlib
matplotlib.use("Qt5Agg")

IDP_E_MINUS  =    20
IDP_MU_MINUS =    22

SNOMAN_MASS = {
    20: 0.511,
    21: 0.511,
    22: 105.658,
    23: 105.658
}

def plot_hist(x, label=None):
    # determine the bin width using the Freedman Diaconis rule
    # see https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule
    h = 2*iqr(x)/len(x)**(1/3)
    n = max(int((np.max(x)-np.min(x))/h),10)
    bins = np.linspace(np.min(x),np.max(x),n)
    plt.hist(x, bins=bins, histtype='step', label=label)

def plot_legend(n):
    plt.figure(n)
    ax = plt.gca()
    handles, labels = ax.get_legend_handles_labels()
    new_handles = [Line2D([],[],c=h.get_edgecolor()) for h in handles]
    plt.legend(handles=new_handles,labels=labels)

def get_stats(x):
    """
    Returns a tuple (mean, error mean, std, error std) for the values in x.

    The formula for the standard error on the standard deviation comes from
    https://stats.stackexchange.com/questions/156518.
    """
    mean = np.mean(x)
    std = np.std(x)
    n = len(x)
    u4 = np.mean((x-mean)**4)
    error = np.sqrt((u4-(n-3)*std**4/(n-1))/n)/(2*std)
    return mean, std/np.sqrt(n), std, error

if __name__ == '__main__':
    import argparse
    import matplotlib.pyplot as plt
    import numpy as np
    import h5py
    import pandas as pd

    parser = argparse.ArgumentParser("plot fit results")
    parser.add_argument("filenames", nargs='+', help="input files")
    args = parser.parse_args()

    for filename in args.filenames:
        print(filename)
        
        with h5py.File(filename) as f:
            ev = pd.read_hdf(filename, "ev")
            mcgn = pd.read_hdf(filename, "mcgn")
            fits = pd.read_hdf(filename, "fits")

            # get rid of 2nd events like Michel electrons
            ev = ev.sort_values(['run','gtid']).groupby(['evn'],as_index=False).nth(0)

            # Now, we merge all three datasets together to produce a single
            # dataframe. To do so, we join the ev dataframe with the mcgn frame
            # on the evn column, and then join with the fits on the run and
            # gtid columns.
            #
            # At the end we will have a single dataframe with one row for each
            # fit, i.e. it will look like:
            #
            # >>> data
            #   run   gtid nhit, ... mcgn_x, mcgn_y, mcgn_z, ..., fit_id1, fit_x, fit_y, fit_z, ...
            #
            # Before merging, we prefix the primary seed track table with mcgn_
            # and the fit table with fit_ just to make things easier.

            # Prefix track and fit frames
            mcgn = mcgn.add_prefix("mcgn_")
            fits = fits.add_prefix("fit_")

            # merge ev and mcgn on evn
            data = ev.merge(mcgn,left_on=['evn'],right_on=['mcgn_evn'])
            # merge data and fits on run and gtid
            data = data.merge(fits,left_on=['run','gtid'],right_on=['fit_run','fit_gtid'])

            # calculate true kinetic energy
            mass = [SNOMAN_MASS[id] for id in data['mcgn_id'].values]
            data['T'] = data['mcgn_energy'].values - mass
            data['dx'] = data['fit_x'].values - data['mcgn_x'].values
            data['dy'] = data['fit_y'].values - data['mcgn_y'].values
            data['dz'] = data['fit_z'].values - data['mcgn_z'].values
            data['dT'] = data['fit_energy1'].values - data['T'].values

            true_dir = np.dstack((data['mcgn_dirx'],data['mcgn_diry'],data['mcgn_dirz'])).squeeze()
            dir = np.dstack((np.sin(data['fit_theta1'])*np.cos(data['fit_phi1']),
                             np.sin(data['fit_theta1'])*np.sin(data['fit_phi1']),
                             np.cos(data['fit_theta1']))).squeeze()

            data['theta'] = np.degrees(np.arccos((true_dir*dir).sum(axis=-1)))

            # only select fits which have at least 2 fits
            data = data.groupby(['run','gtid']).filter(lambda x: len(x) > 1)
            data_true = data[data['fit_id1'] == data['mcgn_id']]
            data_e = data[data['fit_id1'] == IDP_E_MINUS]
            data_mu = data[data['fit_id1'] == IDP_MU_MINUS]

            data_true = data_true.set_index(['run','gtid'])
            data_e = data_e.set_index(['run','gtid'])
            data_mu = data_mu.set_index(['run','gtid'])

            data_true['ratio'] = data_mu['fit_fmin']-data_e['fit_fmin']
            data_true['te'] = data_e['fit_time']
            data_true['tm'] = data_mu['fit_time']
            data_true['Te'] = data_e['fit_energy1']

        if len(data_true) < 2:
            continue

        mean, mean_error, std, std_error = get_stats(data_true.dT)
        print("dT      = %.2g +/- %.2g" % (mean, mean_error))
        print("std(dT) = %.2g +/- %.2g" % (std, std_error))
        mean, mean_error, std, std_error = get_stats(data_true.dx)
        print("dx      = %4.2g +/- %.2g" % (mean, mean_error))
        print("std(dx) = %4.2g +/- %.2g" % (std, std_error))
        mean, mean_error, std, std_error = get_stats(data_true.dy)
        print("dy      = %4.2g +/- %.2g" % (mean, mean_error))
        print("std(dy) = %4.2g +/- %.2g" % (std, std_error))
        mean, mean_error, std, std_error = get_stats(data_true.dz)
        print("dz      = %4.2g +/- %.2g" % (mean, mean_error))
        print("std(dz) = %4.2g +/- %.2g" % (std, std_error))
        mean, mean_error, std, std_error = get_stats(data_true.theta)
        print("std(theta) = %4.2g +/- %.2g" % (std, std_error))

        plt.figure(1)
        plot_hist(data_true.dT, label=filename)
        plt.xlabel("Kinetic Energy difference (MeV)")
        plt.figure(2)
        plot_hist(data_true.dx, label=filename)
        plt.xlabel("X Position difference (cm)")
        plt.figure(3)
        plot_hist(data_true.dy, label=filename)
        plt.xlabel("Y Position difference (cm)")
        plt.figure(4)
        plot_hist(data_true.dz, label=filename)
        plt.xlabel("Z Position difference (cm)")
        plt.figure(5)
        plot_hist(data_true.theta, label=filename)
        plt.xlabel(r"$\theta$ (deg)")
        plt.figure(6)
        plot_hist(data_true.ratio, label=filename)
        plt.xlabel(r"Log Likelihood Ratio ($e/\mu$)")
        plt.figure(7)
        plot_hist(data_true.te/1e3/60.0, label=filename)
        plt.xlabel(r"Electron Fit time (minutes)")
        plt.figure(8)
        plot_hist(data_true.tm/1e3/60.0, label=filename)
        plt.xlabel(r"Muon Fit time (minutes)")
        plt.figure(9)
        plot_hist(data_true.fit_psi/data_true.nhit, label=filename)
        plt.xlabel(r"$\Psi$/Nhit")

    plot_legend(1)
    plot_legend(2)
    plot_legend(3)
    plot_legend(4)
    plot_legend(5)
    plot_legend(6)
    plot_legend(7)
    plot_legend(8)
    plot_legend(9)
    plt.show()
/span>("Qt5Agg") font = {'family':'serif', 'serif': ['computer modern roman']} matplotlib.rc('font',**font) matplotlib.rc('text', usetex=True) SNOMAN_MASS = { 20: 0.511, 21: 0.511, 22: 105.658, 23: 105.658 } AV_RADIUS = 600.0 # Data cleaning bitmasks. DC_MUON = 0x1 DC_JUNK = 0x2 DC_CRATE_ISOTROPY = 0x4 DC_QVNHIT = 0x8 DC_NECK = 0x10 DC_FLASHER = 0x20 DC_ESUM = 0x40 DC_OWL = 0x80 DC_OWL_TRIGGER = 0x100 DC_FTS = 0x200 DC_ITC = 0x400 DC_BREAKDOWN = 0x800 particle_id = {20: 'e', 22: r'\mu'} def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) def plot_hist2(df, muons=False): for id, df_id in sorted(df.groupby('id')): if id == 20: plt.subplot(2,3,1) elif id == 22: plt.subplot(2,3,2) elif id == 2020: plt.subplot(2,3,4) elif id == 2022: plt.subplot(2,3,5) elif id == 2222: plt.subplot(2,3,6) if muons: plt.hist(np.log10(df_id.ke.values/1000), bins=np.linspace(0,4.5,100), histtype='step') plt.xlabel("log10(Energy (GeV))") else: plt.hist(df_id.ke.values, bins=np.linspace(20,10e3,100), histtype='step') plt.xlabel("Energy (MeV)") plt.title('$' + ''.join([particle_id[int(''.join(x))] for x in grouper(str(id),2)]) + '$') if len(df): plt.tight_layout() def plot_hist(df, muons=False): for id, df_id in sorted(df.groupby('id')): if id == 20: plt.subplot(3,4,1) elif id == 22: plt.subplot(3,4,2) elif id == 2020: plt.subplot(3,4,5) elif id == 2022: plt.subplot(3,4,6) elif id == 2222: plt.subplot(3,4,7) elif id == 202020: plt.subplot(3,4,9) elif id == 202022: plt.subplot(3,4,10) elif id == 202222: plt.subplot(3,4,11) elif id == 222222: plt.subplot(3,4,12) if muons: plt.hist(np.log10(df_id.ke.values/1000), bins=np.linspace(0,4.5,100), histtype='step') plt.xlabel("log10(Energy (GeV))") else: plt.hist(df_id.ke.values, bins=np.linspace(20,10e3,100), histtype='step') plt.xlabel("Energy (MeV)") plt.title(str(id)) if len(df): plt.tight_layout() def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] def print_warning(msg): print(bcolors.FAIL + msg + bcolors.ENDC,file=sys.stderr) def unwrap(p, delta, axis=-1): """ A modified version of np.unwrap() useful for unwrapping the 50 MHz clock. It unwraps discontinuities bigger than delta/2 by delta. Example: >>> a = np.arange(10) % 5 >>> a array([0, 1, 2, 3, 4, 0, 1, 2, 3, 4]) >>> unwrap(a,5) array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) In the case of the 50 MHz clock delta should be 0x7ffffffffff*20.0. """ p = np.asarray(p) nd = p.ndim dd = np.diff(p, axis=axis) slice1 = [slice(None, None)]*nd # full slices slice1[axis] = slice(1, None) slice1 = tuple(slice1) ddmod = np.mod(dd + delta/2, delta) - delta/2 np.copyto(ddmod, delta/2, where=(ddmod == -delta/2) & (dd > 0)) ph_correct = ddmod - dd np.copyto(ph_correct, 0, where=abs(dd) < delta/2) up = np.array(p, copy=True, dtype='d') up[slice1] = p[slice1] + ph_correct.cumsum(axis) return up def unwrap_50_mhz_clock(gtr): """ Unwrap an array with 50 MHz clock times. These times should all be in nanoseconds and come from the KEV_GTR variable in the EV bank. Note: We assume here that the events are already ordered contiguously by GTID, so you shouldn't pass an array with multiple runs! """ return unwrap(gtr,0x7ffffffffff*20.0) def retrigger_cut(ev): """ Cuts all retrigger events. """ return ev[ev.dt > 500] def breakdown_follower_cut(ev): """ Cuts all events within 1 second of breakdown events. """ breakdowns = ev[ev.dc & DC_BREAKDOWN != 0] return ev[~np.any((ev.gtr.values > breakdowns.gtr.values[:,np.newaxis]) & \ (ev.gtr.values < breakdowns.gtr.values[:,np.newaxis] + 1e9),axis=0)] def flasher_follower_cut(ev): """ Cuts all events within 200 microseconds of flasher events. """ flashers = ev[ev.dc & DC_FLASHER != 0] return ev[~np.any((ev.gtr.values > flashers.gtr.values[:,np.newaxis]) & \ (ev.gtr.values < flashers.gtr.values[:,np.newaxis] + 200e3),axis=0)] def muon_follower_cut(ev): """ Cuts all events 200 microseconds after a muon. """ muons = ev[ev.dc & DC_MUON != 0] return ev[~np.any((ev.gtr.values > muons.gtr.values[:,np.newaxis]) & \ (ev.gtr.values < muons.gtr.values[:,np.newaxis] + 200e3),axis=0)] def michel_cut(ev): """ Looks for Michel electrons after muons. """ prompt_plus_muons = ev[ev.prompt | ((ev.dc & DC_MUON) != 0)] # Michel electrons and neutrons can be any event which is not a prompt # event follower = ev[~ev.prompt] # require Michel events to pass more of the SNO data cleaning cuts michel = follower[follower.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_FLASHER | DC_NECK | DC_ESUM | DC_OWL | DC_OWL_TRIGGER | DC_FTS) == 0] michel = michel[michel.nhit >= 100] # Accept events which had a muon more than 800 nanoseconds but less than 20 # microseconds before them. The 800 nanoseconds cut comes from Richie's # thesis. He also mentions that the In Time Channel Spread Cut is very # effective at cutting electron events caused by muons, so I should # implement that. # # Note: We currently don't look across run boundaries. This should be a # *very* small effect, and the logic to do so would be very complicated # since I would have to deal with 50 MHz clock rollovers, etc. if prompt_plus_muons.size and michel.size: mask = (michel.gtr.values > prompt_plus_muons.gtr.values[:,np.newaxis] + 800) & \ (michel.gtr.values < prompt_plus_muons.gtr.values[:,np.newaxis] + 20e3) michel = michel.iloc[np.any(mask,axis=0)] michel['muon_gtid'] = pd.Series(prompt_plus_muons['gtid'].iloc[np.argmax(mask[:,np.any(mask,axis=0)],axis=0)].values, index=michel.index.values, dtype=np.int32) return michel else: # Return an empty slice since we need it to have the same datatype as # the other dataframes michel = ev[:0] michel['muon_gtid'] = -1 return michel def atmospheric_events(ev): """ Tags atmospheric events which have a neutron follower. """ prompt = ev[ev.prompt] # Michel electrons and neutrons can be any event which is not a prompt # event follower = ev[~ev.prompt] ev['atm'] = np.zeros(len(ev),dtype=np.bool) if prompt.size and follower.size: # neutron followers have to obey stricter set of data cleaning cuts neutron = follower[follower.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_FLASHER | DC_NECK | DC_ESUM | DC_OWL | DC_OWL_TRIGGER | DC_FTS) == 0] neutron = neutron[~np.isnan(neutron.ftp_x) & ~np.isnan(neutron.rsp_energy)] # FIXME: What should the radius cut be here? AV? (r/r_psup)^3 < 0.9? neutron = neutron[neutron.ftp_r < AV_RADIUS] neutron = neutron[neutron.rsp_energy > 4.0] # neutron events accepted after 20 microseconds and before 250 ms (50 ms during salt) ev.loc[ev.prompt,'atm'] = np.any((neutron.gtr.values > prompt.gtr.values[:,np.newaxis] + 20e3) & \ (neutron.gtr.values < prompt.gtr.values[:,np.newaxis] + 250e6),axis=1) return ev def gtid_sort(ev, first_gtid): """ Adds 0x1000000 to the gtid_sort column for all gtids before the first gtid in a run, which should be passed as a dictionary. This column can then be used to sort the events sequentially. This function should be passed to ev.groupby('run').apply(). We use this idiom instead of just looping over the groupby results since groupby() makes a copy of the dataframe, i.e. for run, ev_run in ev.groupby('run'): ev_run.loc[ev_run.gtid < first_gtid[run],'gtid_sort'] += 0x1000000 would produce a SettingWithCopyWarning, so instead we use: ev = ev.groupby('run',as_index=False).apply(gtid_sort,first_gtid=first_gtid) which doesn't have this problem. """ # see https://stackoverflow.com/questions/32460593/including-the-group-name-in-the-apply-function-pandas-python run = ev.name if run not in first_gtid: print_warning("No RHDR bank for run %i! Assuming first event is the first GTID." % run) first_gtid[run] = ev.gtid.iloc[0] ev.loc[ev.gtid < first_gtid[run],'gtid_sort'] += 0x1000000 return ev def prompt_event(ev): ev['prompt'] = (ev.nhit >= 100) ev.loc[ev.prompt,'prompt'] &= np.concatenate(([True],np.diff(ev[ev.prompt].gtr.values) > 250e6)) return ev # Taken from https://raw.githubusercontent.com/mwaskom/seaborn/c73055b2a9d9830c6fbbace07127c370389d04dd/seaborn/utils.py def despine(fig=None, ax=None, top=True, right=True, left=False, bottom=False, offset=None, trim=False): """Remove the top and right spines from plot(s). fig : matplotlib figure, optional Figure to despine all axes of, default uses current figure. ax : matplotlib axes, optional Specific axes object to despine. top, right, left, bottom : boolean, optional If True, remove that spine. offset : int or dict, optional Absolute distance, in points, spines should be moved away from the axes (negative values move spines inward). A single value applies to all spines; a dict can be used to set offset values per side. trim : bool, optional If True, limit spines to the smallest and largest major tick on each non-despined axis. Returns ------- None """ # Get references to the axes we want if fig is None and ax is None: axes = plt.gcf().axes elif fig is not None: axes = fig.axes elif ax is not None: axes = [ax] for ax_i in axes: for side in ["top", "right", "left", "bottom"]: # Toggle the spine objects is_visible = not locals()[side] ax_i.spines[side].set_visible(is_visible) if offset is not None and is_visible: try: val = offset.get(side, 0) except AttributeError: val = offset _set_spine_position(ax_i.spines[side], ('outward', val)) # Potentially move the ticks if left and not right: maj_on = any( t.tick1line.get_visible() for t in ax_i.yaxis.majorTicks ) min_on = any( t.tick1line.get_visible() for t in ax_i.yaxis.minorTicks ) ax_i.yaxis.set_ticks_position("right") for t in ax_i.yaxis.majorTicks: t.tick2line.set_visible(maj_on) for t in ax_i.yaxis.minorTicks: t.tick2line.set_visible(min_on) if bottom and not top: maj_on = any( t.tick1line.get_visible() for t in ax_i.xaxis.majorTicks ) min_on = any( t.tick1line.get_visible() for t in ax_i.xaxis.minorTicks ) ax_i.xaxis.set_ticks_position("top") for t in ax_i.xaxis.majorTicks: t.tick2line.set_visible(maj_on) for t in ax_i.xaxis.minorTicks: t.tick2line.set_visible(min_on) if trim: # clip off the parts of the spines that extend past major ticks xticks = ax_i.get_xticks() if xticks.size: firsttick = np.compress(xticks >= min(ax_i.get_xlim()), xticks)[0] lasttick = np.compress(xticks <= max(ax_i.get_xlim()), xticks)[-1] ax_i.spines['bottom'].set_bounds(firsttick, lasttick) ax_i.spines['top'].set_bounds(firsttick, lasttick) newticks = xticks.compress(xticks <= lasttick) newticks = newticks.compress(newticks >= firsttick) ax_i.set_xticks(newticks) yticks = ax_i.get_yticks() if yticks.size: firsttick = np.compress(yticks >= min(ax_i.get_ylim()), yticks)[0] lasttick = np.compress(yticks <= max(ax_i.get_ylim()), yticks)[-1] ax_i.spines['left'].set_bounds(firsttick, lasttick) ax_i.spines['right'].set_bounds(firsttick, lasttick) newticks = yticks.compress(yticks <= lasttick) newticks = newticks.compress(newticks >= firsttick) ax_i.set_yticks(newticks) def plot_corner_plot(ev, title, save=None): variables = ['r_psup','psi','z','udotr'] labels = [r'$(r/r_\mathrm{PSUP})^3$',r'$\psi$','z',r'$\vec{u}\cdot\vec{r}$'] limits = [(0,1),(0,10),(-840,840),(-1,1)] cuts = [0.9,6,0,-0.5] ev = ev.dropna(subset=variables) f = plt.figure(figsize=(FIGSIZE[0],FIGSIZE[0])) despine(fig,trim=True) for i in range(len(variables)): for j in range(len(variables)): if j > i: continue ax = plt.subplot(len(variables),len(variables),i*len(variables)+j+1) if i == j: plt.hist(ev[variables[i]],bins=np.linspace(limits[i][0],limits[i][1],100),histtype='step') plt.gca().set_xlim(limits[i]) else: p_i_lo = np.count_nonzero(ev[variables[i]] < cuts[i])/len(ev) p_j_lo = np.count_nonzero(ev[variables[j]] < cuts[j])/len(ev) p_lolo = p_i_lo*p_j_lo p_lohi = p_i_lo*(1-p_j_lo) p_hilo = (1-p_i_lo)*p_j_lo p_hihi = (1-p_i_lo)*(1-p_j_lo) n_lolo = np.count_nonzero((ev[variables[i]] < cuts[i]) & (ev[variables[j]] < cuts[j])) n_lohi = np.count_nonzero((ev[variables[i]] < cuts[i]) & (ev[variables[j]] >= cuts[j])) n_hilo = np.count_nonzero((ev[variables[i]] >= cuts[i]) & (ev[variables[j]] < cuts[j])) n_hihi = np.count_nonzero((ev[variables[i]] >= cuts[i]) & (ev[variables[j]] >= cuts[j])) n = len(ev) observed = np.array([n_lolo,n_lohi,n_hilo,n_hihi]) expected = n*np.array([p_lolo,p_lohi,p_hilo,p_hihi]) psi = -poisson.logpmf(observed,expected).sum() + poisson.logpmf(observed,observed).sum() psi /= np.std(-poisson.logpmf(np.random.poisson(observed,size=(10000,4)),observed).sum(axis=1) + poisson.logpmf(observed,observed).sum()) plt.scatter(ev[variables[j]],ev[variables[i]],s=0.5) plt.gca().set_xlim(limits[j]) plt.gca().set_ylim(limits[i]) plt.title(r"$\psi = %.1f$" % psi) if i == len(variables) - 1: plt.xlabel(labels[j]) else: plt.setp(ax.get_xticklabels(),visible=False) if j == 0: plt.ylabel(labels[i]) else: plt.setp(ax.get_yticklabels(),visible=False) plt.axvline(cuts[j],color='k',ls='--',alpha=0.5) if i != j: plt.axhline(cuts[i],color='k',ls='--',alpha=0.5) plt.tight_layout() if save: plt.savefig(save + ".pdf") plt.savefig(save + ".eps") plt.suptitle(title) def intersect_sphere(pos, dir, R): """ Compute the first intersection of a ray starting at `pos` with direction `dir` and a sphere centered at the origin with radius `R`. The distance to the intersection is returned. Example: pos = np.array([0,0,0]) dir = np.array([1,0,0]) l = intersect_sphere(pos,dir,PSUP_RADIUS): if l is not None: hit = pos + l*dir print("ray intersects sphere at %.2f %.2f %.2f", hit[0], hit[1], hit[2]) else: print("ray didn't intersect sphere") """ b = 2*np.dot(dir,pos) c = np.dot(pos,pos) - R*R if b*b - 4*c <= 0: # Ray doesn't intersect the sphere. return None # First, check the shorter solution. l = (-b - np.sqrt(b*b - 4*c))/2 # If the shorter solution is less than 0, check the second solution. if l < 0: l = (-b + np.sqrt(b*b - 4*c))/2 # If the distance is still negative, we didn't intersect the sphere. if l < 0: return None return l def get_dx(row): pos = np.array([row.x,row.y,row.z]) dir = np.array([np.sin(row.theta1)*np.cos(row.phi1), np.sin(row.theta1)*np.sin(row.phi1), np.cos(row.theta1)]) l = intersect_sphere(pos,-dir,PSUP_RADIUS) if l is not None: pos -= dir*l michel_pos = np.array([row.x_michel,row.y_michel,row.z_michel]) return np.linalg.norm(michel_pos-pos) else: return 0 def dx_to_energy(dx): lines = [] with open("../src/muE_water_liquid.txt") as f: for i, line in enumerate(f): if i < 10: continue if 'Minimum ionization' in line: continue if 'Muon critical energy' in line: continue lines.append(line) data = np.genfromtxt(lines) return np.interp(dx,data[:,8],data[:,0]) def iqr_std_err(x): """ Returns the approximate standard deviation assuming the central part of the distribution is gaussian. """ x = x.dropna() n = len(x) if n == 0: return np.nan # see https://stats.stackexchange.com/questions/110902/error-on-interquartile-range std = iqr(x.values)/1.3489795 return 1.573*std/np.sqrt(n) def iqr_std(x): """ Returns the approximate standard deviation assuming the central part of the distribution is gaussian. """ x = x.dropna() n = len(x) if n == 0: return np.nan return iqr(x.values)/1.3489795 def quantile_error(x,q): """ Returns the standard error for the qth quantile of `x`. The error is computed using the Maritz-Jarrett method described here: https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/quantse.htm. """ x = np.sort(x) n = len(x) m = int(q*n+0.5) A = m - 1 B = n - m i = np.arange(1,len(x)+1) w = beta.cdf(i/n,A,B) - beta.cdf((i-1)/n,A,B) return np.sqrt(np.sum(w*x**2)-np.sum(w*x)**2) def q90_err(x): """ Returns the error on the 90th percentile for all the non NaN values in a Series `x`. """ x = x.dropna() n = len(x) if n == 0: return np.nan return quantile_error(x.values,0.9) def q90(x): """ Returns the 90th percentile for all the non NaN values in a Series `x`. """ x = x.dropna() n = len(x) if n == 0: return np.nan return np.percentile(x.values,90.0) def median(x): """ Returns the median for all the non NaN values in a Series `x`. """ x = x.dropna() n = len(x) if n == 0: return np.nan return np.median(x.values) def median_err(x): """ Returns the approximate error on the median for all the non NaN values in a Series `x`. The error on the median is approximated assuming the central part of the distribution is gaussian. """ x = x.dropna() n = len(x) if n == 0: return np.nan # First we estimate the standard deviation using the interquartile range. # Here we are essentially assuming the central part of the distribution is # gaussian. std = iqr(x.values)/1.3489795 median = np.median(x.values) # Now we estimate the error on the median for a gaussian # See https://stats.stackexchange.com/questions/45124/central-limit-theorem-for-sample-medians. return 1/(2*np.sqrt(n)*norm.pdf(median,median,std)) def std_err(x): x = x.dropna() mean = np.mean(x) std = np.std(x) n = len(x) if n == 0: return np.nan elif n == 1: return 0.0 u4 = np.mean((x-mean)**4) error = np.sqrt((u4-(n-3)*std**4/(n-1))/n)/(2*std) return error # Fermi constant GF = 1.16637887e-5 # 1/MeV^2 ELECTRON_MASS = 0.5109989461 # MeV MUON_MASS = 105.6583745 # MeV PROTON_MASS = 938.272081 # MeV FINE_STRUCTURE_CONSTANT = 7.297352566417e-3 def f(x): y = (5/(3*x**2) + 16*x/3 + 4/x + (12-8*x)*np.log(1/x-1) - 8)*np.log(MUON_MASS/ELECTRON_MASS) y += (6-4*x)*(2*spence(x) - 2*np.log(x)**2 + np.log(x) + np.log(1-x)*(3*np.log(x)-1/x-1) - np.pi**2/3-2) y += (1-x)*(34*x**2+(5-34*x**2+17*x)*np.log(x) - 22*x)/(3*x**2) y += 6*(1-x)*np.log(x) return y def michel_spectrum(T): """ Michel electron energy spectrum for a free muon. `T` should be the kinetic energy of the electron or positron in MeV. Note: The result is not normalized. From https://arxiv.org/abs/1406.3575. """ E = T + ELECTRON_MASS x = 2*E/MUON_MASS mask = (x > 0) & (x < 1) y = np.zeros_like(x,dtype=np.double) y[mask] = GF**2*MUON_MASS**5*x[mask]**2*(6-4*x[mask]+FINE_STRUCTURE_CONSTANT*f(x[mask])/np.pi)/(192*np.pi**3) y *= 2*MUON_MASS return y if __name__ == '__main__': import argparse import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys import h5py parser = argparse.ArgumentParser("plot fit results") parser.add_argument("filenames", nargs='+', help="input files") parser.add_argument("--dc", action='store_true', default=False, help="plot corner plots for backgrounds") parser.add_argument("--save", action='store_true', default=False, help="save corner plots for backgrounds") args = parser.parse_args() ev = pd.concat([pd.read_hdf(filename, "ev") for filename in args.filenames],ignore_index=True) fits = pd.concat([pd.read_hdf(filename, "fits") for filename in args.filenames],ignore_index=True) rhdr = pd.concat([pd.read_hdf(filename, "rhdr") for filename in args.filenames],ignore_index=True) first_gtid = rhdr.set_index('run').to_dict()['first_gtid'] # First, remove junk events since orphans won't have a 50 MHz clock and so # could screw up the 50 MHz clock unwrapping ev = ev[ev.dc & DC_JUNK == 0] # We need the events to be in time order here in order to calculate the # delta t between events. It's not obvious exactly how to do this. You # could sort by GTID, but that wraps around. Similarly we can't sort by the # 50 MHz clock because it also wraps around. Finally, I'm hesitant to sort # by the 10 MHz clock since it can be unreliable. # # Update: Phil proposed a clever way to get the events in order using the # GTID: # # > The GTID rollover should be easy to handle because there should never # > be two identical GTID's in a run. So if you order the events by GTID, # > you can assume that events with GTID's that come logically before the # > first GTID in the run must have occurred after the other events. # # Therefore, we can just add 0x1000000 to all GTIDs before the first GTID # in the event and sort on that. We get the first GTID from the RHDR bank. ev['gtid_sort'] = ev['gtid'].copy() ev = ev.groupby('run',as_index=False).apply(gtid_sort,first_gtid=first_gtid).reset_index(level=0,drop=True) ev = ev.sort_values(by=['run','gtid_sort'],kind='mergesort') for run, ev_run in ev.groupby('run'): # Warn about 50 MHz clock jumps since they could indicate that the # events aren't in order. dt = np.diff(ev_run.gtr) if np.count_nonzero((np.abs(dt) > 1e9) & (dt > -0x7ffffffffff*20.0/2)): print_warning("Warning: %i 50 MHz clock jumps in run %i. Are the events in order?" % \ (np.count_nonzero((np.abs(dt) > 1e9) & (dt > -0x7ffffffffff*20.0/2)),run)) # unwrap the 50 MHz clock within each run ev.gtr = ev.groupby(['run'],group_keys=False)['gtr'].transform(unwrap_50_mhz_clock) for run, ev_run in ev.groupby('run'): # Warn about GTID jumps since we could be missing a potential flasher # and/or breakdown, and we need all the events in order to do a # retrigger cut if np.count_nonzero(np.diff(ev_run.gtid) != 1): print_warning("Warning: %i GTID jumps in run %i" % (np.count_nonzero(np.diff(ev_run.gtid) != 1),run)) # calculate the time difference between each event and the previous event # so we can tag retrigger events ev['dt'] = ev.groupby(['run'],group_keys=False)['gtr'].transform(lambda x: np.concatenate(([1e9],np.diff(x.values)))) # This is a bit of a hack. It appears that many times the fit will # actually do much better by including a very low energy electron or # muon. I believe the reason for this is that of course my likelihood # function is not perfect (for example, I don't include the correct # angular distribution for Rayleigh scattered light), and so the fitter # often wants to add a very low energy electron or muon to fix things. # # Ideally I would fix the likelihood function, but for now we just # discard any fit results which have a very low energy electron or # muon. # # FIXME: Test this since query() is new to pandas fits = fits.query('not (n > 1 and ((id1 == 20 and energy1 < 20) or (id2 == 20 and energy2 < 20) or (id3 == 20 and energy3 < 20)))') fits = fits.query('not (n > 1 and ((id2 == 22 and energy1 < 200) or (id2 == 22 and energy2 < 200) or (id3 == 22 and energy3 < 200)))') # Calculate the approximate Ockham factor. # See Chapter 20 in "Probability Theory: The Logic of Science" by Jaynes # # Note: This is a really approximate form by assuming that the shape of # the likelihood space is equal to the average uncertainty in the # different parameters. fits['w'] = fits['n']*np.log(0.1*0.001) + np.log(fits['energy1']) + fits['n']*np.log(1e-4/(4*np.pi)) # Apply a fudge factor to the Ockham factor of 100 for each extra particle # FIXME: I chose 100 a while ago but didn't really investigate what the # optimal value was or exactly why it was needed. Should do this. fits['w'] -= fits['n']*100 # Note: we index on the left hand site with loc to avoid a copy error # # See https://www.dataquest.io/blog/settingwithcopywarning/ fits.loc[fits['n'] > 1, 'w'] += np.log(fits[fits['n'] > 1]['energy2']) fits.loc[fits['n'] > 2, 'w'] += np.log(fits[fits['n'] > 2]['energy3']) fits['fmin'] = fits['fmin'] - fits['w'] # See https://stackoverflow.com/questions/11976503/how-to-keep-index-when-using-pandas-merge # for how to properly divide the psi column by nhit_cal which is in the ev # dataframe before we actually merge fits['psi'] /= fits.reset_index().merge(ev,on=['run','gtid']).set_index('index')['nhit_cal'] fits.loc[fits['n'] == 1,'ke'] = fits['energy1'] fits.loc[fits['n'] == 2,'ke'] = fits['energy1'] + fits['energy2'] fits.loc[fits['n'] == 3,'ke'] = fits['energy1'] + fits['energy2'] + fits['energy3'] fits['id'] = fits['id1'] fits.loc[fits['n'] == 2, 'id'] = fits['id1']*100 + fits['id2'] fits.loc[fits['n'] == 3, 'id'] = fits['id1']*10000 + fits['id2']*100 + fits['id3'] fits['theta'] = fits['theta1'] fits['r'] = np.sqrt(fits.x**2 + fits.y**2 + fits.z**2) fits['r_psup'] = (fits['r']/PSUP_RADIUS)**3 ev['ftp_r'] = np.sqrt(ev.ftp_x**2 + ev.ftp_y**2 + ev.ftp_z**2) ev['ftp_r_psup'] = (ev['ftp_r']/PSUP_RADIUS)**3 print("number of events = %i" % len(ev)) # Now, select prompt events. # # We define a prompt event here as any event with an NHIT > 100 and whose # previous > 100 nhit event was more than 250 ms ago # # Note: It's important we do this *before* applying the data cleaning cuts # since otherwise we may have a prompt event identified only after the # cuts. # # For example, suppose there was a breakdown and for whatever reason # the *second* event after the breakdown didn't get tagged correctly. If we # apply the data cleaning cuts first and then tag prompt events then this # event will get tagged as a prompt event. ev = ev.groupby('run',group_keys=False).apply(prompt_event) print("number of events after prompt nhit cut = %i" % np.count_nonzero(ev.prompt)) # flasher follower cut ev = ev.groupby('run',group_keys=False).apply(flasher_follower_cut) # breakdown follower cut ev = ev.groupby('run',group_keys=False).apply(breakdown_follower_cut) # retrigger cut ev = ev.groupby('run',group_keys=False).apply(retrigger_cut) if args.save: # default \textwidth for a fullpage article in Latex is 16.50764 cm. # You can figure this out by compiling the following TeX document: # # \documentclass{article} # \usepackage{fullpage} # \usepackage{layouts} # \begin{document} # textwidth in cm: \printinunitsof{cm}\prntlen{\textwidth} # \end{document} width = 16.50764 width /= 2.54 # cm -> inches # According to this page: # http://www-personal.umich.edu/~jpboyd/eng403_chap2_tuftegospel.pdf, # Tufte suggests an aspect ratio of 1.5 - 1.6. height = width/1.5 FIGSIZE = (width,height) import matplotlib.pyplot as plt font = {'family':'serif', 'serif': ['computer modern roman']} plt.rc('font',**font) plt.rc('text', usetex=True) else: # on retina screens, the default plots are way too small # by using Qt5 and setting QT_AUTO_SCREEN_SCALE_FACTOR=1 # Qt5 will scale everything using the dpi in ~/.Xresources import matplotlib matplotlib.use("Qt5Agg") import matplotlib.pyplot as plt # Default figure size. Currently set to my monitor width and height so that # things are properly formatted FIGSIZE = (13.78,7.48) # Make the defalt font bigger plt.rc('font', size=22) if args.dc: ev = ev[ev.prompt] ev.set_index(['run','gtid']) ev = pd.merge(fits,ev,how='inner',on=['run','gtid']) ev_single_particle = ev[(ev.id2 == 0) & (ev.id3 == 0)] ev_single_particle = ev_single_particle.sort_values('fmin').groupby(['run','gtid']).nth(0) ev = ev.sort_values('fmin').groupby(['run','gtid']).nth(0) ev['cos_theta'] = np.cos(ev['theta1']) ev['udotr'] = np.sin(ev_single_particle.theta1)*np.cos(ev_single_particle.phi1)*ev_single_particle.x + \ np.sin(ev_single_particle.theta1)*np.sin(ev_single_particle.phi1)*ev_single_particle.y + \ np.cos(ev_single_particle.theta1)*ev_single_particle.z ev['udotr'] /= ev.r flashers = ev[ev.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_FLASHER | DC_NECK | DC_ITC | DC_BREAKDOWN) == DC_FLASHER] muon = ev[ev.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_FLASHER | DC_NECK | DC_ITC | DC_BREAKDOWN | DC_MUON) == DC_MUON] neck = ev[(ev.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_NECK)) == DC_NECK] noise = ev[(ev.dc & (DC_ITC | DC_QVNHIT | DC_JUNK | DC_CRATE_ISOTROPY)) != 0] breakdown = ev[ev.nhit >= 1000] breakdown = breakdown[breakdown.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_NECK | DC_ITC) == 0] breakdown = breakdown[breakdown.dc & (DC_FLASHER | DC_BREAKDOWN) != 0] signal = ev[ev.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_FLASHER | DC_NECK | DC_ITC | DC_BREAKDOWN | DC_MUON) == 0] with pd.option_context('display.max_rows', None, 'display.max_columns', None): print("Noise events") print(noise[['psi','x','y','z','id1','id2']]) print("Muons") print(muon[['psi','r','id1','id2','id3','energy1','energy2','energy3']]) print("Neck") print(neck[neck.psi < 6][['psi','r','id1','cos_theta']]) print("Flashers") print(flashers[flashers.udotr > 0]) print("Signal") print(signal) # save as PDF b/c EPS doesn't support alpha values if args.save: plot_corner_plot(breakdown,"Breakdowns",save="breakdown_corner_plot") plot_corner_plot(muon,"Muons",save="muon_corner_plot") plot_corner_plot(flashers,"Flashers",save="flashers_corner_plot") plot_corner_plot(neck,"Neck",save="neck_corner_plot") plot_corner_plot(noise,"Noise",save="noise_corner_plot") plot_corner_plot(signal,"Signal",save="signal_corner_plot") else: plot_corner_plot(breakdown,"Breakdowns") plot_corner_plot(muon,"Muons") plot_corner_plot(flashers,"Flashers") plot_corner_plot(neck,"Neck") plot_corner_plot(noise,"Noise") plot_corner_plot(signal,"Signal") fig = plt.figure(figsize=FIGSIZE) plot_hist2(flashers) despine(fig,trim=True) plt.suptitle("Flashers") fig = plt.figure(figsize=FIGSIZE) plot_hist2(muon,muons=True) despine(fig,trim=True) plt.suptitle("Muons") plt.show() sys.exit(0) # First, do basic data cleaning which is done for all events. ev = ev[ev.dc & (DC_JUNK | DC_CRATE_ISOTROPY | DC_QVNHIT | DC_FLASHER | DC_NECK | DC_ITC | DC_BREAKDOWN) == 0] # 00-orphan cut ev = ev[(ev.gtid & 0xff) != 0] print("number of events after data cleaning = %i" % np.count_nonzero(ev.prompt)) # Now, we select events tagged by the muon tag which should tag only # external muons. We keep the sample of muons since it's needed later to # identify Michel electrons and to apply the muon follower cut muons = ev[(ev.dc & DC_MUON) != 0] print("number of muons = %i" % len(muons)) # Try to identify Michel electrons. Currently, the event selection is based # on Richie's thesis. Here, we do the following: # # 1. Apply more data cleaning cuts to potential Michel electrons # 2. Nhit >= 100 # 3. It must be > 800 ns and less than 20 microseconds from a prompt event # or a muon michel = ev.groupby('run',group_keys=False).apply(michel_cut) print("number of michel events = %i" % len(michel)) # Tag atmospheric events. # # Note: We don't cut atmospheric events or muons yet because we still need # all the events in order to apply the muon follower cut. ev = ev.groupby('run',group_keys=False).apply(atmospheric_events) print("number of events after neutron follower cut = %i" % np.count_nonzero(ev.prompt & (~ev.atm))) # remove events 200 microseconds after a muon ev = ev.groupby('run',group_keys=False).apply(muon_follower_cut) # Get rid of muon events in our main event sample ev = ev[(ev.dc & DC_MUON) == 0] prompt = ev[ev.prompt & ~ev.atm] atm = ev[ev.atm] print("number of events after muon cut = %i" % len(prompt)) # Check to see if there are any events with missing fit information atm_ra = atm[['run','gtid']].to_records(index=False) muons_ra = muons[['run','gtid']].to_records(index=False) prompt_ra = prompt[['run','gtid']].to_records(index=False) michel_ra = michel[['run','gtid']].to_records(index=False) fits_ra = fits[['run','gtid']].to_records(index=False) if len(atm_ra) and np.count_nonzero(~np.isin(atm_ra,fits_ra)): print_warning("skipping %i atmospheric events because they are missing fit information!" % np.count_nonzero(~np.isin(atm_ra,fits_ra))) if len(muons_ra) and np.count_nonzero(~np.isin(muons_ra,fits_ra)): print_warning("skipping %i muon events because they are missing fit information!" % np.count_nonzero(~np.isin(muons_ra,fits_ra))) if len(prompt_ra) and np.count_nonzero(~np.isin(prompt_ra,fits_ra)): print_warning("skipping %i signal events because they are missing fit information!" % np.count_nonzero(~np.isin(prompt_ra,fits_ra))) if len(michel_ra) and np.count_nonzero(~np.isin(michel_ra,fits_ra)): print_warning("skipping %i Michel events because they are missing fit information!" % np.count_nonzero(~np.isin(michel_ra,fits_ra))) # Now, we merge the event info with the fitter info. # # Note: This means that the dataframe now contains multiple rows for each # event, one for each fit hypothesis. atm = pd.merge(fits,atm,how='inner',on=['run','gtid']) muons = pd.merge(fits,muons,how='inner',on=['run','gtid']) michel = pd.merge(fits,michel,how='inner',on=['run','gtid']) prompt = pd.merge(fits,prompt,how='inner',on=['run','gtid']) # get rid of events which don't have a fit nan = np.isnan(prompt.fmin.values) if np.count_nonzero(nan): print_warning("skipping %i signal events because the negative log likelihood is nan!" % len(prompt[nan].groupby(['run','gtid']))) prompt = prompt[~nan] nan_atm = np.isnan(atm.fmin.values) if np.count_nonzero(nan_atm): print_warning("skipping %i atmospheric events because the negative log likelihood is nan!" % len(atm[nan_atm].groupby(['run','gtid']))) atm = atm[~nan_atm] nan_muon = np.isnan(muons.fmin.values) if np.count_nonzero(nan_muon): print_warning("skipping %i muons because the negative log likelihood is nan!" % len(muons[nan_muon].groupby(['run','gtid']))) muons = muons[~nan_muon] nan_michel = np.isnan(michel.fmin.values) if np.count_nonzero(nan_michel): print_warning("skipping %i michel electron events because the negative log likelihood is nan!" % len(michel[nan_michel].groupby(['run','gtid']))) michel = michel[~nan_michel] # get the best fit prompt = prompt.sort_values('fmin').groupby(['run','gtid']).nth(0) atm = atm.sort_values('fmin').groupby(['run','gtid']).nth(0) michel_best_fit = michel.sort_values('fmin').groupby(['run','gtid']).nth(0) muon_best_fit = muons.sort_values('fmin').groupby(['run','gtid']).nth(0) muons = muons[muons.id == 22] # require r < 6 meters prompt = prompt[prompt.r_psup < 0.9] atm = atm[atm.r_psup < 0.9] print("number of events after radius cut = %i" % len(prompt)) # Note: Need to design and apply a psi based cut here fig = plt.figure(figsize=FIGSIZE) plot_hist2(prompt) despine(fig,trim=True) if args.save: plt.savefig("prompt.pdf") plt.savefig("prompt.eps") else: plt.suptitle("Without Neutron Follower") fig = plt.figure(figsize=FIGSIZE) plot_hist2(atm) despine(fig,trim=True) if args.save: plt.savefig("atm.pdf") plt.savefig("atm.eps") else: plt.suptitle("With Neutron Follower") fig = plt.figure(figsize=FIGSIZE) plot_hist2(michel_best_fit) despine(fig,trim=True) if args.save: plt.savefig("michel_electrons.pdf") plt.savefig("michel_electrons.eps") else: plt.suptitle("Michel Electrons") fig = plt.figure(figsize=FIGSIZE) plot_hist2(muon_best_fit,muons=True) despine(fig,trim=True) if len(muon_best_fit): plt.tight_layout() if args.save: plt.savefig("external_muons.pdf") plt.savefig("external_muons.eps") else: plt.suptitle("External Muons") # Plot the energy and angular distribution for external muons fig = plt.figure(figsize=FIGSIZE) plt.subplot(2,1,1) plt.hist(muons.ke.values, bins=np.logspace(3,7,100), histtype='step') plt.xlabel("Energy (MeV)") plt.gca().set_xscale("log") plt.subplot(2,1,2) plt.hist(np.cos(muons.theta.values), bins=np.linspace(-1,1,100), histtype='step') despine(fig,trim=True) plt.xlabel(r"$\cos(\theta)$") plt.tight_layout() if args.save: plt.savefig("muon_energy_cos_theta.pdf") plt.savefig("muon_energy_cos_theta.eps") else: plt.suptitle("Muons") # For the Michel energy plot, we only look at the single particle electron # fit michel = michel[michel.id == 20] stopping_muons = pd.merge(muons,michel,left_on=['run','gtid'],right_on=['run','muon_gtid'],suffixes=('','_michel')) if len(stopping_muons): # project muon to PSUP stopping_muons['dx'] = stopping_muons.apply(get_dx,axis=1) # energy based on distance travelled stopping_muons['T_dx'] = dx_to_energy(stopping_muons.dx) stopping_muons['dT'] = stopping_muons['energy1'] - stopping_muons['T_dx'] fig = plt.figure(figsize=FIGSIZE) plt.hist((stopping_muons['energy1']-stopping_muons['T_dx'])*100/stopping_muons['T_dx'], bins=np.linspace(-100,100,200), histtype='step') despine(fig,trim=True) plt.xlabel("Fractional energy difference (\%)") plt.title("Fractional energy difference for Stopping Muons") plt.tight_layout() if args.save: plt.savefig("stopping_muon_fractional_energy_difference.pdf") plt.savefig("stopping_muon_fractional_energy_difference.eps") else: plt.title("Stopping Muon Fractional Energy Difference") # 100 bins between 50 MeV and 10 GeV bins = np.arange(50,10000,1000) pd_bins = pd.cut(stopping_muons['energy1'],bins) T = (bins[1:] + bins[:-1])/2 dT = stopping_muons.groupby(pd_bins)['dT'].agg(['mean','sem','std',std_err,median,median_err,iqr_std,iqr_std_err]) fig = plt.figure(figsize=FIGSIZE) plt.errorbar(T,dT['median']*100/T,yerr=dT['median_err']*100/T) despine(fig,trim=True) plt.xlabel("Kinetic Energy (MeV)") plt.ylabel(r"Energy bias (\%)") plt.tight_layout() if args.save: plt.savefig("stopping_muon_energy_bias.pdf") plt.savefig("stopping_muon_energy_bias.eps") else: plt.title("Stopping Muon Energy Bias") fig = plt.figure(figsize=FIGSIZE) plt.errorbar(T,dT['iqr_std']*100/T,yerr=dT['iqr_std_err']*100/T) despine(fig,trim=True) plt.xlabel("Kinetic Energy (MeV)") plt.ylabel(r"Energy resolution (\%)") plt.tight_layout() if args.save: plt.savefig("stopping_muon_energy_resolution.pdf") plt.savefig("stopping_muon_energy_resolution.eps") else: plt.title("Stopping Muon Energy Resolution") fig = plt.figure(figsize=FIGSIZE) bins=np.linspace(0,100,100) plt.hist(michel.ke.values, bins=bins, histtype='step', label="Dark Matter Fitter") if michel.size: plt.hist(michel[~np.isnan(michel.rsp_energy.values)].rsp_energy.values, bins=np.linspace(20,100,100), histtype='step',label="RSP") x = np.linspace(0,100,1000) y = michel_spectrum(x) y /= np.trapz(y,x=x) N = len(michel) plt.plot(x, N*y*(bins[1]-bins[0]), ls='--', color='k', label="Michel Spectrum") despine(fig,trim=True) plt.xlabel("Energy (MeV)") plt.tight_layout() plt.legend() if args.save: plt.savefig("michel_electrons_ke.pdf") plt.savefig("michel_electrons_ke.eps") else: plt.title("Michel Electrons") plt.show()