aboutsummaryrefslogtreecommitdiff
path: root/utils/plot
blob: 8fd2fae04b1d9e86d645e1cd08ead424953205da (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
#!/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
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

    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 open(filename) as f:
            data = yaml.load(f.read())

        dx = []
        dy = []
        dz = []
        dT = []
        thetas = []
        likelihood_ratio = []
        t_electron = []
        t_muon = []
        psi = []
        for event in data['data']:
            # get the particle ID
            id = event['mcgn'][0]['id']

            if 'ev' not in event:
                continue

            if id not in event['ev'][0]['fit']:
                continue

            fit = event['ev'][0]['fit']

            mass = SNOMAN_MASS[id]
            # for some reason it's the *second* track which seems to contain the
            # initial energy
            true_energy = event['mcgn'][0]['energy']
            # The MCTK bank has the particle's total energy (except for neutrons)
            # so we need to convert it into kinetic energy
            ke = true_energy - mass
            energy = fit[id]['energy']
            dT.append(energy-ke)
            true_posx = event['mcgn'][0]['posx']
            posx = fit[id]['posx']
            dx.append(posx-true_posx)
            true_posy = event['mcgn'][0]['posy']
            posy = fit[id]['posy']
            dy.append(posy-true_posy)
            true_posz = event['mcgn'][0]['posz']
            posz = fit[id]['posz']
            dz.append(posz-true_posz)
            dirx = event['mcgn'][0]['dirx']
            diry = event['mcgn'][0]['diry']
            dirz = event['mcgn'][0]['dirz']
            true_dir = [dirx,diry,dirz]
            true_dir = np.array(true_dir)/np.linalg.norm(true_dir)
            theta = fit[id]['theta']
            phi = fit[id]['phi']
            dir = [np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi),np.cos(theta)]
            dir = np.array(dir)/np.linalg.norm(dir)
            thetas.append(np.degrees(np.arccos(np.dot(true_dir,dir))))
            if IDP_E_MINUS in fit and IDP_MU_MINUS in fit:
                fmin_electron = fit[IDP_E_MINUS]['fmin']
                fmin_muon = fit[IDP_MU_MINUS]['fmin']
                likelihood_ratio.append(fmin_muon-fmin_electron)
            if IDP_E_MINUS in fit:
                t_electron.append(fit[IDP_E_MINUS]['time'])
            if IDP_MU_MINUS in fit:
                t_muon.append(fit[IDP_MU_MINUS]['time'])

            if 'nhit' in event['ev'][0]:
                nhit = event['ev'][0]['nhit']
                psi.append(fit[id]['psi']/nhit)

        if len(t_electron) < 2 or len(t_muon) < 2:
            continue

        mean, mean_error, std, std_error = get_stats(dT)
        print("dT      = %.2g +/- %.2g" % (mean, mean_error))
        print("std(dT) = %.2g +/- %.2g" % (std, std_error))
        mean, mean_error, std, std_error = get_stats(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(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(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(thetas)
        print("std(theta) = %4.2g +/- %.2g" % (std, std_error))

        plt.figure(1)
        plot_hist(dT, label=filename)
        plt.xlabel("Kinetic Energy difference (MeV)")
        plt.figure(2)
        plot_hist(dx, label=filename)
        plt.xlabel("X Position difference (cm)")
        plt.figure(3)
        plot_hist(dy, label=filename)
        plt.xlabel("Y Position difference (cm)")
        plt.figure(4)
        plot_hist(dz, label=filename)
        plt.xlabel("Z Position difference (cm)")
        plt.figure(5)
        plot_hist(thetas, label=filename)
        plt.xlabel(r"$\theta$ (deg)")
        plt.figure(6)
        plot_hist(likelihood_ratio, label=filename)
        plt.xlabel(r"Log Likelihood Ratio ($e/\mu$)")
        plt.figure(7)
        plot_hist(np.array(t_electron)/1e3/60.0, label=filename)
        plt.xlabel(r"Electron Fit time (minutes)")
        plt.figure(8)
        plot_hist(np.array(t_muon)/1e3/60.0, label=filename)
        plt.xlabel(r"Muon Fit time (minutes)")
        if len(psi):
            plt.figure(9)
            plot_hist(psi, 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)
    if len(psi):
        plot_legend(9)
    plt.show()
e=np.float32) def interleave(arr, bits): """ Interleave the bits of quantized three-dimensional points in space. Example >>> interleave(np.identity(3, dtype=np.int)) array([4, 2, 1], dtype=uint64) """ if len(arr.shape) != 2 or arr.shape[1] != 3: raise Exception('shape mismatch') z = np.zeros(arr.shape[0], dtype=np.uint64) for i in range(bits): z |= (arr[:,2] & 1 << i) << (2*i) | \ (arr[:,1] & 1 << i) << (2*i+1) | \ (arr[:,0] & 1 << i) << (2*i+2) return z def morton_order(mesh, bits): """ Return a list of zvalues for triangles in `mesh` by interleaving the bits of the quantized center coordinates of each triangle. Each coordinate axis is quantized into 2**bits bins. """ lower_bound, upper_bound = mesh.get_bounds() if bits <= 0 or bits > 21: raise Exception('number of bits must be in the range (0,21].') max_value = 2**bits - 1 def quantize(x): return np.uint64((x-lower_bound)*max_value/(upper_bound-lower_bound)) mean_positions = quantize(np.mean(mesh.assemble(), axis=1)) return interleave(mean_positions, bits) class Geometry(object): def __init__(self): self.solids = [] self.solid_rotations = [] self.solid_displacements = [] def add_solid(self, solid, rotation=np.identity(3), displacement=(0,0,0)): """ Add the solid `solid` to the geometry. When building the final triangle mesh, `solid` will be placed by rotating it with the rotation matrix `rotation` and displacing it by the vector `displacement`. """ rotation = np.asarray(rotation, dtype=np.float32) if rotation.shape != (3,3): raise ValueError('rotation matrix has the wrong shape.') self.solid_rotations.append(rotation.astype(np.float32)) displacement = np.asarray(displacement, dtype=np.float32) if displacement.shape != (3,): raise ValueError('displacement vector has the wrong shape.') self.solid_displacements.append(displacement) self.solids.append(solid) return len(self.solids)-1 @timeit def build(self, bits=8, shift=3, use_cache=True): """ Build the bounding volume hierarchy, material/surface code arrays, and color array for this geometry. If the bounding volume hierarchy is cached, load the cache instead of rebuilding, else build and cache it. Args: - bits: int, *optional* The number of bits to quantize each linear dimension with when morton ordering the triangle centers for building the bounding volume hierarchy. Defaults to 8. - shift: int, *optional* The number of bits to shift the zvalue of each node when building the next layer of the bounding volume hierarchy. Defaults to 3. - use_cache: bool, *optional* If true, the on-disk cache in ~/.chroma/ will be checked for a previously built version of this geometry, otherwise the BVH will be computed and saved to the cache. If false, the cache is ignored and also not updated. """ nv = np.cumsum([0] + [len(solid.mesh.vertices) for solid in self.solids]) nt = np.cumsum([0] + [len(solid.mesh.triangles) for solid in self.solids]) vertices = np.empty((nv[-1],3), dtype=np.float32) triangles = np.empty((nt[-1],3), dtype=np.uint32) for i, solid in enumerate(self.solids): vertices[nv[i]:nv[i+1]] = \ np.inner(solid.mesh.vertices, self.solid_rotations[i]) + self.solid_displacements[i] triangles[nt[i]:nt[i+1]] = solid.mesh.triangles + nv[i] self.mesh = Mesh(vertices, triangles) self.colors = np.concatenate([solid.color for solid in self.solids]) self.solid_id = np.concatenate([np.fromiter(repeat(i, len(solid.mesh.triangles)), dtype=np.uint32) for i, solid in enumerate(self.solids)]) self.unique_materials = list(np.unique(np.concatenate([solid.unique_materials for solid in self.solids]))) material_lookup = dict(zip(self.unique_materials, range(len(self.unique_materials)))) self.material1_index = np.fromiter(imap(material_lookup.get, chain(*[solid.material1 for solid in self.solids])), dtype=np.int32) self.material2_index = np.fromiter(imap(material_lookup.get, chain(*[solid.material2 for solid in self.solids])), dtype=np.int32) self.unique_surfaces = list(np.unique(np.concatenate([solid.unique_surfaces for solid in self.solids]))) surface_lookup = dict(zip(self.unique_surfaces, range(len(self.unique_surfaces)))) self.surface_index = np.fromiter(imap(surface_lookup.get, chain(*[solid.surface for solid in self.solids])), dtype=np.int32) try: self.surface_index[self.surface_index == surface_lookup[None]] = -1 except KeyError: pass checksum = md5(str(bits)) checksum.update(str(shift)) checksum.update(self.mesh.vertices) checksum.update(self.mesh.triangles) cache_dir = os.path.expanduser('~/.chroma') cache_file = checksum.hexdigest() cache_path = os.path.join(cache_dir, cache_file) if use_cache: try: f = gzip.GzipFile(cache_path, 'rb') except IOError: pass else: print 'loading cache.' data = pickle.load(f) reorder = data.pop('reorder') self.mesh.triangles = self.mesh.triangles[reorder] self.material1_index = self.material1_index[reorder] self.material2_index = self.material2_index[reorder] self.surface_index = self.surface_index[reorder] self.colors = self.colors[reorder] self.solid_id = self.solid_id[reorder] for key, value in data.iteritems(): setattr(self, key, value) f.close() return zvalues_mesh = morton_order(self.mesh, bits) reorder = np.argsort(zvalues_mesh) zvalues_mesh = zvalues_mesh[reorder] if (np.diff(zvalues_mesh) < 0).any(): raise Exception('zvalues_mesh out of order.') self.mesh.triangles = self.mesh.triangles[reorder] self.material1_index = self.material1_index[reorder] self.material2_index = self.material2_index[reorder] self.surface_index = self.surface_index[reorder] self.colors = self.colors[reorder] self.solid_id = self.solid_id[reorder] unique_zvalues = np.unique(zvalues_mesh) self.lower_bounds = np.empty((unique_zvalues.size,3), dtype=np.float32) self.upper_bounds = np.empty((unique_zvalues.size,3), dtype=np.float32) assembled_mesh = self.mesh.assemble(group=False) self.node_map = np.searchsorted(zvalues_mesh, unique_zvalues) self.node_map_end = np.searchsorted(zvalues_mesh, unique_zvalues, side='right') for i, (zi1, zi2) in enumerate(izip(self.node_map, self.node_map_end)): self.lower_bounds[i] = assembled_mesh[zi1*3:zi2*3].min(axis=0) self.upper_bounds[i] = assembled_mesh[zi1*3:zi2*3].max(axis=0) self.layers = np.zeros(unique_zvalues.size, dtype=np.uint32) self.first_node = unique_zvalues.size begin_last_layer = 0 for layer in count(1): bit_shifted_zvalues = unique_zvalues >> shift unique_zvalues = np.unique(bit_shifted_zvalues) i0 = begin_last_layer + bit_shifted_zvalues.size self.node_map.resize(self.node_map.size+unique_zvalues.size) self.node_map[i0:] = np.searchsorted(bit_shifted_zvalues, unique_zvalues) + begin_last_layer self.node_map_end.resize(self.node_map_end.size+unique_zvalues.size) self.node_map_end[i0:] = np.searchsorted(bit_shifted_zvalues, unique_zvalues, side='right') + begin_last_layer self.layers.resize(self.layers.size+unique_zvalues.size) self.layers[i0:] = layer self.lower_bounds.resize((self.lower_bounds.shape[0]+unique_zvalues.size,3)) self.upper_bounds.resize((self.upper_bounds.shape[0]+unique_zvalues.size,3)) for i, zi1, zi2 in izip(count(i0), self.node_map[i0:], self.node_map_end[i0:]): self.lower_bounds[i] = self.lower_bounds[zi1:zi2].min(axis=0) self.upper_bounds[i] = self.upper_bounds[zi1:zi2].max(axis=0) begin_last_layer += bit_shifted_zvalues.size if unique_zvalues.size == 1: break if use_cache: print >>sys.stderr, 'Writing BVH to cache directory...' if not os.path.exists(cache_dir): os.makedirs(cache_dir) with gzip.GzipFile(cache_path, 'wb', compresslevel=1) as f: data = {} for key in ['lower_bounds', 'upper_bounds', 'node_map', 'node_map_end', 'layers', 'first_node']: data[key] = getattr(self, key) data['reorder'] = reorder pickle.dump(data, f, -1)