summaryrefslogtreecommitdiffstats
path: root/tof_mc.py
blob: 2316c3c5f496201f802e2cc0be7c213829d3c8a7 (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
# tol-mc.py
# Monte-Carlo Simulation of a basic muon time-of-flight experiment
# @author: bryan newbold
# @email: bnewbold@mit.edu
# @date: oct 2006

from pylab import *;
from scipy import *;

# default number of tries to run...
max_tries = 10**2

# default geometry
h = 100.0 # cm
h_err = 1.0 # cm

Tw = 15.5*2.54 # inches->cm
Tw_err = .5*2.54
Tl = 23.5*2.54
Tl_err = 1.*2.54
Tpmtl = 19.*2.54
Tpmtl_err = 1.*2.54

Bw = 42.
Bw_err = 4./10 # mm->cm
Bl = 53.
Bl_err = 1.
Bpmtl = 20.
Bpmtl_err = 1.

n_scint = 1.5 # index of refraction of scintillators
C_ = 2.99792458*10**10 # speed of light in cm

# shortcuts to random number generators
ur = lambda: rand();
gr = lambda: randn();

aTx = lambda: ur()*Tl
aTy = lambda: ur()*Tw
#aphi = lambda: arccos( sqrt(ur()))
aomega = lambda: ur()*2*pi
aBx = lambda x,p,o,h: x+h*sin(o)*tan(p)
aBy = lambda y,p,o,h: y+h*cos(o)*tan(p)
#aP = lambda p: 100.*cos(p)
aP = lambda p,mc: ((mc/2.99) + gr() * 0.02) * C_
aTime = lambda x,y,pmt,w: n_scint/(C_)*sqrt((x+pmt)**2 + (w/2 - y)**2) 

if not vars().has_key('phi_table'):
    phi_table = zeros((1000,1),typecode='f')
    for i in frange(0., pi/2,0.00001):
        m = (2*i + sin(2*i))/pi
        phi_table[int(1000*(m - (m%.001)))] = i
    phi_table[-1] = pi/2

def aphi():
    n = ur();
    return phi_table[int(1000*(n-(n%.001)))][0];

def run(tries=max_tries, h=h, h_err=h_err,printstuff=True,mean_c=2.93):
    num_events=0;
    if(printstuff): print "Going to make %d tries..." % tries
    events=zeros((tries,7),typecode='f')
    while tries>0:
        tries = tries-1;
        Tx,Ty,phi,omega=aTx(),aTy(),aphi(),aomega();
        Bx = aBx(Tx,phi,omega,h)
        if((Bx < 0.) or (Bx > Bl)):
            continue;
        By = aBy(Ty + abs(Tw-Bw)/2,phi,omega,h)
        if((By < 0.) or (By > Bw)):
            continue;
        P = aP(phi,mean_c)
        dL = (h/cos(phi)); 
        dT = -1 *aTime(Tx,Ty + abs(Tw-Bw)/2,Tpmtl,Tw) \
             + aTime(Bx,By,Bpmtl,Bw) \
             + dL/P; 
        events[num_events] = (Tx,Ty,Bx,By,P,dT,dL);
        num_events = num_events +1;
    if num_events>0:
        if(printstuff): print "... %d valid events!" % num_events;
        return events[0:num_events];
    else:
        if(printstuff): print "No valid events!"
        return [];

def plot_events(events, xres=16,yres=16):
    if(size(events[0]) != 7):
        print "Passed matrix is no good...";
        return;
    figure();
    # TOP part
    subplot(211);
    x = arange(0.,Tl,Tl/xres);
    y = arange(0.,Tw,Tw/yres);
    X,Y = meshgrid(x,y);
    Z = zeros((xres,yres));
    for i in events:
        Z[int(i[1] * yres/Tw),int(i[0] * xres/Tl)] +=1;
    contourf(X,Y,Z);
    title("Distribution on Top Paddle (counts per %.3g cm^2)" \
        % (Tl/xres * Tw/yres));
    xlabel("Paddle Length (%g cm +/- %g cm)" % (Tl,Tl_err));
    ylabel("Paddle Width (%g cm +/- %g cm)" % (Tw,Tw_err));
    colorbar();

    # BOTTOM part
    subplot(212);
    x = arange(0.,Bl,Bl/xres);
    y = arange(0.,Bw,Bw/yres);
    X,Y = meshgrid(x,y);
    Z = zeros((xres,yres));
    for i in events:
        Z[int(i[3] * yres/Bw),int(i[2] * xres/Bl)] +=1;
    contourf(X,Y,Z);
    title("Distribution on Bottom Paddle (counts per %.3g cm^2)" \
        % (Bl/xres * Tw/yres));
    xlabel("Paddle Length (%g cm +/- %g)" % (Bl,Bl_err));
    ylabel("Paddle Width (%g cm +/- %g cm)" % (Bw,Bw_err));
    colorbar();

def plot_events_3d(events):
    if(size(events[0] != 6)):
        print "Passed matrix is no good...";
        return;
    figure();
    return;

def plot_deltaT_h(heights=frange(33.,233,50.),num_events=1000,err=3,c=2.93):
    
    points = zeros((size(heights),6),typecode='f');
    points[:,0] = list(heights[:]);
    times = frange((int(err)));
    dL = frange((int(err)));
    actP = frange((int(err)));
    for i in points:
        for r in range(0,size(times)):
            events = run(int(num_events),h=i[0],printstuff=False,mean_c=c);
            times[int(r)] = mean(events[:,5]);
            dL[int(r)] = mean(events[:,6]);
            actP[int(r)] = mean(events[:,4]);
        i[1] = mean(times);
        i[2] = std(times);
        i[3] = mean(dL);
        i[4] = mean(actP)
        i[5] = std(actP)
    
    stuff = fittodata_linear(points[:,0],points[:,1],[1.,1.],err=points[:,2],ret_all=True)
    plotfit(stuff)
    v = stuff['params']
    ax = gca()
    title("Change in delta-T with average h");
    xlabel("Average h in cm");
    ylabel("Average delta-T");
    txt = text(0.65,.22,"delta-T/h: %g \noffset: %g \nmean muon speed: %g cm/s\nmonte carlo input speed:%g +/- %g cm/s" 
            % (v[0],v[1],1/v[0],mean(points[:,4]),mean(points[:,5])), 
            horizontalalignment='center',
            verticalalignment='center',
            transform = ax.transAxes)
    

    stuff = fittodata_linear(points[:,3],points[:,1],[1.,1.],err=points[:,2],ret_all=True)
    plotfit(stuff)
    vc = stuff['params']
    ax=gca()
    title('Change in mean delta-T with change in mean L')
    xlabel('Mean Length of flight')
    ylabel('Mean time gap between events')
    txt = text(0.65,.22,"delta-T/h: %g \noffset: %g \nmean muon speed: %g cm/s\nmean muon speed corrected: %g cm/s\nmonte carlo input speed:%g +/- %g cm/s" 
            % (v[0],v[1],1/v[0],1/vc[0],mean(points[:,4]),mean(points[:,5])), 
            horizontalalignment='center',
            verticalalignment='center',
            transform = ax.transAxes)

def plot_L_vs_h(heights=r_[18.5:218.5:8.],num_events=400,err=2,c=2.93):
    points = zeros((size(heights),5),typecode='f');
    
    for i in range(0,size(heights)):
        points[i,0] = heights[i];

    times = r_[0.:int(err)];
    dL = r_[0.:int(err)];
    for i in range(0,size(heights)):
        for r in range(0,size(times)):
            events = run(int(num_events),h=points[i,0],printstuff=False,mean_c=c);
            times[int(r)] = mean(events[:,5]);
            dL[int(r)] = mean(events[:,6]);
        points[i,1] = mean(times);
        points[i,2] = std(times);
        points[i,3] = mean(dL);
        points[i,4] = std(dL);

    x = points[:,0].tolist(); x = array(x)
    y = points[:,3].tolist(); y = array(y)
    err = points[:,4].tolist(); err = array(err)

    plotfit(fittodata_linear(x,y,[3.,-1.],err=err,ret_all=True))
    
    title("Change in mean L with h");
    xlabel("h in cm");
    ylabel("Mean L");
    figure();
    plot(x,y-x);
    return (x,y,err);