-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbeam.py
More file actions
2511 lines (1965 loc) · 104 KB
/
Copy pathbeam.py
File metadata and controls
2511 lines (1965 loc) · 104 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
# This file is part of ABEL
# Copyright 2025, The ABEL Authors
# Authors: C.A.Lindstrøm(1), J.B.B.Chen(1), O.G.Finnerud(1), D.Kalvik(1), E.Hørlyk(1), A.Huebl(2), K.N.Sjobak(1), E.Adli(1)
# Affiliations: 1) University of Oslo, 2) LBNL
# License: GPL-3.0-or-later
import numpy as np
import openpmd_api as io
import copy, warnings, os
import scipy.constants as SI
import scipy.sparse as sp
from scipy.spatial.transform import Rotation as Rot
from datetime import datetime
from pytz import timezone
from types import SimpleNamespace
from matplotlib import pyplot as plt
from abel.CONFIG import CONFIG
from abel.utilities.relativity import energy2proper_velocity, proper_velocity2energy, momentum2proper_velocity, proper_velocity2momentum, proper_velocity2gamma, energy2gamma, gamma2momentum
from abel.utilities.statistics import weighted_mean, weighted_std, weighted_cov
from abel.utilities.plasma_physics import k_p, wave_breaking_field, beta_matched
from abel.physics_models.hills_equation import evolve_hills_equation_analytic
from abel.physics_models.betatron_motion import evolve_betatron_motion
class Beam():
def __init__(self, phasespace=None, num_particles=1000, num_bunches_in_train=1, bunch_separation=0.0, allow_low_energy_particles=True, particle_mass=SI.m_e):
# check the inputs
if num_particles < 1 or not isinstance(num_particles, int):
raise ValueError('num_particles must be an integer larger than 1.')
if num_bunches_in_train < 1 or not isinstance(num_bunches_in_train, int):
raise ValueError('num_bunches_in_train cannot be lower than 1.')
if bunch_separation < 0.0:
raise ValueError('bunch_separation cannot be negative.')
# the phase space variable is private
if phasespace is not None:
self.__phasespace = phasespace
else:
self.__phasespace = self.reset_phase_space(num_particles)
# bunch pattern information
self.num_bunches_in_train = num_bunches_in_train
self.bunch_separation = bunch_separation # [s]
self.trackable_number = -1 # will increase to 0 after first tracking element
self.stage_number = 0
self.location = 0
self.particle_mass = particle_mass
self.allow_low_energy_particles = allow_low_energy_particles # Flag for allowing particles to have low energies.
# reset phase space
def reset_phase_space(self, num_particles):
if num_particles < 1 or not isinstance(num_particles, int):
raise ValueError('num_particles must be an integer larger than 1.')
self.__phasespace = np.zeros((11, num_particles))
# filter out macroparticles based on a mask (true means delete)
def __delitem__(self, indices):
if hasattr(indices, 'len'):
if len(indices) == len(self):
indices = np.where(indices)
self.__phasespace = np.ascontiguousarray(np.delete(self.__phasespace, indices, 1))
# filter out nans
def remove_nans(self):
del self[np.isnan(self).any(axis=1)]
# set phase space
def set_phase_space(self, Q, xs, ys, zs, uxs=None, uys=None, uzs=None, pxs=None, pys=None, pzs=None, xps=None, yps=None, Es=None, spxs=None, spys=None, spzs=None, weightings=None, particle_mass=SI.m_e):
"""
Set the phase space of the beam. All input arrays must have the same
lengths.
Parameters
----------
Q : [C] float
Total beam charge.
xs, ys, zs : [m] 1D float ndarray
Coordinates for the macroparticles.
uxs, uys, uzs : [m/s] 1D float ndarray, optional
Proper velocities for the macroparticles. All uzs values must be
above 10*particle rest energy/c/particle mass. Default set to
``None``.
pxs, pys, pzs : [kg m/s] 1D float ndarray, optional
Momenta for the macroparticles. All pzs values must be above
10*particle rest energy/c. Default set to ``None``.
xps, yps : [rad] 1D float ndarray, optional
Angles dx/ds and dy/ds for the macroparticles. Default set to
``None``.
Es : [eV] 1D float ndarray, optional
Energies for the macroparticles. All values must be above
10*particle rest energy. Default set to ``None``.
weightings : 1D float ndarray, optional
Weights for the macroparticles. Default set to ``None``.
particle_mass : [kg] float, optional
Particle mass for a single real particle. Default set to ``SI.m_e``.
Returns
----------
``None``
"""
# Check coordinate type and length
if not isinstance(xs, np.ndarray) or not isinstance(ys, np.ndarray) or not isinstance(zs, np.ndarray):
raise TypeError('Incompatible input type.')
num_particles = len(xs)
if len(ys) != num_particles or len(zs) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
# Check proper velocity type and length
if uxs is not None:
if not isinstance(uxs, np.ndarray):
raise TypeError('Incompatible input type.')
if len(uxs) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
if uys is not None:
if not isinstance(uys, np.ndarray):
raise TypeError('Incompatible input type.')
if len(uys) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
if uzs is not None:
if not isinstance(uzs, np.ndarray):
raise TypeError('Incompatible input type.')
if len(uzs) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
# Check momentum type and length
if pxs is not None:
if not isinstance(pxs, np.ndarray):
raise TypeError('Incompatible input type.')
if len(pxs) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
if pys is not None:
if not isinstance(pys, np.ndarray):
raise TypeError('Incompatible input type.')
if len(pys) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
if pzs is not None:
if not isinstance(pzs, np.ndarray):
raise TypeError('Incompatible input type.')
if len(pzs) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
# Check angle type and length
if xps is not None:
if not isinstance(xps, np.ndarray):
raise TypeError('Incompatible input type.')
if len(xps) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
if yps is not None:
if not isinstance(yps, np.ndarray):
raise TypeError('Incompatible input type.')
if len(yps) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
# Check energy type and length
if Es is not None:
if not isinstance(Es, np.ndarray):
raise TypeError('Incompatible input type.')
if len(Es) != num_particles:
raise ValueError('The input arrays must have the same lengths.')
# Prevent defining proper velocity, momentum or angle in the same direction
if uxs is not None and pxs is not None:
raise ValueError('Cannot define proper velocity and momentum in the same direction.')
if uxs is not None and xps is not None:
raise ValueError('Cannot define proper velocity and angle in the same direction.')
if pxs is not None and xps is not None:
raise ValueError('Cannot define momentum and angle in the same direction.')
if uys is not None and pys is not None:
raise ValueError('Cannot define proper velocity and momentum in the same direction.')
if uys is not None and yps is not None:
raise ValueError('Cannot define proper velocity and angle in the same direction.')
if pys is not None and yps is not None:
raise ValueError('Cannot define momentum and angle in the same direction.')
if uzs is not None and pzs is not None:
raise ValueError('Cannot define proper velocity and momentum in the same direction.')
if uzs is not None and Es is not None:
raise ValueError('Cannot set both uzs and Es.')
if pzs is not None and Es is not None:
raise ValueError('Cannot set both pzs and Es.')
if particle_mass is not None and particle_mass < 0:
raise ValueError('Particle mass cannot be negative.')
# make empty phase space
self.reset_phase_space(num_particles)
# add positions
self.set_xs(xs)
self.set_ys(ys)
self.set_zs(zs)
# minimum thresholds for energy, uz and pz
energy_thres = 10*particle_mass*SI.c**2/SI.e # [eV], 10 * particle rest energy. Gives beta=0.995.
uz_thres = energy2proper_velocity(energy_thres, unit='eV', m=particle_mass)
pz_thres = gamma2momentum(energy2gamma(energy_thres, unit='eV', m=particle_mass))
# add momenta
if uzs is None:
if pzs is not None:
if np.any(pzs < pz_thres):
if not self.allow_low_energy_particles:
raise ValueError('Beam pzs contains values that are too small.')
else:
warnings.warn('Beam pzs contains values that are too small.\n', UserWarning)
uzs = momentum2proper_velocity(pzs)
elif Es is not None:
if np.any(Es < energy_thres):
if not self.allow_low_energy_particles:
raise ValueError('Beam Es contains values that are too small.')
else:
warnings.warn('Beam Es contains values that are too small.\n', UserWarning)
uzs = energy2proper_velocity(Es)
else:
if np.any(uzs < uz_thres):
if not self.allow_low_energy_particles:
raise ValueError('Beam uzs contains values that are too small.')
else:
warnings.warn('Beam uzs contains values that are too small.\n', UserWarning)
self.__phasespace[5,:] = uzs
if uxs is None:
if pxs is not None:
uxs = momentum2proper_velocity(pxs)
elif xps is not None:
uxs = xps * uzs
self.__phasespace[3,:] = uxs
if uys is None:
if pys is not None:
uys = momentum2proper_velocity(pys)
elif yps is not None:
uys = yps * uzs
self.__phasespace[4,:] = uys
# charge
if weightings is None:
self.__phasespace[6,:] = Q/num_particles
else:
if np.any(weightings < 0):
raise ValueError('Beam weightings cannot be negative.')
self.__phasespace[6,:] = Q*weightings/np.sum(weightings)
# ids
self.__phasespace[7,:] = np.arange(num_particles)
# add spins
if spxs is None:
spxs = np.zeros(num_particles)
self.__phasespace[8,:] = spxs
if spys is None:
spys = np.zeros(num_particles)
self.__phasespace[9,:] = spys
if spzs is None:
spzs = np.zeros(num_particles)
self.__phasespace[10,:] = spzs
# single particle mass [kg]
self.particle_mass = particle_mass
# addition operator (add two beams using the + operator)
def __add__(self, beam):
return Beam(phasespace = np.append(self.__phasespace, beam.__phasespace, axis=1))
# in-place addition operator (add one beam to another using the += operator)
def __iadd__(self, beam):
if beam is not None:
self.__phasespace = np.append(self.__phasespace, beam.__phasespace, axis=1)
return self
# indexing operator (get single particle out)
def __getitem__(self, index):
return self.__phasespace[:,index]
# "length" operator (number of macroparticles)
def __len__(self):
return self.__phasespace.shape[1]
# string operator (called when printing)
def __str__(self):
if np.sum(self.weightings()) == 0.0:
return f"Beam: {len(self)} macroparticles, {self.charge()*1e9:.2f} nC"
else:
return f"Beam: {len(self)} macroparticles, {self.charge()*1e9:.2f} nC, {self.energy()/1e9:.2f} GeV"
## BUNCH PATTERN
def bunch_frequency(self) -> float:
if self.num_bunches_in_train == 1:
return None
elif self.bunch_separation == 0.0:
return None
else:
return 1/self.bunch_separation
def train_duration(self) -> float:
if self.num_bunches_in_train == 1:
return 0.0
elif self.bunch_separation == 0.0:
return None
else:
return self.bunch_separation * (self.num_bunches_in_train-1)
def average_current_train(self) -> float:
return self.charge()*self.bunch_frequency()
## BEAM ARRAYS
# get phase space variables
def xs(self):
return self.__phasespace[0,:]
def ys(self):
return self.__phasespace[1,:]
def zs(self):
return self.__phasespace[2,:]
def uxs(self):
return self.__phasespace[3,:]
def uys(self):
return self.__phasespace[4,:]
def uzs(self):
return self.__phasespace[5,:]
def qs(self):
return self.__phasespace[6,:]
def ids(self):
return self.__phasespace[7,:]
def spxs(self):
return self.__phasespace[8,:]
def spys(self):
return self.__phasespace[9,:]
def spzs(self):
return self.__phasespace[10,:]
# set phase space variables
def set_xs(self, xs):
self.__phasespace[0,:] = xs
def set_ys(self, ys):
self.__phasespace[1,:] = ys
def set_zs(self, zs):
self.__phasespace[2,:] = zs
def set_uxs(self, uxs):
self.__phasespace[3,:] = uxs
def set_uys(self, uys):
self.__phasespace[4,:] = uys
def set_uzs(self, uzs):
energy_thres = 10*self.particle_mass*SI.c**2/SI.e # [eV], 10 * particle rest energy. Gives beta=0.995.
uz_thres = energy2proper_velocity(energy_thres, unit='eV', m=self.particle_mass)
if np.any(uzs < uz_thres):
if not self.allow_low_energy_particles:
raise ValueError('Beam uzs contains values that are too small.')
else:
warnings.warn('Beam uzs contains values that are too small.\n', UserWarning)
self.__phasespace[5,:] = uzs
def set_xps(self, xps):
self.set_uxs(xps*self.uzs())
def set_yps(self, yps):
self.set_uys(yps*self.uzs())
def set_Es(self, Es):
energy_thres = 10*self.particle_mass*SI.c**2/SI.e # [eV], 10 * particle rest energy. Gives beta=0.995.
if np.any(Es < energy_thres):
if not self.allow_low_energy_particles:
raise ValueError('Beam Es contains values that are too small.')
else:
warnings.warn('Beam Es contains values that are too small.\n', UserWarning)
self.set_uzs(energy2proper_velocity(Es))
def set_qs(self, qs):
self.__phasespace[6,:] = qs
def set_ids(self, ids):
self.__phasespace[7,:] = ids
def set_spxs(self, spxs):
self.__phasespace[8,:] = spxs
def set_spys(self, spys):
self.__phasespace[9,:] = spys
def set_spzs(self, spzs):
self.__phasespace[10,:] = spzs
def weightings(self):
return self.__phasespace[6,:]/(self.charge_sign()*SI.e)
# copy another beam's macroparticle charge
def copy_particle_charge(self, beam):
if beam.__phasespace is None or self.__phasespace is None:
raise ValueError('One of the beams is empty.')
self.set_qs(np.median(beam.qs()))
def scale_charge(self, Q):
self.set_qs((Q/self.charge())*self.qs())
def scale_energy(self, E):
self.set_Es((E/self.energy())*self.Es())
def rs(self):
return np.sqrt(self.xs()**2 + self.ys()**2)
def pxs(self):
return proper_velocity2momentum(self.uxs(), m=self.particle_mass)
def pys(self):
return proper_velocity2momentum(self.uys(), m=self.particle_mass)
def pzs(self):
return proper_velocity2momentum(self.uzs(), m=self.particle_mass)
def xps(self):
return self.uxs()/self.uzs()
def yps(self):
return self.uys()/self.uzs()
def gammas(self):
return proper_velocity2gamma(self.uzs())
def Es(self):
return proper_velocity2energy(self.uzs())
def deltas(self, pz0=None):
if pz0 is None:
pz0 = np.mean(self.pzs())
return self.pzs()/pz0 -1
def ts(self):
return self.zs()/SI.c
def comp_beams(beam1, beam2, comp_location=False, rtol=1e-15, atol=0.0):
"""
Compare the phase spaces of two beams. Chekcks if all arrays are
element-wise equal within given tolerances.
Parameters
----------
beam1 : ABEL ``Beam`` object
First beam to be compared.
beam2 : ABEL ``Beam`` object
Second beam to be compared.
comp_location : bool, optional
Flag for comparing the location of the beams. Default set to
``False``.
rtol : float, optional
The relative tolerance parameter (see [1]_). Default set to 1e-15.
atol : float, optional
The absolute tolerance parameter (see [1]_). Default set to 0.0.
Returns
----------
``None``
References
----------
.. [1] ``numpy.allclose()`` https://numpy.org/doc/stable/reference/generated/numpy.allclose.html
"""
if comp_location:
assert np.allclose(beam1.location, beam2.location, rtol, atol)
assert beam1.stage_number == beam2.stage_number
assert np.allclose(beam1.qs(), beam2.qs(), rtol, atol)
assert np.allclose(beam1.weightings(), beam2.weightings(), rtol, atol)
assert np.allclose(beam1.xs(), beam2.xs(), rtol, atol)
assert np.allclose(beam1.ys(), beam2.ys(), rtol, atol)
assert np.allclose(beam1.zs(), beam2.zs(), rtol, atol)
assert np.allclose(beam1.uxs(), beam2.uxs(), rtol, atol)
assert np.allclose(beam1.uys(), beam2.uys(), rtol, atol)
assert np.allclose(beam1.uzs(), beam2.uzs(), rtol, atol)
assert np.allclose(beam1.particle_mass, beam2.particle_mass, rtol, atol)
def comp_beam_params(beam1, beam2, comp_location=False):
"""
Compare the parameters of two beams to see if they are equal within
given tolerances.
Parameters
----------
beam1 : ABEL ``Beam`` object
First beam to be compared.
beam2 : ABEL ``Beam`` object
Second beam to be compared.
comp_location : bool, optional
Flag for comparing the location of the beams. Default set to
``False``.
Returns
----------
``None``
References
----------
.. [1] ``numpy.allclose()`` https://numpy.org/doc/stable/reference/generated/numpy.allclose.html
"""
if comp_location:
assert np.allclose(beam1.location, beam2.location, rtol=0.0, atol=0.3)
assert np.allclose(beam1.particle_mass, beam2.particle_mass, rtol=1e-05, atol=1e-08)
assert np.allclose(beam1.total_particles(), beam2.total_particles(), rtol=1e-05, atol=1e-08)
assert np.allclose(beam1.charge(), beam2.charge(), rtol=1e-05, atol=1e-08)
assert np.allclose(beam1.energy(), beam2.energy(), rtol=0.0, atol=0.6e9) # Usually rather large discrepancy in energy.
assert np.allclose(beam1.energy_spread(), beam2.energy_spread(), rtol=0.0, atol=0.6e9)
assert np.allclose(beam1.rel_energy_spread(), beam2.rel_energy_spread(), rtol=0.0, atol=5e-4)
assert np.allclose(beam1.bunch_length(), beam2.bunch_length(), rtol=0.05, atol=0.5e-6)
assert np.allclose(beam1.beam_size_x(), beam2.beam_size_x(), rtol=0.05, atol=0.5e-6)
assert np.allclose(beam1.beam_size_y(), beam2.beam_size_y(), rtol=0.05, atol=0.05e-6)
assert np.allclose(beam1.geom_emittance_x(), beam2.geom_emittance_x(), rtol=1e-05, atol=1e-08)
assert np.allclose(beam1.geom_emittance_y(), beam2.geom_emittance_y(), rtol=1e-05, atol=1e-08)
assert np.allclose(beam1.norm_emittance_x(), beam2.norm_emittance_x(), rtol=0.0, atol=1e-6)
assert np.allclose(beam1.norm_emittance_y(), beam2.norm_emittance_y(), rtol=0.0, atol=0.5e-6)
assert np.allclose(beam1.peak_current(), beam2.peak_current(), rtol=0.0, atol=0.7e3)
assert np.allclose(beam1.beta_x(), beam2.beta_x(), rtol=0.05, atol=5e-3)
assert np.allclose(beam1.beta_y(), beam2.beta_y(), rtol=0.05, atol=5e-3)
assert np.allclose(beam1.gamma_x(), beam2.gamma_x(), rtol=0.05, atol=0.0)
assert np.allclose(beam1.gamma_y(), beam2.gamma_y(), rtol=0.05, atol=0.0)
assert np.allclose(beam1.z_offset(), beam2.z_offset(), rtol=0.0, atol=3e-6)
assert np.allclose(beam1.x_offset(), beam2.x_offset(), rtol=0.0, atol=3e-6)
assert np.allclose(beam1.y_offset(), beam2.y_offset(), rtol=0.0, atol=3e-6)
assert np.allclose(beam1.x_angle(), beam2.x_angle(), rtol=0.0, atol=3e-6)
assert np.allclose(beam1.y_angle(), beam2.y_angle(), rtol=0.0, atol=3e-6)
assert np.allclose(beam1.divergence_x(), beam2.divergence_x(), rtol=0.0, atol=0.2e-5)
assert np.allclose(beam1.divergence_y(), beam2.divergence_y(), rtol=0.0, atol=0.5e-6)
# vector of transverse positions and angles: (x, x', y, y')
def transverse_vector(self):
vector = np.zeros((4,len(self)))
vector[0,:] = self.xs()
vector[1,:] = self.xps()
vector[2,:] = self.ys()
vector[3,:] = self.yps()
return vector
# set phase space based on transverse vector: (x, x', y, y')
def set_transverse_vector(self, vector):
self.set_xs(vector[0,:])
self.set_xps(vector[1,:])
self.set_ys(vector[2,:])
self.set_yps(vector[3,:])
def norm_transverse_vector(self):
vector = np.zeros((4,len(self)))
vector[0,:] = self.xs()
vector[1,:] = self.uxs()/SI.c
vector[2,:] = self.ys()
vector[3,:] = self.uys()/SI.c
return vector
## Rotate the coordinate system of the beam
# ==================================================
def rotate_coord_sys_3D(self, axis1, angle1, axis2=np.array([0, 1, 0]), angle2=0.0, axis3=np.array([1, 0, 0]), angle3=0.0, invert=False):
"""
Rotates the coordinate system (passive transformation) of the beam first
with ``angle1`` around ``axis1``, then with ``angle2`` around ``axis2``
and lastly with ``angle3`` around ``axis3``.
Parameters
----------
axis1 : 1x3 float ndarrays
Unit vector specifying the rotation axes.
angle1 : [rad] float
Angle used for rotation of the beam's coordinate system around the
respective axes.
axis2, axis3 : 1x3 float ndarrays, optional
Additional unit vectors specifying the rotation axes.
angle2, angle3 : [rad] float, optional
Additional angles used for rotation of the beam's coordinate system
around the respective axes.
invert : bool, optional
Performs a standard passive transformation when ``False``. If
``True``, will perform an active transformation and can thus be used
to invert the passive transformation.
Returns
----------
Modified beam ``xs``, ``ys``, ``zs``, ``uxs``, ``uys`` and ``uzs``.
"""
# Check the inputs
if np.linalg.norm(axis1) != 1.0 or np.linalg.norm(axis2) != 1.0 or np.linalg.norm(axis3) != 1.0:
raise ValueError('The rotation axes have to be unit vectors.')
if angle1 < -np.pi or angle1 > np.pi or angle2 < -np.pi or angle2 > np.pi or angle3 < -np.pi or angle3 > np.pi:
raise ValueError('The rotation angles have to be in the interval [-pi, pi].')
# Combine into (N, 3) arrays
zs = self.zs()
xs = self.xs()
ys = self.ys()
uzs = self.uzs()
uxs = self.uxs()
uys = self.uys()
coords = np.column_stack((zs, xs, ys))
u_vecs = np.column_stack((uzs, uxs, uys))
# Create rotation objects
rotation1 = Rot.from_rotvec(angle1 * axis1)
rotation2 = Rot.from_rotvec(angle2 * axis2)
rotation3 = Rot.from_rotvec(angle3 * axis3)
# Combine the rotations by applying them in sequence
combined_rotation = rotation1 * rotation2 * rotation3 # Rotation order is right-to-left, but effectively opposite when inverse=True in combined_rotation.apply().
# Apply rotation to the arrays
rotated_coords = combined_rotation.apply(coords, inverse= not invert) # Since combined_rotation.apply() performs active transformations by default, inverse must be set to True for passive transformation.
rotated_u_vecs = combined_rotation.apply(u_vecs, inverse= not invert)
# Extract the rotated arrays
rotated_zs, rotated_xs, rotated_ys = rotated_coords[:, 0], rotated_coords[:, 1], rotated_coords[:, 2]
rotated_uzs, rotated_uxs, rotated_uys = rotated_u_vecs[:, 0], rotated_u_vecs[:, 1], rotated_u_vecs[:, 2]
self.set_zs(rotated_zs)
self.set_xs(rotated_xs)
self.set_ys(rotated_ys)
self.set_uzs(rotated_uzs)
self.set_uxs(rotated_uxs)
self.set_uys(rotated_uys)
# ==================================================
def beam_alignment_angles(self):
"""
Calculates the angles for rotation around the y- and x-axis to align the
z-axis to the beam proper velocity.
Parameters
----------
N/A
Returns
----------
x_angle : [rad] float
Used for rotating the beam's frame around the y-axis.
y_angle : [rad] float
Used for rotating the beam's frame around the x-axis. Note that due
to the right hand rule, a positive rotation angle in the zy-plane
corresponds to rotation from z-axis towards negative y. I.e. the
opposite sign convention of ``beam.yps()``.
"""
# Get the mean proper velocity component offsets
uz_offset = energy2proper_velocity(self.energy())
ux_offset = self.ux_offset()
uy_offset = self.uy_offset()
point_vec = np.array([uz_offset, ux_offset, uy_offset])
point_vec = point_vec/np.linalg.norm(point_vec)
# Calculate the angles to be used for beam rotation
z_axis = np.array([1, 0, 0]) # Axis as an unit vector
zx_projection = point_vec * np.array([1, 1, 0]) # The projection of the pointing vector onto the zx-plane.
# Separate treatments for small angles to avoid numerical instability
if np.abs(self.x_angle()) < 1e-4:
x_angle = ux_offset/uz_offset
else:
x_angle = np.sign(point_vec[1]) * np.arccos( np.dot(zx_projection, z_axis) / np.linalg.norm(zx_projection) ) # The angle between zx_projection and z_axis.
if np.abs(self.y_angle()) < 1e-4:
y_angle = point_vec[2]/np.linalg.norm(zx_projection)
else:
rotated_zy_projection = np.array([ np.linalg.norm(zx_projection), 0, point_vec[2] ]) # The new pointing vector after its zx-projection has been aligned to the rotated z-axis.
y_angle = np.sign(point_vec[2]) * np.arccos( np.dot(rotated_zy_projection, z_axis) / np.linalg.norm(rotated_zy_projection) ) # Note that due to the right hand rule, a positive y_angle corresponds to rotation from z-axis towards negative y. I.e. opposite sign convention of yps.
return x_angle, y_angle
# ==================================================
def xy_rotate_coord_sys(self, x_angle=None, y_angle=None, invert=False):
"""
Rotates the coordinate system of the beam first with ``x_angle`` around
the y-axis then with ``y_angle`` around the x-axis.
Parameters
----------
x_angle : [rad] float, optional
Angle to rotate the coordinate system with in the zx-plane. Calls
``Beam.beam_alignment_angles()`` by default if no angle is provided.
y_angle : [rad] float, optional
Angle to rotate the coordinate system with in the zy-plane. Note
that due to the right hand rule, a positive rotation angle in the
zy-plane corresponds to rotation from z-axis towards negative y.
I.e. the opposite sign convention of ``beam.yps()``. Calls
``Beam.beam_alignment_angles()`` by default if no angle is provided.
invert : bool, optional
Performs a standard passive transformation when False. If True, will
perform an active transformation and can thus be used to invert the
passive transformation.
Returns
----------
Modified beam ``xs``, ``ys``, ``zs``, ``uxs``, ``uys`` and ``uzs``.
"""
x_axis = np.array([0, 1, 0]) # Axis as an unit vector. Axis permutaton is zxy.
y_axis = np.array([0, 0, 1])
if x_angle is None:
x_angle, _ = self.beam_alignment_angles()
if y_angle is None:
_, y_angle = self.beam_alignment_angles()
y_angle = -y_angle
self.rotate_coord_sys_3D(y_axis, x_angle, x_axis, y_angle, invert=invert)
# ==================================================
def add_pointing_tilts(self, align_x_angle=None, align_y_angle=None):
"""
Uses active transformation to tilt the beam in the zx- and zy-planes.
Parameters
----------
align_x_angle : [rad] float, optional
Beam coordinates in the zx-plane are rotated with this angle. If
``None``, will align the beam using its angular offset.
align_y_angle : [rad] float, optional
Beam coordinates in the zy-plane are rotated with this angle. Note
that due to the right hand rule, a positive rotation angle in the
zy-plane corresponds to rotation from z-axis towards negative y.
I.e. the opposite sign convention of ``beam.yps()``. If ``None``,
will align the beam using its angular offset.
Returns
----------
Modified beam ``xs``, ``ys`` and ``zs``.
"""
if align_x_angle is None:
align_x_angle, _ = self.beam_alignment_angles()
if align_y_angle is None:
_, align_y_angle = self.beam_alignment_angles()
align_y_angle = -align_y_angle
y_axis = np.array([0, 0, 1])
x_axis = np.array([0, 1, 0])
zs = self.zs()
xs = self.xs()
ys = self.ys()
# Combine into (N, 3) arrays
coords = np.column_stack((zs, xs, ys))
# Create the rotation object
rotation_y = Rot.from_rotvec(align_x_angle * y_axis)
rotation_x = Rot.from_rotvec(align_y_angle * x_axis)
combined_rotation = rotation_y * rotation_x
# Apply rotation to the coordinates only
rotated_coords = combined_rotation.apply(coords, inverse=False) # Active transformation
# Extract the rotated coordinates
rotated_zs, rotated_xs, rotated_ys = rotated_coords[:, 0], rotated_coords[:, 1], rotated_coords[:, 2]
self.set_zs(rotated_zs)
self.set_xs(rotated_xs)
self.set_ys(rotated_ys)
# ==================================================
def slice_centroids(self, beam_quant, bin_number=None, cut_off=None, make_plot=False):
"""
Returns the slice centroids of a beam quantity ``beam_quant``.
Parameters
----------
beam_quant : 1D float array
Beam quantity to be binned into bins/slices defined by ``z_centroids``.
The mean is calculated for the quantity for all particles in the
z-bins. Includes e.g. ``beam.xs()``, ``beam.Es()`` etc.
bin_number : float, optional
Number of beam slices.
cut_off : float, optional
Determines the longitudinal coordinates inside the region of
interest.
make_plot : bool, optional
Flag for making plots.
Returns
----------
beam_quant_slices : 1D float array
``beam_quant`` binned into bins/slices defined by ``z_centroids``. The mean
is calculated for the quantity for all particles in the z-bins.
Includes e.g. ``beam.xs()``, ``beam.Es()`` etc.
z_centroids : [m] 1D float array
z-coordinates of the beam slices.
"""
zs = self.zs()
mean_z = self.z_offset()
weights = self.weightings()
if cut_off is None:
cut_off = 1.5 * self.bunch_length()
# Sort the arrays
indices = np.argsort(zs)
zs_sorted = zs[indices] # Particle quantity.
weights_sorted = weights[indices] # Particle quantity.
beam_quant_sorted = beam_quant[indices] # Particle quantity.
# Filter out elements outside the region of interest
bool_indices = (zs_sorted <= mean_z + cut_off) & (zs_sorted >= mean_z - cut_off)
zs_roi = zs_sorted[bool_indices]
weights_roi = weights_sorted[bool_indices]
beam_quant_roi = beam_quant_sorted[bool_indices]
if bin_number is None:
bin_number = int(np.sqrt(len(zs_roi)/2))
# Beam slice zs
_, edges = np.histogram(zs_roi, bins=bin_number) # Get the edges of the histogram of z with bin_number bins.
z_centroids = (edges[0:-1] + edges[1:])/2 # Centres of the beam slices (z)
# Compute the mean of beam_quant of all particles inside a z-bin
beam_quant_centroids = np.empty(len(z_centroids))
for i in range(0,len(edges)-1):
left = np.searchsorted(zs_roi, edges[i]) # zs_sorted[left:len(zs_sorted)] >= edges[i], left side of bin i.
right = np.searchsorted(zs_roi, edges[i+1], side='right') # zs_sorted[0:right] <= edges[i+1], right (larger) side of bin i.
beam_quant_centroids[i] = weighted_mean(beam_quant_roi[left:right], weights_roi[left:right])
if make_plot is True:
plt.figure()
plt.scatter(zs*1e6, beam_quant)
plt.plot(z_centroids*1e6, beam_quant_centroids, 'rx-')
plt.xlabel(r'$\xi$ [$\mathrm{\mu}$m]')
return beam_quant_centroids, z_centroids
# ==================================================
def x_tilt_angle(self, z_cutoff=None):
"Retrieve the tilt angle of the beam in the zx-plane. WARNING: becomes unreliable around > 1e-4 rad."
if z_cutoff is None:
z_cutoff = 1.5 * self.bunch_length()
x_centroids, z_centroids = self.slice_centroids(self.xs(), cut_off=z_cutoff, make_plot=False)
# Perform linear regression
slope, _ = np.polyfit(z_centroids, x_centroids, 1)
return np.arctan(slope)
# ==================================================
def y_tilt_angle(self, z_cutoff=None):
"Retrieve the tilt angle of the beam in the zy-plane. WARNING: becomes unreliable around > 1e-4 rad."
if z_cutoff is None:
z_cutoff = 1.5 * self.bunch_length()
y_centroids, z_centroids = self.slice_centroids(self.ys(), cut_off=z_cutoff, make_plot=False)
# Perform linear regression
slope, _ = np.polyfit(z_centroids, y_centroids, 1)
return np.arctan(slope)
## BEAM STATISTICS
def total_particles(self):
"Total number of physical particles."
return int(np.nansum(self.weightings()))
def population(self):
"Total number of physical particles."
return np.sum(self.weightings())
def particle_charge(self):
"The charge of a physical particle."
return self.charge()/self.total_particles()
def charge(self):
"Total beam charge."
return np.nansum(self.qs())
def abs_charge(self):
"Total absolute beam charge."
return abs(self.charge())
def charge_sign(self):
if self.charge() == 0:
return 1.0
else:
return self.charge()/abs(self.charge())
def energy(self, clean=False):
return weighted_mean(self.Es(), self.weightings(), clean)
def gamma(self, clean=False):
return weighted_mean(self.gammas(), self.weightings(), clean)
def total_energy(self):
return SI.e * np.nansum(self.weightings()*self.Es())
def energy_spread(self, clean=False):
return weighted_std(self.Es(), self.weightings(), clean)
def rel_energy_spread(self, clean=False):
return self.energy_spread(clean)/self.energy(clean)
def z_offset(self, clean=False):
return weighted_mean(self.zs(), self.weightings(), clean)
def bunch_length(self, clean=False):
return weighted_std(self.zs(), self.weightings(), clean)
def x_offset(self, clean=False):
return weighted_mean(self.xs(), self.weightings(), clean)
def beam_size_x(self, clean=False):
return weighted_std(self.xs(), self.weightings(), clean)
def y_offset(self, clean=False):
return weighted_mean(self.ys(), self.weightings(), clean)
def beam_size_y(self, clean=False):
return weighted_std(self.ys(), self.weightings(), clean)
def x_angle(self, clean=False):
return weighted_mean(self.xps(), self.weightings(), clean)
def divergence_x(self, clean=False):
return weighted_std(self.xps(), self.weightings(), clean)
def y_angle(self, clean=False):
return weighted_mean(self.yps(), self.weightings(), clean)
def divergence_y(self, clean=False):
return weighted_std(self.yps(), self.weightings(), clean)
def ux_offset(self, clean=False):
return weighted_mean(self.uxs(), self.weightings(), clean)
def uy_offset(self, clean=False):
return weighted_mean(self.uys(), self.weightings(), clean)
def uz_offset(self, clean=False):
return weighted_mean(self.uzs(), self.weightings(), clean)
def geom_emittance_x(self, clean=False):
return np.sqrt(np.linalg.det(weighted_cov(self.xs(), self.xps(), self.weightings(), clean)))
def geom_emittance_y(self, clean=False):
return np.sqrt(np.linalg.det(weighted_cov(self.ys(), self.yps(), self.weightings(), clean)))
def norm_emittance_x(self, clean=False):
return np.sqrt(np.linalg.det(weighted_cov(self.xs(), self.uxs()/SI.c, self.weightings(), clean)))
def norm_emittance_y(self, clean=False):
return np.sqrt(np.linalg.det(weighted_cov(self.ys(), self.uys()/SI.c, self.weightings(), clean)))