-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.py
More file actions
2387 lines (2088 loc) · 89.6 KB
/
generator.py
File metadata and controls
2387 lines (2088 loc) · 89.6 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)
from mpl_toolkits.mplot3d import Axes3D
from scipy.integrate import solve_ivp
import matplotlib.patches as mpatches
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import time
import pickle
import multiprocessing
from matplotlib.animation import FuncAnimation, PillowWriter
import math
import ROOT
ROOT.gROOT.SetBatch(1)
ROOT.gStyle.SetOptFit(0)
ROOT.gStyle.SetOptStat(0)
# ROOT.gStyle.SetPalette(ROOT.kRust)
# ROOT.gStyle.SetPalette(ROOT.kSolar)
# ROOT.gStyle.SetPalette(ROOT.kInvertedDarkBodyRadiator)
ROOT.gStyle.SetPalette(ROOT.kDarkBodyRadiator)
# ROOT.gStyle.SetPalette(ROOT.kRainbow)
ROOT.gStyle.SetPadBottomMargin(0.15)
ROOT.gStyle.SetPadLeftMargin(0.13)
ROOT.gStyle.SetPadRightMargin(0.16)
ROOT.gStyle.SetGridColor(ROOT.kGray)
ROOT.gStyle.SetGridWidth(1)
import bremss as br
import argparse
parser = argparse.ArgumentParser(description='serial_analyzer.py...')
parser.add_argument('-mag', metavar='magnets settings (run 502 or run 490)', required=True, help='magnets settings (run 502 or run 490)')
parser.add_argument('-gen', metavar='particles to generate', required=True, help='particles to generate')
parser.add_argument('-acc', metavar='require full acceptance?', required=False, help='require full acceptance?')
parser.add_argument('-mlt', metavar='multi processing?', required=False, help='multi processing?')
parser.add_argument('-shw', metavar='show plots?', required=False, help='show plots?')
parser.add_argument('-gif', metavar='do gif?', required=False, help='do gif?')
argus = parser.parse_args()
MagnetsSettings = float(argus.mag)
magset = [502, 490.0,490.1,490.2,490.5]
if(MagnetsSettings not in magset):
print(f"Unsupported magnets settings run: {MagnetsSettings}")
quit()
Nparticles = int(argus.gen)
if(Nparticles<=0):
print(f"Unsupported Nparticles: {Nparticles}")
quit()
fullacc = True if(argus.acc is not None and argus.acc=="1") else False
mltprc = True if(argus.mlt is not None and argus.mlt=="1") else False
doshw = True if(argus.shw is not None and argus.shw=="1") else False
dogif = True if(argus.gif is not None and argus.gif=="1") else False
plt.rcParams['image.cmap'] = 'afmhot'
# plt.rcParams['image.cmap'] = 'copper'
plt.rcParams['text.usetex'] = True
# Convert units
m_to_cm = 1e2
m_to_mm = 1e3
m_to_um = 1e6
cm_to_mm = 1e1
cm_to_um = 1e4
cm_to_m = 1e-2
mm_to_m = 1e-3
mm_to_cm = 1e-1
mm_to_um = 1e3
um_to_mm = 1e-3
um_to_cm = 1e-4
um_to_m = 1e-6
kG_to_T = 0.1
GeV_to_kgms = 5.39e-19
GeV_to_kg = 1.8e-27
GeV_to_kgm2s2 = 1.6e-10
# Physical constants
c = 299792458 # speed of light in m/s
c2 = c*c
e = 1.602176634e-19 # elementary charge in C
m_e = 9.1093837015e-31 # electron/positron mass in kg
m_p = 1.67262192e-27 # proton/antiproton mass in kg
##################################
######### configurations #########
##################################
fx0 = 0*um_to_m ### TODO??? ### this is where the beam is shot from
fy0 = 0*um_to_m ### TODO??? ### this is where the beam is shot from
# fx0 = 0*um_to_m ### TODO??? ### this is where the beam is shot from
# fy0 = 0*um_to_m ### TODO??? ### this is where the beam is shot from
fz0 = -200*cm_to_m ### fixed, just has to be before the Be window ### this is where the beam is shot from
fsigmax = 50*um_to_m ## beam sigma
fsigmay = 50*um_to_m ## beam sigma
fsigmaz = 150*um_to_m ## beam sigma
zAL = +30 ### the aluminum foil, cm
zBe = -84 ### the beryllium window, cm
Z0 = zBe if(MagnetsSettings==502) else zAL
Z0_m = Z0*cm_to_m
MM = m_e ## kg, positron
QQ = +1 ## unit charge, positron
mGeV = (MM*c2)/GeV_to_kgm2s2 ## GeV
E_GeV = 10 # GeV, energy of primary partticles
Emin = 1e-2 #1 ## GeV
Emax = 10 ## GeV
smearT = False #True
smearP = True
smear_sigma_T_um = 0.03 ## um
smear_sigma_P_GeV = 1e-4 ## GeV
ZMAX = 18 ## METERES
tmax = ZMAX / (0.99 * c) ### time range for propagation (seconds): approximate time to travel 18 meters (last detector is at ~18 meters, relativistic particles going ~c)
t_span = (0, tmax)
max_dt = 1e-9
dy_det = 0 # cm
X0 = 35.3 if(MagnetsSettings==502) else 8.897 # cm for Beryllium of Aluminum
t_cm = 0.005 if(MagnetsSettings==502) else 0.01 # cm (50 or 100 µm)
E_vals, photons, eplus = br.build_pdfs(Emin,E_GeV,X0,t_cm)
rng = np.random.default_rng(123)
### magnets
magsetvals = {502:[-7.637,28.55,-7.637], 490.0:[-30.68,46.42,-30.68], 490.1:[-27.99,44.98,-27.99], 490.2:[-20.38,40.42,-20.38], 490.5:[-6.66,28.86,-6.66] }
magsetdelt = {"quad0":[0,0], "quad1":[0,0], "quad2":[0,0], "xcorr":[0,0], "dipole":[0,0]} ### x,y displacement, cm
# magsetangl = {"quad0":[0,0,0], "quad1":[0,0,0], "quad2":[0.004,0,0], "xcorr":[0,0,0], "dipole":[0,0,0]} ### 3D rotation, degrees
magsetangl = {"quad0":[0,0,0], "quad1":[0,0,0], "quad2":[0,0,0], "xcorr":[0,0,0], "dipole":[0,0,0]} ### 3D rotation, degrees
detangl = [0,0,0]
for name,angles in magsetangl.items():
for i in range(3):
angles[i] = angles[i]*np.pi/180.
for i in range(3):
detangl[i] = detangl[i]*np.pi/180.
##################################
##################################
##################################
### chip
npix_x = 1024
npix_y = 512
pix_x = 0.02924
pix_y = 0.02688
chipXmm = npix_x*pix_x
chipYmm = npix_y*pix_y
chipXcm = chipXmm*mm_to_cm
chipYcm = chipYmm*mm_to_cm
chipXm = chipXmm*mm_to_m
chipYm = chipYmm*mm_to_m
pix_x_nbins = npix_x+1
pix_x_min = -0.5
pix_x_max = npix_x+0.5
pix_y_nbins = npix_y+1
pix_y_min = -0.5
pix_y_max = npix_y+0.5
rebin2D = 12
rebin2D_mid = 4
hPixelMatrix1 = ROOT.TH1D("h_pix1",";Pixel;Hits",npix_x*npix_y,1,npix_x*npix_y+1)
hPixelMatrix2 = ROOT.TH2D("h_pix2",";pixel-x;pixel-y;Hits",pix_x_nbins,pix_x_min,pix_x_max, pix_y_nbins,pix_y_min,pix_y_max)
hPixelMatrix1_middle = ROOT.TH1D("h_pix1_middle",";Pixel;Hits",int(npix_x/rebin2D_mid)*int(npix_y/rebin2D_mid),1,int(npix_x/rebin2D_mid)*int(npix_y/rebin2D_mid)+1)
hPixelMatrix2_middle = ROOT.TH2D("h_pix2_middle",";pixel-x;pixel-y;Hits",int(npix_x/rebin2D_mid)+1,pix_x_min,pix_x_max, int(npix_y/rebin2D_mid)+1,pix_y_min,pix_y_max)
hPixelMatrix1_coarse = ROOT.TH1D("h_pix1_coarse",";Pixel;Hits",int(npix_x/rebin2D)*int(npix_y/rebin2D),1,int(npix_x/rebin2D)*int(npix_y/rebin2D)+1)
hPixelMatrix2_coarse = ROOT.TH2D("h_pix2_coarse",";pixel-x;pixel-y;Hits",int(npix_x/rebin2D)+1,pix_x_min,pix_x_max, int(npix_y/rebin2D)+1,pix_y_min,pix_y_max)
hPz_full = ROOT.TH1D("hPz_full", ";p_{z} [GeV];Particles",100,0,10)
hPz_small = ROOT.TH1D("hPz_small",";p_{z} [GeV];Particles",50,1.5,4.5)
hPz_zoom = ROOT.TH1D("hPz_zoom", ";p_{z} [GeV];Particles",40,1.5,3.5)
# Define detector x range
# detector_x_center_cm = -1.0 # cm
detector_x_center_cm = 0. # cm
detector_x_center_m = detector_x_center_cm*cm_to_m
# Define detector y range
detector_y_center_cm = 5.165 + 0.1525 + 3.685 + dy_det # cm
detector_y_center_m = detector_y_center_cm*cm_to_m
# Calculate detector z position
detector_z_base_cm = 1363 + 303.2155 + 11.43 + 1.05 # cm
detector_z_base_m = detector_z_base_cm*cm_to_m
detector_z_base_mm = detector_z_base_cm*cm_to_mm
def spot_cut(x,y,xcent,ycent,xrad,yrad):
CX = xcent
CY = ycent
RX = xrad
RY = yrad
X = (x-CX)/RX
Y = (y-CY)/RY
X2 = X*X
Y2 = Y*Y
if( (X2+Y2)>1. ): return False
return True
def Rot3D(u,thetax=0,thetay=0,thetaz=0):
Rx = [[1,0,0],[0,math.cos(thetax),-math.sin(thetax)], [0,math.sin(thetax),math.cos(thetax)]]
Ry = [[math.cos(thetay),0,math.sin(thetay)], [0,1,0], [-math.sin(thetay),0,math.cos(thetay)]]
Rz = [[math.cos(thetaz),math.sin(thetaz),0], [-math.sin(thetaz),math.cos(thetaz),0], [0,0,1]]
### rotate around x
vx = [0,0,0]
vx[0] = Rx[0][0]*u[0]+Rx[0][1]*u[1]+Rx[0][2]*u[2]
vx[1] = Rx[1][0]*u[0]+Rx[1][1]*u[1]+Rx[1][2]*u[2]
vx[2] = Rx[2][0]*u[0]+Rx[2][1]*u[1]+Rx[2][2]*u[2]
### rotate around y
vy = [0,0,0]
vy[0] = Ry[0][0]*vx[0]+Ry[0][1]*vx[1]+Ry[0][2]*vx[2]
vy[1] = Ry[1][0]*vx[0]+Ry[1][1]*vx[1]+Ry[1][2]*vx[2]
vy[2] = Ry[2][0]*vx[0]+Ry[2][1]*vx[1]+Ry[2][2]*vx[2]
### rotate around z
vz = [0,0,0]
vz[0] = Rz[0][0]*vy[0]+Rz[0][1]*vy[1]+Rz[0][2]*vy[2]
vz[1] = Rz[1][0]*vy[0]+Rz[1][1]*vy[1]+Rz[1][2]*vy[2]
vz[2] = Rz[2][0]*vy[0]+Rz[2][1]*vy[1]+Rz[2][2]*vy[2]
### result
return vz
# Define magnet elements
class Element:
def __init__(self, name, x_min, x_max, y_min, y_max, z_min, z_max, angles=[]):
self.name = name
self.x_min = x_min * cm_to_m
self.x_max = x_max * cm_to_m
self.y_min = y_min * cm_to_m
self.y_max = y_max * cm_to_m
self.z_min = z_min * cm_to_m
self.z_max = z_max * cm_to_m
self.hits = []
if(len(angles)==3):
umin = [self.x_min,self.y_min,self.z_min]
umax = [self.x_max,self.y_max,self.z_max]
vmin = Rot3D(umin,thetax=angles[0],thetay=angles[1],thetaz=angles[2])
vmax = Rot3D(umax,thetax=angles[0],thetay=angles[1],thetaz=angles[2])
self.x_min = vmin[0]
self.y_min = vmin[1]
self.z_min = vmin[2]
self.x_max = vmax[0]
self.y_max = vmax[1]
self.z_max = vmax[2]
def is_inside(self, x, y, z):
return (self.x_min <= x <= self.x_max and
self.y_min <= y <= self.y_max and
self.z_min <= z <= self.z_max)
def get_vertices(self):
vertices = np.array([
[self.x_min, self.y_min, self.z_min],
[self.x_max, self.y_min, self.z_min],
[self.x_max, self.y_max, self.z_min],
[self.x_min, self.y_max, self.z_min],
[self.x_min, self.y_min, self.z_max],
[self.x_max, self.y_min, self.z_max],
[self.x_max, self.y_max, self.z_max],
[self.x_min, self.y_max, self.z_max]
])
return vertices
def record_hit(self, particle_id, x, y, z, px, py, pz):
self.hits.append({
'particle_id': particle_id,
'x': x, 'y': y, 'z': z,
'px': px, 'py': py, 'pz': pz
})
def plot_element(self, ax, col, alpha=0.2):
vertices = self.get_vertices()
# List of sides' vertices
faces = [
[vertices[0], vertices[1], vertices[2], vertices[3]], # Bottom face
[vertices[4], vertices[5], vertices[6], vertices[7]], # Top face
[vertices[0], vertices[1], vertices[5], vertices[4]], # Front face
[vertices[2], vertices[3], vertices[7], vertices[6]], # Back face
[vertices[1], vertices[2], vertices[6], vertices[5]], # Right face
[vertices[0], vertices[3], vertices[7], vertices[4]] # Left face
]
# Plot sides
for face in faces:
face = np.array(face)
ax.plot_surface(
face[:, 0].reshape(2, 2),
face[:, 1].reshape(2, 2),
face[:, 2].reshape(2, 2),
color=col, alpha=alpha
)
class Dipole(Element):
def __init__(self, name, x_min, x_max, y_min, y_max, z_min, z_max, B_x,B_y,B_z, angles=[]):
super().__init__(name, x_min, x_max, y_min, y_max, z_min, z_max, angles)
self.name = name
self.B_x = B_x # Tesla
self.B_y = B_y # Tesla
self.B_z = B_z # Tesla
# self.hits = []
self.angles = angles
if(len(self.angles)==3):
uB = [self.B_x,self.B_y,self.B_z]
vB = Rot3D(uB,thetax=self.angles[0],thetay=self.angles[1],thetaz=self.angles[2])
self.B_x = vB[0]
self.B_y = vB[1]
self.B_z = vB[2]
def field(self, x, y, z):
if self.is_inside(x, y, z):
return np.array([self.B_x, self.B_y, self.B_z])
else:
return np.array([0, 0, 0])
class Quadrupole(Element):
def __init__(self, name, x_min, x_max, y_min, y_max, z_min, z_max, gradient, angles=[]):
super().__init__(name, x_min, x_max, y_min, y_max, z_min, z_max, angles)
self.name = name
self.gradient = gradient * kG_to_T # Tesla/m
# self.hits = []
self.angles = angles
def field(self, x, y, z):
if self.is_inside(x, y, z):
### calculate the center of the magnet volume
x_center = (self.x_min + self.x_max) / 2
y_center = (self.y_min + self.y_max) / 2
### field relative to the magnetic center
B_x = self.gradient * (y - y_center)
B_y = self.gradient * (x - x_center)
B_z = 0
if(len(self.angles)==3):
uB = [B_x,B_y,0]
vB = Rot3D(uB,thetax=self.angles[0],thetay=self.angles[1],thetaz=self.angles[2])
B_x = vB[0]
B_y = vB[1]
B_z = vB[2]
return np.array([B_x, B_y, B_z])
else:
return np.array([0, 0, 0])
class Detector(Element):
def __init__(self, name, x_min, x_max, y_min, y_max, z_min, z_max, angles=[]):
super().__init__(name, x_min, x_max, y_min, y_max, z_min, z_max, angles)
self.name = name
self.z_pos = z_min * cm_to_m
# self.hits = [] # To store particle hits
self.angles = angles
def field(self, x, y, z):
# Detectors don't generate magnetic fields
return np.array([0, 0, 0])
def plot_element(self, ax, col, alpha=0.4):
# Override to plot as a thin rectangular plane
vertices = self.get_vertices()
# Create a rectangular plane
x = [vertices[0][0], vertices[1][0], vertices[2][0], vertices[3][0], vertices[4][0]]
y = [vertices[0][1], vertices[1][1], vertices[2][1], vertices[3][1], vertices[4][1]]
z = [vertices[0][2], vertices[1][2], vertices[2][2], vertices[3][2], vertices[4][2]]
L1verts = []
L1verts.append( np.array([ [x[0],y[0],z[0]],
[x[1],y[1],z[1]],
[x[2],y[2],z[2]],
[x[3],y[3],z[3]] ]) )
ax.add_collection3d(Poly3DCollection(L1verts, facecolors=col, linewidths=0.5, edgecolors=col, alpha=.20))
def print_hits(self,initial_states):
if not self.hits:
print(f"Detector at z={self.z_pos:.2f} m: No hits recorded")
return
print(f"Detector at z={self.z_pos:.2f} m hits:")
for hit in self.hits:
pid = hit['particle_id']
xx = hit['x']
yy = hit['y']
pz = initial_states[pid][5]/GeV_to_kgms
print(f" Particle {pid}: x={xx:.6f} m, y={yy:.6f} m (pz={pz:.2f} GeV)")
class Beampipe(Element):
def __init__(self, name, inner_radius_cm, outer_radius_cm, z_min_cm, z_max_cm, angles=[]):
# For bounding box, use outer radius to define x,y limits
super().__init__(name, -outer_radius_cm, outer_radius_cm,
-outer_radius_cm, outer_radius_cm,
z_min_cm, z_max_cm, angles)
self.name = name
self.inner_radius = inner_radius_cm * cm_to_m
self.outer_radius = outer_radius_cm * cm_to_m
self.z_min_pipe = z_min_cm * cm_to_m
self.z_max_pipe = z_max_cm * cm_to_m
# self.hits = []
def field(self, x, y, z):
# Beampipe doesn't generate magnetic fields
return np.array([0, 0, 0])
def is_inside_pipe_material(self, x, y, z):
"""Check if point is inside the pipe material (between inner and outer radius)"""
if not (self.z_min_pipe <= z <= self.z_max_pipe):
return False
r = np.sqrt(x**2 + y**2)
return self.inner_radius <= r <= self.outer_radius
def is_outside_vacuum(self, x, y, z):
"""Check if point is outside the vacuum region (beyond inner radius)"""
if not (self.z_min_pipe <= z <= self.z_max_pipe):
return False
r = np.sqrt(x**2 + y**2)
return r > self.inner_radius
def plot_element(self, ax, color='gray', alpha=0.3):
"""Plot beampipe as a semi-transparent cylinder"""
# Create cylindrical surface
z_pipe = np.linspace(self.z_min_pipe, self.z_max_pipe, 50)
theta = np.linspace(0, 2*np.pi, 50)
# Create meshgrid for outer surface
Z_outer, THETA_outer = np.meshgrid(z_pipe, theta)
X_outer = self.outer_radius * np.cos(THETA_outer)
Y_outer = self.outer_radius * np.sin(THETA_outer)
# Create meshgrid for inner surface
X_inner = self.inner_radius * np.cos(THETA_outer)
Y_inner = self.inner_radius * np.sin(THETA_outer)
# Plot outer surface
ax.plot_surface(X_outer, Y_outer, Z_outer,
color=color, alpha=alpha, linewidth=0)
# Plot inner surface (slightly more transparent)
ax.plot_surface(X_inner, Y_inner, Z_outer,
color=color, alpha=alpha*0.5, linewidth=0)
# Add end caps
r_cap = np.linspace(self.inner_radius, self.outer_radius, 20)
theta_cap = np.linspace(0, 2*np.pi, 50)
R_cap, THETA_cap = np.meshgrid(r_cap, theta_cap)
X_cap = R_cap * np.cos(THETA_cap)
Y_cap = R_cap * np.sin(THETA_cap)
# Front cap
Z_cap_front = np.full_like(X_cap, self.z_min_pipe)
ax.plot_surface(X_cap, Y_cap, Z_cap_front,
color=color, alpha=alpha, linewidth=0)
# Back cap
Z_cap_back = np.full_like(X_cap, self.z_max_pipe)
ax.plot_surface(X_cap, Y_cap, Z_cap_back,
color=color, alpha=alpha, linewidth=0)
########################################################################
########################################################################
def GenerateGaussianBeam(E_GeV,mass_GeV,charge,mks=False):
fbeamfocus = 0
lf = E_GeV/mass_GeV
femittancex = 50e-3*mm_to_m/lf ### mm-rad
femittancey = 50e-3*mm_to_m/lf ### mm-rad
fbetax = (fsigmax**2)/femittancex
fbetay = (fsigmay**2)/femittancey
### z
z0 = np.random.normal(fz0,fsigmaz)
zdrift = z0 - fbeamfocus ### correct drift distance for x, y distribution. Forces the beam to pass through the IP (i.e. focuesd at z=0)
### x
sigmax = fsigmax * np.sqrt(1.0 + (zdrift/fbetax)**2)
x0 = np.random.normal(fx0, sigmax)
meandx = x0*zdrift / (zdrift**2 + fbetax**2)
sigmadx = np.sqrt( femittancex*fbetax / (zdrift**2 + fbetax**2) )
dx0 = np.random.normal(meandx, sigmadx)
### y
sigmay = fsigmay * np.sqrt(1.0 + (zdrift/fbetay)**2)
y0 = np.random.normal(fy0, sigmay)
meandy = y0*zdrift / (zdrift**2 + fbetay**2)
sigmady = np.sqrt( femittancey*fbetay / (zdrift**2 + fbetay**2) )
dy0 = np.random.normal(meandy, sigmady)
### p
pz = np.sqrt( (E_GeV**2 - mass_GeV**2)/ (dx0**2 + dy0**2 + 1.0) )
px = dx0*pz
py = dy0*pz
pz0 = pz*GeV_to_kgms # kg*m/s
px0 = px*GeV_to_kgms # kg*m/s
py0 = py*GeV_to_kgms # kg*m/s
mass_kg = mass_GeV*GeV_to_kgm2s2/c2 # kg
### state
state_mks = [x0,y0,z0, px0,py0,pz0, mass_kg,charge] ### [x[m],y[m],z[m], px[kg*m/s],py[kg*m/s],pz[kg*m/s], m[kg],q[unit]]
state_nat = [x0,y0,z0, px,py,pz, mass_GeV,charge] ### [x[m],y[m],z[m], px[GeV],py[GeV],pz[GeV], m[GeV],q[unit]]
return state_mks if(mks) else state_nat
def propagate_state_in_vacuum_to_z(state, z):
if(z==state[2]): return state
x0 = state[0]
y0 = state[1]
z0 = state[2]
px = state[3]
py = state[4]
pz = state[5]
m = state[6]
q = state[7]
pxz = np.sqrt(px**2 + pz**2)
pyz = np.sqrt(py**2 + pz**2)
thetax = np.arcsin(px/pxz)
thetay = np.arcsin(py/pyz)
x = x0 + np.tan(thetax)*(z-z0)
y = y0 + np.tan(thetay)*(z-z0)
state_at_z = [x,y,z, px,py,pz, m,q]
return state_at_z
# def truncated_exp_NK(a,b,how_many=1):
# a = -np.log(a)
# b = -np.log(b)
# rands = np.exp(-(np.random.rand(how_many)*(b-a) + a))
# return rands[0] if(how_many==1) else rands
def truncated_exp_NK(aa, bb, slope=1.0, how_many=1):
'''
Sample from a power-law-like distribution between [aa, bb], with controllable slope.
slope=1 -> exp distribution
slope<1 -> shallower (power-law)
slope>1 -> steeper (power-law)
'''
aa, bb = float(aa), float(bb)
if slope == 1:
r = np.random.rand(how_many)
samples = np.exp(-(r * (-np.log(bb) + np.log(aa)) - np.log(aa)))
else:
r = np.random.rand(how_many)
samples = ((bb**(1-slope) - aa**(1-slope)) * r + aa**(1-slope))**(1/(1-slope))
return samples[0] if how_many == 1 else samples
def simulate_secondary_production(primary_state,q=+1,Emin=0.5,Emax=5,smear_T=False,smear_pT=False):
x = primary_state[0]
y = primary_state[1]
z = primary_state[2]
px = primary_state[3]
py = primary_state[4]
pz = primary_state[5]
mass = primary_state[6]
### smear trasverse position
if(smear_T):
x = x + np.random.normal(0,smear_sigma_T_um*um_to_m)
y = y + np.random.normal(0,smear_sigma_T_um*um_to_m)
### smear trasverse momenta
if(smear_pT):
px = px + np.random.normal(0,smear_sigma_P_GeV)
py = py + np.random.normal(0,smear_sigma_P_GeV)
### sample energy from exponential
# E = truncated_exp_NK(Emin,Emax,slope=0.3) if(Emax>Emin) else Emin # GeV
E = br.sample_from_pdf_on_bins(E_vals, eplus, nsamples=1, rng=rng)
while(E[0]<Emin or E[0]>Emax): E = br.sample_from_pdf_on_bins(E_vals, eplus, nsamples=1, rng=rng)
E = E[0]
### assume the x-y momemnta staty the same and correct the z momentum
pz = np.sqrt( E**2 - mass**2 - px**2 - py**2 ) # GeV
secondary_state = [x,y,z, px,py,pz, mass, q]
return secondary_state
def state_GeV_to_kgms(state):
state_mks = [0]*len(state)
state_mks[0] = state[0]
state_mks[1] = state[1]
state_mks[2] = state[2]
state_mks[3] = state[3]*GeV_to_kgms # kg*m/s
state_mks[4] = state[4]*GeV_to_kgms # kg*m/s
state_mks[5] = state[5]*GeV_to_kgms # kg*m/s
state_mks[6] = state[6]*GeV_to_kgm2s2/c2 # kg
state_mks[7] = state[7]
return state_mks
########################################################################
########################################################################
# Create the detector objects
detectors = []
for i in range(5):
zpos = detector_z_base_cm + i ### detectors are spaced by 1 cm
detector = Detector(
name=f"ALPIDE_{i}",
x_min=detector_x_center_cm-chipYcm/2., x_max=detector_x_center_cm+chipYcm/2.,
y_min=detector_y_center_cm-chipXcm/2., y_max=detector_y_center_cm+chipXcm/2.,
z_min=zpos, z_max=zpos, ### 0 width...
angles=detangl
)
detectors.append(detector)
# Create magnetic elements
quad0 = Quadrupole(
name="quad0",
x_min=-2.4610+magsetdelt["quad0"][0], x_max=2.4610+magsetdelt["quad0"][0], # cm
y_min=-2.4610+magsetdelt["quad0"][1], y_max=2.4610+magsetdelt["quad0"][1], # cm
z_min=367.33336, z_max=464.6664, # cm
gradient=magsetvals[MagnetsSettings][0], # kG/m
angles=magsetangl["quad0"]
)
quad1 = Quadrupole(
name="quad1",
x_min=-2.4610+magsetdelt["quad1"][0], x_max=2.4610+magsetdelt["quad1"][0], # cm
y_min=-2.4610+magsetdelt["quad1"][1], y_max=2.4610+magsetdelt["quad1"][1], # cm
z_min=590.3336, z_max=687.6664, # cm
# gradient=+28.55 if(MagnetsSettings==502) else +46.42 # kG/m
gradient=magsetvals[MagnetsSettings][1], # kG/m
angles=magsetangl["quad1"]
)
quad2 = Quadrupole(
name="quad2",
x_min=-2.4610+magsetdelt["quad2"][0], x_max=2.4610+magsetdelt["quad2"][0], # cm
y_min=-2.4610+magsetdelt["quad2"][1], y_max=2.4610+magsetdelt["quad2"][1], # cm
z_min=812.3336, z_max=909.6664, # cm
gradient=magsetvals[MagnetsSettings][2], # kG/m
angles=magsetangl["quad2"]
)
xcorr = Dipole(
name="xcorr",
x_min=-10.795+magsetdelt["xcorr"][0], x_max=+10.795+magsetdelt["xcorr"][0],
y_min=-4.6990+magsetdelt["xcorr"][1], y_max=+4.6990+magsetdelt["xcorr"][1],
z_min=987.779, z_max=1011.15,
B_x=0, B_y=+0.026107, B_z=0, # Tesla
angles=magsetangl["xcorr"]
)
dipole = Dipole(
name="dipole",
x_min=-2.2352+magsetdelt["dipole"][0], x_max=2.2352+magsetdelt["dipole"][0],
y_min=-6.6927+magsetdelt["dipole"][1], y_max=3.4927+magsetdelt["dipole"][1],
z_min=1260.34, z_max=1351.78,
B_x=0.219, B_y=0, B_z=0, # Tesla
angles=magsetangl["dipole"]
)
flange = Element(
name="flange",
x_min=-2.2352, x_max=2.2352,
y_min=-6.3752, y_max=3.1752,
z_min=1377.784, z_max=1377.785
)
# Create beampipe from z=0 to entrance of dipole:
beampipe_inner_radius_cm = 2. # 2 cm inner radius
beampipe_outer_radius_cm = 2.2 # 2.2 cm outer radius
beampipe_z_start_cm = 0.0 # Start at IP
beampipe_z_end_cm = dipole.z_min * m_to_cm - 0.0 # End 0 cm before dipole entrance
beampipe = Beampipe(
name="beampipe",
inner_radius_cm=beampipe_inner_radius_cm,
outer_radius_cm=beampipe_outer_radius_cm,
z_min_cm=beampipe_z_start_cm,
z_max_cm=beampipe_z_end_cm,
)
### collect all elements
magnets = [quad0, quad1, quad2, xcorr, dipole]
elements = magnets + [flange] + [beampipe] + detectors
# for element in elements:
# if(element.name=="beampipe"): continue
# print(f"{element.name}: angles={element.angles}")
########################################################################
########################################################################
########################################################################
### linear mapping from real space to pixel space
def real_to_pixel_coords(x_real, y_real, xmin, xmax, ymin, ymax):
xpixelmin = 0
xpixelmax = npix_y-1
nxpixels = npix_y
ypixelmin = 0
ypixelmax = npix_x-1
nypixels = npix_x
x_real = np.asarray(x_real)
y_real = np.asarray(y_real)
x_pixel = xpixelmin + (x_real - xmin) * (xpixelmax - xpixelmin) / (xmax - xmin)
y_pixel = ypixelmin + (y_real - ymin) * (ypixelmax - ypixelmin) / (ymax - ymin)
return x_pixel, y_pixel
### convert to integer indices and clip to valid range
def real_to_pixel_indices(x_real, y_real, xmin, xmax, ymin, ymax):
xpixelmin = 0
xpixelmax = npix_y-1
nxpixels = npix_y
ypixelmin = 0
ypixelmax = npix_x-1
nypixels = npix_x
x_pixel, y_pixel = real_to_pixel_coords(x_real, y_real, xmin, xmax, ymin, ymax)
x_indices = np.clip(np.round(x_pixel).astype(int), xpixelmin, xpixelmax-1)
y_indices = np.clip(np.round(y_pixel).astype(int), ypixelmin, ypixelmax-1)
return x_indices, y_indices
### transform to EUDAQ space
def transform_pixel_indices(x_indices, y_indices, rotate_90_cw=True, mirror_x=True, flip_y=True):
xpixelmin = 0
xpixelmax = npix_y-1
nxpixels = npix_y
ypixelmin = 0
ypixelmax = npix_x-1
nypixels = npix_x
x_trans = x_indices.copy()
y_trans = y_indices.copy()
# step 1: Rotate 90 degrees clockwise (x,y) -> (y, -x)
# After rotation: new_x = y, new_y = max_x - x
if(rotate_90_cw):
temp_x = y_trans.copy()
temp_y = (xpixelmax - 1) - x_trans
x_trans = temp_x
y_trans = temp_y
# Update pixel boundaries after rotation (dimensions swap)
xpixelmin, xpixelmax, nxpixels, ypixelmin, ypixelmax, nypixels = \
ypixelmin, ypixelmax, nypixels, xpixelmin, xpixelmax, nxpixels
# # step 2: mirror x-axis around its center
# if(mirror_x):
# x_center = (xpixelmin + xpixelmax - 1) / 2
# x_trans = 2 * x_center - x_trans
# x_trans = np.clip(x_trans, xpixelmin, xpixelmax - 1).astype(int)
# # step 3: flip y-axis around its center
# if(flip_y):
# y_center = (ypixelmin + ypixelmax) / 2
# y_trans = 2 * y_center - y_trans
# y_trans = np.clip(y_trans, ypixelmin, ypixelmax).astype(int)
return x_trans, y_trans
def hist2d_to_1d_root_style(hist2d_result,transform=True):
counts, xedges, yedges, image = hist2d_result
nbinsx, nbinsy = counts.shape
bin_numbers = []
occupancy_counts = []
for i in range(nbinsx): # X bins (rows)
for j in range(nbinsy): # Y bins (columns) - inner loop
# ROOT-style global bin number: ny * binx + biny
# ROOT bins are 1-indexed, but we'll use 0-indexed for simplicity
global_bin = nbinsy * i + j
occupancy = counts[i, j]
bin_numbers.append(global_bin)
occupancy_counts.append(occupancy)
return np.array(bin_numbers), np.array(occupancy_counts)
########################################################################
########################################################################
########################################################################
# To calculate total magnetic field at a point
def total_field(position):
x, y, z = position
field = np.zeros(3)
# for element in elements: field += element.field(x, y, z)
for magnet in magnets: field += magnet.field(x, y, z)
return field
def record_hits(element,z_element,trajectory,particle_id):
for i in range(len(trajectory.t) - 1):
z1, z2 = trajectory.y[2][i], trajectory.y[2][i+1]
# If particle trajectory crosses the detector plane
if (z1 <= z_element <= z2) or (z2 <= z_element <= z1):
# Linear interpolation to find position at detector plane
t1, t2 = trajectory.t[i], trajectory.t[i+1]
fraction = (z_element - z1) / (z2 - z1) if z2 != z1 else 0
t_hit = t1 + fraction * (t2 - t1)
x_hit = trajectory.y[0][i] + fraction * (trajectory.y[0][i+1] - trajectory.y[0][i])
y_hit = trajectory.y[1][i] + fraction * (trajectory.y[1][i+1] - trajectory.y[1][i])
px_hit = trajectory.y[3][i] + fraction * (trajectory.y[3][i+1] - trajectory.y[3][i])
py_hit = trajectory.y[4][i] + fraction * (trajectory.y[4][i+1] - trajectory.y[4][i])
pz_hit = trajectory.y[5][i] + fraction * (trajectory.y[5][i+1] - trajectory.y[5][i])
# Check if hit is within detector surface
if (element.x_min <= x_hit <= element.x_max and element.y_min <= y_hit <= element.y_max):
element.record_hit(particle_id, x_hit, y_hit, z_element, px_hit, py_hit, pz_hit)
# Define the equations of motion for a charged particle in a magnetic field
def particle_motion(t, state):
### state vector: [x[m],y[m],z[m], px[kg*m/s],py[kg*m/s],pz[kg*m/s], m[kg],q[unit]]
x,y,z, px,py,pz, m,q = state
q = int(q)
dm_dt = 0
dq_dt = 0
position = np.array([x, y, z])
momentum = np.array([px, py, pz])
### relativistic velocity
p_mag = np.linalg.norm(momentum)
gamma = np.sqrt(1 + (p_mag/(m*c))**2) ### relativistic factor
velocity = momentum / (gamma * m)
# Rate of change of position is velocity
dx_dt = velocity[0]
dy_dt = velocity[1]
dz_dt = velocity[2]
### magnetic field at current position
B = total_field(position)
if(np.linalg.norm(B)<1e-6): return [dx_dt,dy_dt,dz_dt, 0,0,0, dm_dt,dq_dt]
### lorentz force: F = q(v × B)
force = (q * e) * np.cross(velocity, B)
### rate of change of momentum is force
dpx_dt = force[0]
dpy_dt = force[1]
dpz_dt = force[2]
# print(f"t={t:.2e}, r={x:.2e},{y:.2e},{z:.2e}, p={px:.2e},{py:.2e},{pz:.2e}, p={p_mag:.2e}, gam={gamma:.2e}, v={velocity[0]:.2e},{velocity[1]:.2e},{velocity[2]:.2e}, m={m:.2e}, q={q:}, B={B[0]:.2e},{B[1]:.2e},{B[2]:.2e}, dr/dt={dx_dt:.2e},{dy_dt:.2e},{dz_dt:.2e}, dp_dt={dpx_dt:.2e},{dpy_dt:.2e},{dpz_dt:.2e}")
return [dx_dt,dy_dt,dz_dt, dpx_dt,dpy_dt,dpz_dt, dm_dt,dq_dt]
# Add this function to replace your existing collision_event function
def collision_event(t, state, elements_to_check=None, beampipe=None):
'''
Event function to detect when a particle hits walls of magnet elements or beampipe.
Returns zero when a collision occurs.
Parameters:
-----------
t : float
Current time value
state : array
Current state [x,y,z, px,py,pz, m,q]
elements_to_check : list, optional
List of elements to check for collisions
beampipe : Beampipe, optional
Beampipe object to check for collisions
Returns:
--------
float
Distance from nearest wall (negative inside boundaries, zero at boundary, positive outside)
'''
if elements_to_check is None:
elements_to_check = [quad0, quad1, quad2, xcorr, dipole]
x, y, z = state[0], state[1], state[2]
# Initialize distance to a large value
min_distance = float('inf')
# Check beampipe collision first (most restrictive)
if beampipe is not None and beampipe.z_min_pipe <= z <= beampipe.z_max_pipe:
r = np.sqrt(x**2 + y**2)
# Distance to inner wall of beampipe (negative if outside vacuum)
distance_to_vacuum_boundary = beampipe.inner_radius - r
min_distance = min(min_distance, distance_to_vacuum_boundary)
# Check magnet element collisions
for element in elements_to_check:
### skip if not in z-range of element (with small margin)
if(not (element.z_min - 0.0001 <= z <= element.z_max + 0.0001)): continue
# Calculate distances to each wall
dx_min = x - element.x_min
dx_max = element.x_max - x
dy_min = y - element.y_min
dy_max = element.y_max - y
# Find minimum distance to wall
distances = [dx_min, dx_max, dy_min, dy_max]
element_min_distance = min(distances)
# Update minimum distance if this element's wall is closer
min_distance = min(min_distance, element_min_distance)
# If not near any element, return a large positive value
if min_distance == float('inf'):
return 1.0
return min_distance
# Set terminal attribute
collision_event.terminal = True
def propagate_particle_with_collision(particle_id, initial_state, t_span, beampipe=None, max_step=1e-10):
'''
Propagate particle through beamline with collision detection including beampipe.
Parameters:
-----------
particle_id : int, Unique identifier for the particle
initial_state : array, Initial state [x0,y0,z0, px0,py0,pz0, m,q]
t_span : tuple, (t_start, t_end) for integration
beampipe : Beampipe, optional, Beampipe object for collision detection
max_step : float, optional, Maximum step size for integrator
Returns:
--------
solution : OdeSolution
Solution object from solve_ivp
collision_info : dict or None
Information about collision if it occurred, None otherwise
'''
# Use solve_ivp with event detection including beampipe
solution = solve_ivp(
particle_motion,
t_span,
initial_state,
method='RK45',
events=lambda t, state: collision_event(t, state, beampipe=beampipe),
max_step=max_step,
rtol=1e-8,
atol=1e-10
)
# Check for detector crossings
for det in detectors: record_hits(det, det.z_pos, solution, particle_id)
# Record hits on other elements
# record_hits(flange, flange.z_min, solution, particle_id)
record_hits(flange, flange.z_max, solution, particle_id)
# record_hits(dipole, dipole.z_min, solution, particle_id)
record_hits(dipole, dipole.z_max, solution, particle_id)
# record_hits(xcorr, xcorr.z_min, solution, particle_id)
record_hits(xcorr, xcorr.z_max, solution, particle_id)
# record_hits(quad0, quad0.z_min, solution, particle_id)
record_hits(quad0, quad0.z_max, solution, particle_id)
# record_hits(quad1, quad1.z_min, solution, particle_id)
record_hits(quad1, quad1.z_max, solution, particle_id)
# record_hits(quad2, quad2.z_min, solution, particle_id)
record_hits(quad2, quad2.z_max, solution, particle_id)
# Record beampipe hits if it exists
if beampipe is not None: record_hits(beampipe, beampipe.z_max_pipe, solution, particle_id)
# Check if collision occurred
collision_info = None
if solution.t_events[0].size > 0:
# Collision occurred
collision_time = solution.t_events[0][0]
collision_state = np.array([
np.interp(collision_time, solution.t, solution.y[0]),
np.interp(collision_time, solution.t, solution.y[1]),
np.interp(collision_time, solution.t, solution.y[2]),
np.interp(collision_time, solution.t, solution.y[3]),
np.interp(collision_time, solution.t, solution.y[4]),
np.interp(collision_time, solution.t, solution.y[5])
])
# Determine which element was hit
collision_element = None
element_name = "unknown"
# Check if beampipe was hit first
if (beampipe is not None and
beampipe.z_min_pipe <= collision_state[2] <= beampipe.z_max_pipe):
r = np.sqrt(collision_state[0]**2 + collision_state[1]**2)
if abs(r - beampipe.inner_radius) < 1e-6:
collision_element = beampipe
element_name = "Beampipe"
# If not beampipe, check other elements
if collision_element is None:
for element in [quad0, quad1, quad2, xcorr, dipole]:
if (element.z_min <= collision_state[2] <= element.z_max):
if (abs(collision_state[0] - element.x_min) < 1e-6 or
abs(collision_state[0] - element.x_max) < 1e-6 or
abs(collision_state[1] - element.y_min) < 1e-6 or
abs(collision_state[1] - element.y_max) < 1e-6):
collision_element = element
break
if collision_element == quad0: element_name = "Quadrupole 0"
elif collision_element == quad1: element_name = "Quadrupole 1"
elif collision_element == quad2: element_name = "Quadrupole 2"
elif collision_element == xcorr: element_name = "Xcorr"
elif collision_element == dipole: element_name = "Dipole"
elif collision_element == flange: element_name = "Flange"
collision_info = {
"time": collision_time,
"position": collision_state[:3],
"momentum": collision_state[3:],
"element": element_name
}
return solution, collision_info
def get_state_at_z(solution, collision, z_target, check_collision=False):
### check if there is NO collision first: