-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpylatt.py
More file actions
8573 lines (7969 loc) · 293 KB
/
pylatt.py
File metadata and controls
8573 lines (7969 loc) · 293 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
"""
Lattice code in python 2016-12-06
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
__version__ = 2.0
__author__ = "YONGJUN LI, mpyliyj@gmail.com or mpyliyj@hotmail.com"
import cmath
import copy
import functools
import math
from multiprocessing import Process, Queue
import string
import sys
import time
import warnings
import cupy as cp
from matplotlib.cbook import flatten
from matplotlib.collections import PatchCollection
import matplotlib.patches as mpatches
import matplotlib.pylab as plt
import numpy as np
try:
import numba as nb
from numba import cuda as nb_cuda
except:
nb_cuda = None
print('*** Could NOT import "numba"')
# nb_cuda = None
try:
import nvtx
except:
print('*** Could NOT import "nvtx"')
from scipy.linalg import logm
import scipy.optimize as opt
from scipy.optimize import fmin
ncp = np
import mvp
ncp.seterr(all="ignore")
# --- global parameters:
csp = 299792458.0 # speed of light
twopi = 2 * ncp.pi
def use_cpu():
global ncp
ncp = np
def use_gpu():
global ncp
ncp = cp
if nb_cuda is not None:
@nb_cuda.jit(device=True)
def cuda_matrix_mult(X, Y, Z):
Z[:, :] = 0.0
# m, n = X.shape
_n, p = Y.shape
i, j = nb_cuda.grid(2)
if i >= Z.shape[0] or j >= Z.shape[1]:
return
for k in range(p):
Z[i, j] += X[i, k] * Y[k, j]
@nb_cuda.jit(device=True)
def cuda_matrix_copy(X, Y):
i, j = nb_cuda.grid(2)
if i >= X.shape[0] or j >= X.shape[1]:
return
X[i, j] = Y[i, j]
@nb_cuda.jit(device=True)
def cuda_1d_vec_copy(x, y):
i = nb_cuda.grid(1)
if i >= x.size or i >= y.size:
return
x[i] = y[i]
@nb_cuda.jit(device=True)
def cuda_symp_int_update(x1, x2, x3, K1L):
i = nb_cuda.grid(1)
if i >= x1.size:
return
x1[i] += K1L * x2[i] / (1.0 + x3[i])
@nb_cuda.jit(device=True)
def cuda_avg_1d_vecs(x1, x2, xp):
i = nb_cuda.grid(1)
if (i >= x1.size) or (i >= x2.size) or (i >= xp.size):
return
xp[i] = (x1[i] + x2[i]) / 2.0
@nb_cuda.jit(device=True)
def cuda_calc_avg_slope(xp, yp, _dL, S):
i = nb_cuda.grid(1)
if i >= xp.size:
return
S[i] += math.sqrt(1.0 + xp[i] ** 2 + yp[i] ** 2) * _dL
@nb_cuda.jit
def cuda_sympass4_quad(x, Z, S, xp, yp, _Ma, _Mb, _K1Lg, _K1Ld, _dL):
m, n = _Ma.shape
_n, p = x.shape
# assert n == _n
# with nvtx.annotate("Ma1", color="blue"):
x1p, y1p = x[1], x[3]
##x = _Ma.dot(x)
cuda_matrix_mult(_Ma, x, Z)
cuda_matrix_copy(x, Z)
# x[1] -= _K1Lg * x[0] / (1.0 + x[5])
cuda_symp_int_update(x[1], x[0], x[5], _K1Lg * (-1))
# x[3] += _K1Lg * x[2] / (1.0 + x[5])
cuda_symp_int_update(x[3], x[2], x[5], _K1Lg)
##with nvtx.annotate("Mb1", color="green"):
##x = _Mb.dot(x)
cuda_matrix_mult(_Mb, x, Z)
cuda_matrix_copy(x, Z)
# x[1] -= _K1Ld * x[0] / (1.0 + x[5])
cuda_symp_int_update(x[1], x[0], x[5], _K1Ld * (-1))
# x[3] += _K1Ld * x[2] / (1.0 + x[5])
cuda_symp_int_update(x[3], x[2], x[5], _K1Ld)
##with nvtx.annotate("Mb2", color="red"):
##x = _Mb.dot(x)
cuda_matrix_mult(_Mb, x, Z)
cuda_matrix_copy(x, Z)
# x[1] -= _K1Lg * x[0] / (1.0 + x[5])
cuda_symp_int_update(x[1], x[0], x[5], _K1Lg * (-1))
# x[3] += _K1Lg * x[2] / (1.0 + x[5])
cuda_symp_int_update(x[3], x[2], x[5], _K1Lg)
##with nvtx.annotate("Ma2", color="yellow"):
##x = _Ma.dot(x)
cuda_matrix_mult(_Ma, x, Z)
cuda_matrix_copy(x, Z)
x2p, y2p = x[1], x[3]
# xp, yp = (x1p + x2p) / 2, (y1p + y2p) / 2
cuda_avg_1d_vecs(x1p, x2p, xp)
cuda_avg_1d_vecs(y1p, y2p, yp)
##with nvtx.annotate("avg", color="magenta"):
## --- average slope at entrance and exit
# S += math.sqrt(1.0 + xp**2 + yp**2) * _dL
cuda_calc_avg_slope(xp, yp, _dL, S)
@nb_cuda.jit(device=True)
def cuda_device_sympass4_quad(
x, Z, S, xp, yp, x1p, y1p, x2p, y2p, _Ma, _Mb, _K1Lg, _K1Ld, _dL
):
# x1p, y1p = x[1], x[3]
cuda_1d_vec_copy(x1p, x[1])
cuda_1d_vec_copy(y1p, x[3])
cuda_matrix_mult(_Ma, x, Z)
cuda_matrix_copy(x, Z)
cuda_symp_int_update(x[1], x[0], x[5], _K1Lg * (-1))
cuda_symp_int_update(x[3], x[2], x[5], _K1Lg)
cuda_matrix_mult(_Mb, x, Z)
cuda_matrix_copy(x, Z)
cuda_symp_int_update(x[1], x[0], x[5], _K1Ld * (-1))
cuda_symp_int_update(x[3], x[2], x[5], _K1Ld)
cuda_matrix_mult(_Mb, x, Z)
cuda_matrix_copy(x, Z)
cuda_symp_int_update(x[1], x[0], x[5], _K1Lg * (-1))
cuda_symp_int_update(x[3], x[2], x[5], _K1Lg)
cuda_matrix_mult(_Ma, x, Z)
cuda_matrix_copy(x, Z)
x2p, y2p = x[1], x[3]
cuda_1d_vec_copy(x2p, x[1])
cuda_1d_vec_copy(y2p, x[3])
cuda_avg_1d_vecs(x1p, x2p, xp)
cuda_avg_1d_vecs(y1p, y2p, yp)
cuda_calc_avg_slope(xp, yp, _dL, S)
@nb_cuda.jit
def cuda_sympass4_quad_for_loop(
x, Z, S, xp, yp, x1p, y1p, x2p, y2p, _Ma, _Mb, _K1Lg, _K1Ld, _dL
):
# cuda_device_sympass4_quad(x, Z, S, xp, yp, x1p, y1p, x2p, y2p,
# _Ma, _Mb, _K1Lg, _K1Ld, _dL)
# cuda_device_sympass4_quad(x, Z, S, xp, yp, x1p, y1p, x2p, y2p,
# _Ma, _Mb, _K1Lg, _K1Ld, _dL)
# cuda_device_sympass4_quad(x, Z, S, xp, yp, x1p, y1p, x2p, y2p,
# _Ma, _Mb, _K1Lg, _K1Ld, _dL)
# cuda_device_sympass4_quad(x, Z, S, xp, yp, x1p, y1p, x2p, y2p,
# _Ma, _Mb, _K1Lg, _K1Ld, _dL)
# counter = 0
# while counter < 2:
##if True:
# cuda_device_sympass4_quad(x, Z, S, xp, yp, x1p, y1p, x2p, y2p,
# _Ma, _Mb, _K1Lg, _K1Ld, _dL)
# counter += 1
for i in range(1):
# x1p, y1p = x[1], x[3]
cuda_1d_vec_copy(x1p, x[1])
cuda_1d_vec_copy(y1p, x[3])
cuda_matrix_mult(_Ma, x, Z)
cuda_matrix_copy(x, Z)
cuda_symp_int_update(x[1], x[0], x[5], _K1Lg * (-1))
cuda_symp_int_update(x[3], x[2], x[5], _K1Lg)
cuda_matrix_mult(_Mb, x, Z)
cuda_matrix_copy(x, Z)
cuda_symp_int_update(x[1], x[0], x[5], _K1Ld * (-1))
cuda_symp_int_update(x[3], x[2], x[5], _K1Ld)
cuda_matrix_mult(_Mb, x, Z)
cuda_matrix_copy(x, Z)
cuda_symp_int_update(x[1], x[0], x[5], _K1Lg * (-1))
cuda_symp_int_update(x[3], x[2], x[5], _K1Lg)
cuda_matrix_mult(_Ma, x, Z)
cuda_matrix_copy(x, Z)
# x2p, y2p = x[1], x[3]
cuda_1d_vec_copy(x2p, x[1])
cuda_1d_vec_copy(y2p, x[3])
cuda_avg_1d_vecs(x1p, x2p, xp)
cuda_avg_1d_vecs(y1p, y2p, yp)
cuda_calc_avg_slope(xp, yp, _dL, S)
@nb_cuda.jit
def quad_sympass4_numba(x, K1Lg, K1Ld, Ma, Mb, nkick, dL, n, S):
"""Based on Jonathan Dursi's code"""
idx = nb_cuda.grid(1)
if idx < n:
S[idx] = 0.0
for _ in range(nkick):
x1p, y1p = x[1, idx], x[3, idx]
for dim in range(6):
v = 0.0
for k in range(6):
v += Ma[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= K1Lg * x[0, idx] / (1.0 + x[5, idx])
x[3, idx] += K1Lg * x[2, idx] / (1.0 + x[5, idx])
for dim in range(6):
v = 0.0
for k in range(6):
v += Mb[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= K1Ld * x[0, idx] / (1.0 + x[5, idx])
x[3, idx] += K1Ld * x[2, idx] / (1.0 + x[5, idx])
for dim in range(6):
v = 0
for k in range(6):
v += Mb[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= K1Lg * x[0, idx] / (1.0 + x[5, idx])
x[3, idx] += K1Lg * x[2, idx] / (1.0 + x[5, idx])
for dim in range(6):
v = 0.0
for k in range(6):
v += Ma[dim, k] * x[k, idx]
x[dim, idx] = v
x2p, y2p = x[1, idx], x[3, idx]
xp, yp = (x1p + x2p) / 2, (y1p + y2p) / 2
S[idx] += math.sqrt(1.0 + xp * xp + yp * yp) * dL
@nb_cuda.jit
def sext_sympass4_numba(x, K2Lg, K2Ld, Ma, Mb, nkick, dL, n, S):
idx = nb_cuda.grid(1)
if idx < n:
S[idx] = 0.0
for _ in range(nkick):
x1p, y1p = x[1, idx], x[3, idx]
for dim in range(6):
v = 0.0
for k in range(6):
v += Ma[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= (
K2Lg / 2 * (x[0, idx] ** 2 - x[2, idx] ** 2) / (1.0 + x[5, idx])
)
x[3, idx] += K2Lg * (x[0, idx] * x[2, idx]) / (1.0 + x[5, idx])
for dim in range(6):
v = 0.0
for k in range(6):
v += Mb[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= (
K2Ld / 2 * (x[0, idx] ** 2 - x[2, idx] ** 2) / (1.0 + x[5, idx])
)
x[3, idx] += K2Ld * (x[0, idx] * x[2, idx]) / (1.0 + x[5, idx])
for dim in range(6):
v = 0
for k in range(6):
v += Mb[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= (
K2Lg / 2 * (x[0, idx] ** 2 - x[2, idx] ** 2) / (1.0 + x[5, idx])
)
x[3, idx] += K2Lg * (x[0, idx] * x[2, idx]) / (1.0 + x[5, idx])
for dim in range(6):
v = 0.0
for k in range(6):
v += Ma[dim, k] * x[k, idx]
x[dim, idx] = v
x2p, y2p = x[1, idx], x[3, idx]
xp, yp = (x1p + x2p) / 2, (y1p + y2p) / 2
S[idx] += math.sqrt(1.0 + xp * xp + yp * yp) * dL
@nb_cuda.jit
def bend_sympass4_numba(
x, K2Lg, K2Ld, K1Lg, K1Ld, Lg, Ld, R, Ma, Mb, nkick, dL, n, S
):
idx = nb_cuda.grid(1)
if idx < n:
S[idx] = 0.0
for _ in range(nkick):
x1p, y1p = x[1, idx], x[3, idx]
x1 = x[0, idx]
for dim in range(6):
v = 0.0
for k in range(6):
v += Ma[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= (
K2Lg / 2 * (x[0, idx] ** 2 - x[2, idx] ** 2) / (1.0 + x[5, idx])
+ K1Lg * x[0, idx] / (1.0 + x[5, idx])
- Lg * x[5, idx] / R
+ Lg * x[0, idx] / (R**2)
)
x[3, idx] += K2Lg * (x[0, idx] * x[2, idx]) / (
1.0 + x[5, idx]
) + K1Lg * x[2, idx] / (1.0 + x[5, idx])
for dim in range(6):
v = 0.0
for k in range(6):
v += Mb[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= (
K2Ld / 2 * (x[0, idx] ** 2 - x[2, idx] ** 2) / (1.0 + x[5, idx])
+ K1Ld * x[0, idx] / (1.0 + x[5, idx])
- Ld * x[5, idx] / R
+ Ld * x[0, idx] / (R**2)
)
x[3, idx] += K2Ld * (x[0, idx] * x[2, idx]) / (
1.0 + x[5, idx]
) + K1Ld * x[2, idx] / (1.0 + x[5, idx])
for dim in range(6):
v = 0
for k in range(6):
v += Mb[dim, k] * x[k, idx]
x[dim, idx] = v
x[1, idx] -= (
K2Lg / 2 * (x[0, idx] ** 2 - x[2, idx] ** 2) / (1.0 + x[5, idx])
+ K1Lg * x[0, idx] / (1.0 + x[5, idx])
- Lg * x[5, idx] / R
+ Lg * x[0, idx] / (R**2)
)
x[3, idx] += K2Lg * (x[0, idx] * x[2, idx]) / (
1.0 + x[5, idx]
) + K1Lg * x[2, idx] / (1.0 + x[5, idx])
for dim in range(6):
v = 0.0
for k in range(6):
v += Ma[dim, k] * x[k, idx]
x[dim, idx] = v
x2p, y2p = x[1, idx], x[3, idx]
x2 = x[0, idx]
xp, yp = (x1p + x2p) / 2, (y1p + y2p) / 2
xav = (x1 + x2) / 2
S[idx] += math.sqrt(1.0 + xp * xp + yp * yp) * (1.0 + xav / R) * dL
class drif(object):
"""
class: drif - define a drift space with given name and length
usage: D01 = drif(name='D01',L=1.0,nkick=0,Dx=0,Dy=0,tilt=0,tag=[])
Parameter list:
name: element name
L: length
Dx, Dy, tilt: misalignment in meter, radian
tm: transport matrix 6x6
tx,ty: twiss matrics 3x3 for x and y plane
nkick: number of kicks, reserved for inherited classes
tag: tag list for searching
"""
def __init__(self, name="D01", L=1.0, nkick=0, Dx=0, Dy=0, tilt=0, tag=[]):
self.name = str(name)
self._L = ncp.float64(L)
self._Dx = ncp.float64(Dx)
self._Dy = ncp.float64(Dy)
self._tilt = ncp.float64(tilt)
self._nkick = int(nkick)
self.tag = tag
self._update()
def __repr__(self):
return "%s: %s,L=%g" % (self.name, self.__class__.__name__, self.L)
def put(self, field, value):
"""
update a new value on an instance's attribute
usage: instance.put(field_name, new_field_value)
same as use . operator to modify an instance's attribute
"""
if hasattr(self, field):
setattr(self, field, value)
self._update()
else:
raise RuntimeError("%s has no attribute of %s" % (self.name, field))
@property
def L(self):
return self._L
@L.setter
def L(self, value):
try:
self._L = ncp.float64(value)
self._update()
except:
raise RuntimeError("L must be float (or convertible)")
@property
def Dx(self):
return self._Dx
@Dx.setter
def Dx(self, value):
try:
self._Dx = ncp.float64(value)
self._update()
except:
raise RuntimeError("Dx must be float (or convertible)")
@property
def Dy(self):
return self._Dy
@Dy.setter
def Dy(self, value):
try:
self._Dy = ncp.float64(value)
self._update()
except:
raise RuntimeError("Dy must be float (or convertible)")
@property
def tilt(self):
return self._tilt
@tilt.setter
def tilt(self, value):
try:
self._tilt = ncp.float64(value)
self._update()
except:
raise RuntimeError("tilt must be float (or convertible)")
@property
def nkick(self):
return self._nkick
@nkick.setter
def nkick(self, value):
try:
self._nkick = int(value)
self._update()
except:
raise RuntimeError("nkick must be int (or convertible)")
@property
def tm(self):
return self._tm
@property
def tx(self):
return self._tx
@property
def ty(self):
return self._ty
def _update(self):
"""
update matrices and check magnet length using latest parametes
"""
self._chklength()
self._transmatrix()
self._twissmatrix()
def _transmatrix(self):
"""
calculate linear transport matrix
"""
self._tm = ncp.eye(6)
self._tm[0, 1] = self.L
self._tm[2, 3] = self.L
def _twissmatrix(self):
"""
from transport matrix to calculate two twiss matrices
"""
self._tx = trans2twiss(self.tm[0:2, 0:2])
self._ty = trans2twiss(self.tm[2:4, 2:4])
def _chklength(self):
"""
check element length, print a warnning if negative length
"""
if self.L < 0.0:
print("warning: %s has a negative length %g" % (self.name, self.L))
def sympass4(self, x, fast=1):
"""
implement 4-th order symplectic pass with initial condition
x: the initial coordinates in phase space for m particles
if fast = 1, assume x has (6,-1), otherwise reshape x
"""
if not fast:
x = ncp.array(x, dtype=ncp.float64).reshape(6, -1)
if self.L != 0:
x = self.tm.dot(x)
x[4] += (ncp.sqrt(1.0 + ncp.square(x[1]) + ncp.square(x[3])) - 1.0) * self.L
return x
class quad(drif):
"""
class: quad - define a quadrupole with given length and K1
usage: Q01 = quad(name='Q01',L=0.5,K1=0.5)
Parameter list:
name: element name
L: length
K1: normalized K1 as the MAD convention
Dx, Dy, tilt: misalignment in meter, radian
tm: transport matrix 6x6
tx,ty: twiss matrics 3x3 for x and y plane
nkick: number of kicks
tag: tag list for searching
"""
def __init__(self, name="Q01", L=0.25, K1=1, nkick=4, Dx=0, Dy=0, tilt=0, tag=[]):
self.name = str(name)
self._L = ncp.float64(L)
self._K1 = ncp.float64(K1)
self._nkick = int(nkick)
self._Dx = ncp.float64(Dx)
self._Dy = ncp.float64(Dy)
self._tilt = ncp.float64(tilt)
self.tag = tag
self._update()
def __repr__(self):
return "%s: %s,L=%g,K1=%g,tilt=%g" % (
self.name,
self.__class__.__name__,
self.L,
self.K1,
self.tilt,
)
@property
def K1(self):
return self._K1
@K1.setter
def K1(self, value):
try:
self._K1 = ncp.float64(value)
self._update()
except:
raise RuntimeError("K1 must be float (or convertible)")
def _transmatrix(self):
self._tm = ncp.eye(6)
if self.K1 > 0:
k = ncp.sqrt(self.K1)
p = k * self.L
self._tm[0:2, 0:2] = ncp.array(
[[ncp.cos(p), ncp.sin(p) / k], [-k * ncp.sin(p), ncp.cos(p)]]
)
self._tm[2:4, 2:4] = ncp.array(
[[ncp.cosh(p), ncp.sinh(p) / k], [k * ncp.sinh(p), ncp.cosh(p)]]
)
elif self.K1 < 0:
k = ncp.sqrt(-self.K1)
p = k * self.L
self._tm[0:2, 0:2] = ncp.array(
[[ncp.cosh(p), ncp.sinh(p) / k], [k * ncp.sinh(p), ncp.cosh(p)]]
)
self._tm[2:4, 2:4] = ncp.array(
[[ncp.cos(p), ncp.sin(p) / k], [-k * ncp.sin(p), ncp.cos(p)]]
)
else:
super(quad, self)._transmatrix()
if self.tilt != 0.0:
r1 = rotmat(-self.tilt)
r0 = rotmat(self.tilt)
self._tm = r1.dot(self.tm).dot(r0)
def _update(self):
"""
update transport (tm) and Twiss (tx,ty) matrices with current
element parameters, settings for 4th order symplectic pass
"""
super(quad, self)._update()
self._setSympass()
def _setSympass(self):
"""
set symplectic pass
"""
if self.K1 == 0 or self.L == 0:
attrlist = ["_dL", "_Ma", "_Mb", "_K1Lg", "_K1Ld"]
for al in attrlist:
if hasattr(self, al):
delattr(self, al)
return
a = 0.675603595979828664
b = -0.175603595979828664
g = 1.351207191959657328
d = -1.702414383919314656
self._dL = self.L / self.nkick
self._Ma = ncp.eye(6)
self._Ma[0, 1] = a * self._dL
self._Ma[2, 3] = self._Ma[0, 1]
self._Mb = ncp.eye(6)
self._Mb[0, 1] = b * self._dL
self._Mb[2, 3] = self._Mb[0, 1]
self._K1Lg = g * self.K1 * self._dL
self._K1Ld = d * self.K1 * self._dL
def sympass4(self, x, fast=1):
"""
implement 4th order symplectic tracking with given initial conditions
"""
if not fast:
with nvtx.annotate("Re-shaping", color="blue"):
x = ncp.array(x, dtype=ncp.float64).reshape(6, -1)
if self.K1 == 0 or self.L == 0:
return super(quad, self).sympass4(x)
else:
with nvtx.annotate("Global-to-Local", color="yellow"):
if self.Dx != 0:
x[0] -= self.Dx
if self.Dy != 0:
x[2] -= self.Dy
if self.tilt != 0:
x = rotmat(self.tilt).dot(x)
if nb_cuda is None:
with nvtx.annotate("Non-Numba", color="green"):
S = 0.0
for i in range(self.nkick):
with nvtx.annotate("Ma1", color="blue"):
x1p, y1p = x[1], x[3]
x = self._Ma.dot(x)
x[1] -= self._K1Lg * x[0] / (1.0 + x[5])
x[3] += self._K1Lg * x[2] / (1.0 + x[5])
with nvtx.annotate("Mb1", color="green"):
x = self._Mb.dot(x)
x[1] -= self._K1Ld * x[0] / (1.0 + x[5])
x[3] += self._K1Ld * x[2] / (1.0 + x[5])
with nvtx.annotate("Mb2", color="red"):
x = self._Mb.dot(x)
x[1] -= self._K1Lg * x[0] / (1.0 + x[5])
x[3] += self._K1Lg * x[2] / (1.0 + x[5])
with nvtx.annotate("Ma2", color="yellow"):
x = self._Ma.dot(x)
x2p, y2p = x[1], x[3]
xp, yp = (x1p + x2p) / 2, (y1p + y2p) / 2
with nvtx.annotate("avg", color="magenta"):
# --- average slope at entrance and exit
S += (
ncp.sqrt(1.0 + ncp.square(xp) + ncp.square(yp))
* self._dL
)
else:
if False:
with nvtx.annotate("Pre-allocation", color="blue"):
Z = ncp.zeros_like(x)
S = ncp.zeros(x.shape[1])
xp = ncp.zeros_like(S)
yp = ncp.zeros_like(S)
with nvtx.annotate("Numba Setup", color="green"):
threadsperblock = (32, 32)
blockspergrid_x = math.ceil(x.shape[0] / threadsperblock[0])
blockspergrid_y = math.ceil(x.shape[1] / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)
for i in range(self.nkick):
with nvtx.annotate(f"quad-kick{i+1}", color="red"):
cuda_sympass4_quad[blockspergrid, threadsperblock](
x,
Z,
S,
xp,
yp,
self._Ma,
self._Mb,
self._K1Lg,
self._K1Ld,
self._dL,
)
Z *= 0.0
elif False: # NOT Working
with nvtx.annotate("Pre-allocation", color="blue"):
Z = ncp.zeros_like(x)
S = ncp.zeros(x.shape[1])
xp = ncp.zeros_like(S)
yp = ncp.zeros_like(S)
x1p = ncp.zeros_like(S)
y1p = ncp.zeros_like(S)
x2p = ncp.zeros_like(S)
y2p = ncp.zeros_like(S)
with nvtx.annotate("Numba Setup", color="green"):
threadsperblock = (32, 32)
blockspergrid_x = math.ceil(x.shape[0] / threadsperblock[0])
blockspergrid_y = math.ceil(x.shape[1] / threadsperblock[1])
blockspergrid = (blockspergrid_x, blockspergrid_y)
print([blockspergrid, threadsperblock])
with nvtx.annotate(f"quad-kicks", color="red"):
cuda_sympass4_quad_for_loop[blockspergrid, threadsperblock](
# self.nkick,
x,
Z,
S,
xp,
yp,
x1p,
y1p,
x2p,
y2p,
self._Ma,
self._Mb,
self._K1Lg,
self._K1Ld,
self._dL,
)
else: # From Jonathan Dursi
with nvtx.annotate("Pre-allocation", color="blue"):
S = ncp.zeros(x.shape[1])
with nvtx.annotate(f"quad-kicks", color="red"):
_, n = x.shape
nthreads = 128
nblocks = (n + nthreads - 1) // nthreads
quad_sympass4_numba[nblocks, nthreads](
x,
self._K1Lg,
self._K1Ld,
self._Ma,
self._Mb,
self.nkick,
self._dL,
n,
S,
)
with nvtx.annotate("Local-to-Global", color="yellow"):
if self.tilt != 0:
x = rotmat(-self.tilt).dot(x)
if self.Dy != 0:
x[2] += self.Dy
if self.Dx != 0:
x[0] += self.Dx
with nvtx.annotate("Pathlength adj.", color="blue"):
x[4] += S - self.L
return x
class matr(drif):
"""
class matr: define a linear element with its given 6x6 matrix
usage: M01 = matr(name='M01',tm=ncp.eye(6),Dx=0,Dy=0,tilt=0,tag=[])
Parameter list:
name: element name
L: length
K1: normalized K1 as the MAD convention
Dx, Dy, tilt: misalignment in meter, radian
tm: transport matrix 6x6
tx,ty: twiss matrics 3x3 for x and y plane
tag: tag list for searching
"""
def __init__(self, name="MAT01", L=0, tm=ncp.eye(6), Dx=0, Dy=0, tilt=0, tag=[]):
self.name = str(name)
self._L = ncp.float64(L)
self._tm = ncp.array(tm).reshape(6, 6)
self._Dx = ncp.float64(Dx)
self._Dy = ncp.float64(Dy)
self._tilt = ncp.float64(tilt)
self.tag = tag
self._update()
@property
def tm(self):
return self._tm
@tm.setter
def tm(self, value):
try:
self._tm = ncp.array(value).reshape(6, 6)
self._update()
except:
raise RuntimeError("tm must be 6x6 float (or convertible)")
def _transmatrix(self):
"""
if the given matrix is not symplectic, print warning
"""
if abs(ncp.linalg.det(self.tm) - 1.0) > 1.0e-6:
print("warning: %s's linear matrix is not symplectic" % self.name)
if self.tilt != 0.0:
r1 = rotmat(-self.tilt)
r0 = rotmat(self.tilt)
self._tm = r1.dot(self.tm).dot(r0)
def sympass4(self, x, fast=1):
"""
path-length calculation is using the average of slopes at both
entrance and exit, which might not be so accurate
"""
if not fast:
x = ncp.array(x, dtype=ncp.float64).reshape(6, -1)
x1p, y1p = x[1], x[3]
x = ncp.dot(self.tm, x)
x2p, y2p = x[1], x[3]
xp, yp = (x1p + x2p) / 2, (y1p + y2p) / 2
x[4] += (ncp.sqrt(1.0 + ncp.square(xp) + ncp.square(yp)) - 1.0) * self.L
return x
class moni(drif):
"""
class moni: define monitor (BPM) with a default length 0
usage: BPM01 = moni(name='BPM01',L=0,Dx=0,Dy=0,tilt=0,tag=[])
Parameter list:
name: element name
L: length
Dx, Dy, tilt: misalignment in meter, radian
tm: transport matrix 6x6
tx,ty: twiss matrics 3x3 for x and y plane
tag: tag list for searching
"""
def __init__(self, name="BPM01", L=0, Dx=0, Dy=0, tilt=0, tag=[]):
self.name = str(name)
self._L = ncp.float64(L)
self._Dx = ncp.float64(Dx)
self._Dy = ncp.float64(Dy)
self._tilt = ncp.float64(tilt)
self._update()
class rfca(drif):
"""
class rfca: define RF cavity with given parameters
usage: RFC01 = rfca(name='RFC01',voltage=2e6,freq=0.5e9,L=0)
Parameter list:
name: element name
L: length
Dx, Dy, tilt: misalignment in meter, radian
tm: transport matrix 6x6
tx,ty: twiss matrics 3x3 for x and y plane
tag: tag list for searching
voltage: RF cavity voltage in V
freq: RF cavity frequency in Hz
phase: RF acclerator phase in degree
"""
def __init__(
self,
name="RFC01",
L=0,
voltage=2e6,
freq=0.5e9,
phase=0,
Dx=0,
Dy=0,
tilt=0,
tag=[],
):
self.name = str(name)
self._L = ncp.float64(L)
self._Dx = ncp.float64(Dx)
self._Dy = ncp.float64(Dy)
self._tilt = ncp.float64(tilt)
self._voltage = ncp.float64(voltage)
self._freq = ncp.float64(freq)
self._phase = ncp.float64(phase)
self.tag = []