-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsad2xs.py
1204 lines (1015 loc) · 45.4 KB
/
sad2xs.py
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
"""
UNOFFICIAL SAD to XSuite Converter
Designed for initial import of SuperKEKB Lattice
Tested (working) on import of FCC-ee (Z) Lattice (GHC 24.3)
=============================================
Author(s): John P T Salvesen, Giovanni Iadarola
Email: [email protected]
Last Updated: 16-01-2024
"""
################################################################################
# Required Packages
################################################################################
import xtrack as xt
import numpy as np
################################################################################
# Version Information
################################################################################
__version__ = '0.2.3'
__date__ = '16-01-2024'
__author__ = 'J. Salvesen, G. Iadarola'
__email__ = '[email protected]'
################################################################################
# Conversion Function
################################################################################
def sad2xsuite(
sad_lattice_path: str,
multipole_replacements: dict = None,
ref_particle_mass0: float = None,
ref_particle_p0c: float = None,
bend_edge_model: str = 'linear',
install_markers: bool = True) -> tuple[xt.Line, dict]:
"""
Convert SAD Lattice to XSuite Lattice
############################################################################
Parameters:
############################################################################
sad_lattice_path: str
Path to the SAD lattice file
multipole_replacements: dict (optional)
Dictionary of replacements for multipole elements
Default is None
Dictionary should be of the form:
{
'element_base_string': replacement_element_type
}
Where element_base_string is the base string of the element name
and replacement_element_type is the element type to replace with
Currently supported options for replacement_element_type are:
'Bend', 'Quadrupole', 'Sextupole
ref_particle_mass0: float (optional)
Reference Particle Mass [eV]
Default is the electron mass
ref_particle_p0c: float (optional)
Reference Particle Momentum [eV/c]
Default is None, will attempt to read from SAD file
bend_edge_model: str (optional)
Model for the bend elements. Options are 'full', 'linear', 'suppressed'
Default is 'linear'
install_markers: bool (optional)
Install markers at the correct locations
Default is True
Requires slicing of thick elements
############################################################################
Outputs
############################################################################
line: xtrack.Line
XSuite Line object representing the lattice
marker_locations: dict
Dictionary of markers and their locations
"""
############################################################################
# Setup
############################################################################
########################################
# Known Element Types
########################################
sad_elements = (
'drift',
'bend', 'quad', 'sext', 'oct', 'mult',
'sol', 'cavi', 'apert',
'mark', 'moni', 'beambeam')
########################################
# Marker Replacements
########################################
# Dangerous default value {} as argument
if multipole_replacements is None:
multipole_replacements = {}
############################################################################
# Parsing Raw SAD File
############################################################################
########################################
# Load SAD File to Python
########################################
with open(sad_lattice_path, 'r', encoding="utf-8") as sad_file:
content = sad_file.read()
########################################
# Convert Formatting to XSuite Style
########################################
# Make Content Lowercase (Xsuite style)
content = content.lower()
# Correct Formatting Issues
while ' =' in content:
content = content.replace(' =', '=')
while '= ' in content:
content = content.replace('= ', '=')
while '( ' in content:
content = content.replace('( ', '(')
while ' )' in content:
content = content.replace(' )', ')')
while ' ' in content:
content = content.replace(' ', ' ')
########################################
# Angle Handling
########################################
# Ensure no spaces between the value and it's unit
content = content.replace(' deg', 'deg')
########################################
# Split the file into sections
########################################
# Semicolons are used to separate element sections
sad_sections = content.split(';')
############################################################################
# SAD File Section Cleaning
############################################################################
cleaned_sections = []
########################################
# Iterate through the sections
########################################
for section in sad_sections:
cleaned_section = section
########################################
# Remove Commented Lines
########################################
# Remove lines that start with '!'
comment_removed_section = []
for line in cleaned_section.split('\n'):
if not line.startswith('!'):
comment_removed_section.append(line)
cleaned_section = '\n'.join(comment_removed_section)
########################################
# Strip newlines and whitespace
########################################
cleaned_section = cleaned_section.strip()
########################################
# Remove Empty Sections
########################################
if len(cleaned_section) == 0:
continue
cleaned_sections.append(cleaned_section)
############################################################################
# Separation by Element Type
############################################################################
cleaned_elements = {}
cleaned_expressions = {}
cleaned_lines = {}
########################################
# Iterate through the sections
########################################
for section in cleaned_sections:
########################################
# Get the "Command" of the Section
########################################
section_command = section.split()[0]
########################################
# SAD Feature Commands
########################################
if section_command.startswith('on') or section_command.startswith('off'):
continue
########################################
# Momentum Command
########################################
if section_command.startswith('momentum'):
momentum = section
momentum = momentum.replace("momentum", "")
momentum = momentum.replace("\n", "")
momentum = momentum.replace(" ", "")
momentum = momentum.replace("=", "")
if 'kev' in momentum:
momentum = float(momentum.replace("kev", "")) * 1E3
elif 'mev' in momentum:
momentum = float(momentum.replace("mev", "")) * 1E6
elif 'gev' in momentum:
momentum = float(momentum.replace("gev", "")) * 1E9
elif 'tev' in momentum:
momentum = float(momentum.replace("tev", "")) * 1E12
elif 'ev' in momentum:
momentum = float(momentum.replace("ev", ""))
else:
try:
momentum = float(momentum)
except TypeError:
continue
cleaned_expressions['momentum'] = momentum
continue
########################################
# Mass Command
########################################
if section_command.startswith('mass'):
mass = section
mass = mass.replace("mass", "")
mass = mass.replace("\n", "")
mass = mass.replace(" ", "")
mass = mass.replace("=", "")
if 'kev' in mass:
mass = float(mass.replace("kev", "")) * 1E3
elif 'mev' in mass:
mass = float(mass.replace("mev", "")) * 1E6
elif 'gev' in mass:
mass = float(mass.replace("gev", "")) * 1E9
elif 'tev' in mass:
mass = float(mass.replace("tev", "")) * 1E12
elif 'ev' in mass:
mass = float(mass.replace("ev", ""))
else:
try:
mass = float(mass)
except TypeError:
continue
cleaned_expressions['mass'] = mass
continue
########################################
# Deferred Expressions
########################################
if section_command not in sad_elements and section_command != 'line':
########################################
# If no equals sign, skip the section
########################################
if '=' not in section:
print('Unknown Section Includes the following information:')
print(section)
continue
########################################
# Split information based on the equals sign
########################################
variable, expression = section.split('=')
########################################
# Convert to Float if Possible
########################################
if all(char in "0123456789-." for char in expression) \
and expression.count('.') <= 1 \
and expression.count('-') <= 1:
cleaned_expressions[variable] = float(expression)
continue
else:
########################################
# Check if the expression is duplicated
########################################
if variable not in cleaned_expressions:
cleaned_expressions[variable] = expression
continue
else:
########################################
# If duplicate, create new with all dependencies
########################################
previous_expression = cleaned_expressions[variable]
if isinstance(previous_expression, float):
previous_expression = str(previous_expression)
new_expression = expression.replace(
variable, previous_expression)
cleaned_expressions[variable] = new_expression
continue
########################################
# Lines
########################################
if section_command.startswith('line'):
line_section = section
line_section = line_section.replace("line", "")
line_section = line_section.replace("\n", "")
########################################
# Split into lines by closing bracket
########################################
lines = line_section.split(')')
########################################
# Process each line
########################################
for line in lines:
if len(line) == 0:
continue
line_name, line_content = line.split('=')
line_name = line_name.replace(' ', '')
line_content = line_content.replace('(', '')
line_content = line_content.replace('\n', ' ')
line_elements = []
for element in line_content.split():
if len(element) > 0:
line_elements.append(element)
cleaned_lines[line_name] = line_elements
########################################
# Elements
########################################
if section_command in sad_elements:
section_dict = {}
########################################
# Convert to Dictionary Style
########################################
element_section = section
element_section = element_section.replace(section_command, "")
element_section = element_section.replace('\n ', ' ')
element_section = element_section.replace(' \n', ' ')
element_section = element_section.replace('\n', ' ')
element_section = element_section.replace(')', '),')
########################################
# Split the section into elements
########################################
elements = element_section.split(',')
########################################
# Process each element
########################################
for element in elements:
if len(element) == 0:
continue
ele_dict = {}
while element.startswith(' '):
element = element[1:]
ele_name, ele_vars = element.split('(')
ele_name = ele_name.replace(' ', '')
ele_name = ele_name.replace('=', '')
ele_vars = ele_vars.replace(')', '')
########################################
# Process data in each element
########################################
tokens = ele_vars.split(' ')
for token in tokens:
if len(token) == 0:
continue
########################################
# Angle handling
########################################
if 'deg' in token:
token_name, token_value = token.split('=')
token_value = token_value.replace('deg', '')
token_value = float(token_value)
token_value = np.deg2rad(token_value)
token = token_name + '=' + str(token_value)
var_name, var_value = token.split('=')
try:
var_value = float(var_value)
ele_dict[var_name] = var_value
except ValueError:
ele_dict[var_name] = var_value
section_dict[ele_name] = ele_dict
########################################
# Add elements
########################################
if section_command in cleaned_elements:
cleaned_elements[section_command].update(section_dict)
else:
cleaned_elements[section_command] = section_dict
############################################################################
# Address missing momentum and mass
############################################################################
if 'mass' not in cleaned_expressions and ref_particle_mass0 is None:
raise ValueError('No mass found in SAD file or function input')
elif 'mass' not in cleaned_expressions:
print('Warning: No mass found in SAD file')
print('Using user provided value')
cleaned_expressions['mass'] = ref_particle_mass0
elif 'mass' in cleaned_expressions and ref_particle_mass0 is not None:
print('Warning: Mass found in SAD file and function input')
print('Using user provided value')
cleaned_expressions['mass'] = ref_particle_mass0
if 'momentum' not in cleaned_expressions and ref_particle_p0c is None:
raise ValueError('No momentum found in SAD file or function input')
elif 'momentum' not in cleaned_expressions:
print('Warning: No momentum found in SAD file')
print('Using user provided value')
cleaned_expressions['momentum'] = ref_particle_p0c
elif 'momentum' in cleaned_expressions and ref_particle_p0c is not None:
print('Warning: Momentum found in SAD file and function input')
print('Using user provided value')
cleaned_expressions['momentum'] = ref_particle_p0c
############################################################################
# Create Xsuite Environment
############################################################################
env = xt.Environment()
############################################################################
# Pass deferred expressions to the environment
############################################################################
########################################
# Floats first
########################################
for expression_name, expression in cleaned_expressions.items():
if isinstance(expression, float):
env[expression_name] = expression
########################################
# Strings may depend on floats
########################################
for expression_name, expression in cleaned_expressions.items():
if isinstance(expression, str):
env[expression_name] = expression
############################################################################
# Create Xsuite Elements
############################################################################
########################################
# Drift
########################################
if 'drift' in cleaned_elements:
drifts = cleaned_elements['drift']
for ele_name, ele_vars in drifts.items():
########################################
# Assert Length
########################################
if 'l' not in ele_vars:
raise ValueError(f'Error: Drift {ele_name} missing length')
########################################
# Create Element
########################################
env.new(
name = ele_name,
parent = xt.Drift,
length = ele_vars['l'])
continue
########################################
# Bend
########################################
if 'bend' in cleaned_elements:
bends = cleaned_elements['bend']
for ele_name, ele_vars in bends.items():
########################################
# Assert Length
########################################
if 'l' not in ele_vars:
print(f'Warning: Bend {ele_name} missing length ')
print('Installing unpowered 0 length bend')
env.new(
name = ele_name,
parent = xt.Bend,
length = 0,
k0 = 0,
h = 0,
edge_entry_angle = 0,
edge_exit_angle = 0,
rot_s_rad = 0)
continue
########################################
# Initialise parameters that may not be present
########################################
rotation = 0
if 'rotate' in ele_vars:
rotation = ele_vars['rotate']
e1 = 0
e2 = 0
h = 0
########################################
# Separate Bends and Kicks
########################################
# Bends have angle, and allowed to have edge angles
if 'angle' in ele_vars:
k0l = ele_vars['angle']
k0 = f"{k0l} / {ele_vars['l']}"
h = k0
if 'e1' in ele_vars:
e1 = ele_vars['e1']
if 'e2' in ele_vars:
e2 = ele_vars['e2']
# Kicks have k0, and are not allowed to have edge angles
elif 'k0' in ele_vars:
k0l = ele_vars['k0']
k0 = f"{k0l} / {ele_vars['l']}"
########################################
# User warning if highly fringed
########################################
max_fringe_ratio = 0
if 'f1' in ele_vars:
max_fringe_ratio = max(0, ele_vars['f1'] / ele_vars['l'])
if 'fb1' in ele_vars:
max_fringe_ratio = max(0, ele_vars['fb1'] / ele_vars['l'])
if 'fb2' in ele_vars:
max_fringe_ratio = max(0, ele_vars['fb2'] / ele_vars['l'])
if max_fringe_ratio > 0.25:
print(f'Warning: Bend {ele_name} has fringe ratio > 0.25 at {max_fringe_ratio}')
########################################
# Create Element
########################################
env.new(
name = ele_name,
parent = xt.Bend,
length = ele_vars['l'],
k0 = k0,
h = h,
edge_entry_angle = f"{e1} * {k0l}",
edge_exit_angle = f"{e2} * {k0l}",
rot_s_rad = rotation)
continue
########################################
# Quadrupole
########################################
if 'quad' in cleaned_elements:
quads = cleaned_elements['quad']
for ele_name, ele_vars in quads.items():
########################################
# Assert Length
########################################
if 'l' not in ele_vars:
print(f'Error: Quadrupole {ele_name} missing length and excluded')
continue
########################################
# Initialise parameters that may not be present
########################################
rotation = 0
if 'rotate' in ele_vars:
rotation = ele_vars['rotate']
########################################
# User warning if highly fringed
########################################
max_fringe_ratio = 0
if 'f1' in ele_vars:
max_fringe_ratio = max(0, ele_vars['f1'] / ele_vars['l'])
if 'fb1' in ele_vars:
max_fringe_ratio = max(0, ele_vars['fb1'] / ele_vars['l'])
if 'fb2' in ele_vars:
max_fringe_ratio = max(0, ele_vars['fb2'] / ele_vars['l'])
if max_fringe_ratio > 0.25:
print(f'Warning: Quad {ele_name} has fringe ratio > 0.25 at {max_fringe_ratio}')
########################################
# Create Element
########################################
# TODO: Better to do k1 and k1s native + rotation?
env.new(
name = ele_name,
parent = xt.Quadrupole,
length = ele_vars['l'],
k1 = f"{ele_vars['k1']} / {ele_vars['l']} *\
{np.cos(rotation * 2)}",
k1s = f"{ele_vars['k1']} / {ele_vars['l']} *\
{np.sin(rotation * 2)}")
continue
########################################
# Sextupole
########################################
if 'sext' in cleaned_elements:
sexts = cleaned_elements['sext']
for ele_name, ele_vars in sexts.items():
########################################
# Assert Length
########################################
if 'l' not in ele_vars:
print(f'Error: Sextupole {ele_name} missing length and excluded')
continue
########################################
# Initialise parameters that may not be present
########################################
rotation = 0
if 'rotate' in ele_vars:
rotation = ele_vars['rotate']
########################################
# Create Element
########################################
# TODO: Better to do k1 and k1s native + rotation?
env.new(
name = ele_name,
parent = xt.Sextupole,
length = ele_vars['l'],
k2 = f"{ele_vars['k2']} / {ele_vars['l']} *\
{np.cos(rotation * 3)}",
k2s = f"{ele_vars['k2']} / {ele_vars['l']} *\
{np.sin(rotation * 3)}")
continue
########################################
# Octupole
########################################
if 'oct' in cleaned_elements:
octs = cleaned_elements['oct']
for ele_name, ele_vars in octs.items():
########################################
# Initialise parameters that may not be present
########################################
rotation = 0
if 'rotate' in ele_vars:
rotation = ele_vars['rotate']
k0l = 0
if 'k0' in ele_vars:
k0l = ele_vars['k0']
k1l = 0
if 'k1' in ele_vars:
k1l = ele_vars['k1']
k2l = 0
if 'k2' in ele_vars:
k2l = ele_vars['k2']
k3l = 0
if 'k3' in ele_vars:
k3l = ele_vars['k3']
knl = [
f"{k0l} * {np.cos(rotation)}" if k0l != 0 else 0,
f"{k1l} * {np.cos(rotation * 2)}" if k1l != 0 else 0,
f"{k2l} * {np.cos(rotation * 3)}" if k2l != 0 else 0,
f"{k3l} * {np.cos(rotation * 4)}" if k3l != 0 else 0]
ksl = [
f"{k0l} * {np.sin(rotation)}" if k0l != 0 else 0,
f"{k1l} * {np.sin(rotation * 2)}" if k1l != 0 else 0,
f"{k2l} * {np.sin(rotation * 3)}" if k2l != 0 else 0,
f"{k3l} * {np.sin(rotation * 4)}" if k3l != 0 else 0]
########################################
# Thin lens, or drift kick drift
########################################
if 'l' in ele_vars:
if ele_vars['l'] != 0:
env.new(
f'{ele_name}_drift_i', xt.Drift,
length = f"{ele_vars['l']} / 2")
env.new(
f'{ele_name}_drift_o', xt.Drift,
length = f"{ele_vars['l']} / 2")
env.new(
f'{ele_name}_kick', xt.Multipole,
knl = knl, ksl = ksl)
env.new_line(
name = ele_name,
components = [
f'{ele_name}_drift_i',
f'{ele_name}_kick',
f'{ele_name}_drift_o'])
continue
else:
env.new(f'{ele_name}', xt.Multipole, knl = knl, ksl = ksl)
continue
########################################
# Multipole
########################################
if 'mult' in cleaned_elements:
mults = cleaned_elements['mult']
for ele_name, ele_vars in mults.items():
########################################
# Initialise parameters that may not be present
########################################
length = 0
if 'l' in ele_vars:
length = ele_vars['l']
rotation = 0
if 'rotate' in ele_vars:
rotation = ele_vars['rotate']
knl = []
for kn in range(0, 21):
knl.append(0)
if f'k{kn}' in ele_vars:
knl[kn] = ele_vars[f'k{kn}']
ksl = []
for ks in range(0, 21):
ksl.append(0)
if f'sk{ks}' in ele_vars:
ksl[ks] = ele_vars[f'sk{ks}']
########################################
# User Defined Multipole Replacements
########################################
if any(ele_name.startswith(test_key) for test_key in multipole_replacements):
replace_type = None
if not 'l' in ele_vars:
print('Warning: Multipole replacement not supported for thin lens')
print(f'Installing element {ele_name} as normal multipole')
env.new(
f'{ele_name}', xt.Multipole,
knl = knl, ksl = ksl, rot_s_rad = rotation)
continue
# Search the multipole replacements dict for the type of element
for replacement in multipole_replacements:
if ele_name.startswith(replacement):
replace_type = multipole_replacements[replacement]
########################################
# Bend Replacement (kick)
########################################
k0 = 0
if 'k0' in ele_vars:
k0 = f"{ele_vars['k0']} / {ele_vars['l']}"
if replace_type == 'Bend':
env.new(
name = ele_name,
parent = xt.Bend,
length = ele_vars['l'],
k0 = k0,
h = 0,
edge_entry_angle = 0,
edge_exit_angle = 0,
rot_s_rad = rotation)
continue
########################################
# Quadrupole Replacement
########################################
k1 = 0
k1s = 0
if 'k1' in ele_vars:
k1 = f"{ele_vars['k1']} / {ele_vars['l']} * {np.cos(rotation * 2)}"
k1s = f"{ele_vars['k1']} / {ele_vars['l']} * {np.sin(rotation * 2)}"
elif replace_type == 'Quadrupole':
# TODO: Better to do k1 and k1s native + rotation?
env.new(
name = ele_name,
parent = xt.Quadrupole,
length = ele_vars['l'],
k1 = k1,
k1s = k1s)
continue
########################################
# Sextupole Replacement
########################################
k2 = 0
k2s = 0
if 'k2' in ele_vars:
k2 = f"{ele_vars['k2']} / {ele_vars['l']} * {np.cos(rotation * 3)}"
k2s = f"{ele_vars['k2']} / {ele_vars['l']} * {np.sin(rotation * 3)}"
elif replace_type == 'Sextupole':
env.new(
name = ele_name,
parent = xt.Sextupole,
length = ele_vars['l'],
k2 = k2,
k2s = k2s)
continue
else:
raise ValueError('Error: Unknown element replacement')
########################################
# Elements stored as multipole, but really something simpler
########################################
if (length != 0 and knl[1] == 0 and ksl[1] == 0 \
and knl[2] == 0 and ksl[2] == 0) \
and (knl[0] != 0 or ksl[0] != 0):
# Then it's a bend
env.new(
name = ele_name,
parent = xt.Bend,
length = ele_vars['l'],
k0 = f"sqrt({knl[0]}**2 + {ksl[0]}**2) / {ele_vars['l']}",
h = 0,
edge_entry_angle = 0,
edge_exit_angle = 0,
rot_s_rad = rotation)
continue
elif (length != 0 and knl[0] == 0 and ksl[0] == 0 \
and knl[2] == 0 and ksl[2] == 0) \
and (knl[1] != 0 or ksl[1] != 0):
# Then it's a quadrupole
env.new(
name = ele_name,
parent = xt.Quadrupole,
length = ele_vars['l'],
k1 = f"{knl[1]} / {ele_vars['l']}",
k1s = f"{ksl[1]} / {ele_vars['l']}")
continue
elif (length != 0 and knl[0] == 0 and ksl[0] == 0 \
and knl[1] == 0 and ksl[1] == 0) \
and (knl[2] != 0 or ksl[2] != 0):
# Then it's a sextupole
env.new(
name = ele_name,
parent = xt.Sextupole,
length = ele_vars['l'],
k2 = f"{knl[2]} / {ele_vars['l']}",
k2s = f"{ksl[2]} / {ele_vars['l']}")
continue
########################################
# Else True multipole
########################################
if 'l' in ele_vars:
if ele_vars['l'] != 0:
env.new(f'{ele_name}_drift_i', xt.Drift,
length = f"{ele_vars['l']} / 2")
env.new(f'{ele_name}_drift_o', xt.Drift,
length = f"{ele_vars['l']} / 2")
env.new(f'{ele_name}_kick', xt.Multipole,
knl = knl,
ksl = ksl,
rot_s_rad = rotation)
env.new_line(
name = ele_name,
components = [
f'{ele_name}_drift_i',
f'{ele_name}_kick',
f'{ele_name}_drift_o'])
continue
else:
env.new(
f'{ele_name}', xt.Multipole,
knl = knl, ksl = ksl, rot_s_rad = rotation)
continue
########################################
# Cavities
########################################
if 'cavi' in cleaned_elements:
cavis = cleaned_elements['cavi']
for ele_name, ele_vars in cavis.items():
########################################
# Initialise parameters that may not be present
########################################
phi = 0
if 'phi' in ele_vars:
phi = ele_vars['phi']
freq = 0
if 'freq' in ele_vars:
freq = ele_vars['freq']
if 'harm' in ele_vars:
print('Warning: Harmonic numbers not implemented')
########################################
# Create Element
########################################
env.new(
name = ele_name,
parent = xt.Cavity,
voltage = ele_vars['volt'],
frequency = freq,
lag = phi)
continue
########################################
# Apertures
########################################
if 'apert' in cleaned_elements:
aperts = cleaned_elements['apert']
for ele_name, ele_vars in aperts.items():
########################################
# Create Element
########################################
env.new(
name = ele_name,
parent = xt.LimitEllipse,
a = ele_vars['ax'],
b = ele_vars['ay'])
continue
########################################
# Solenoid (only geometric effect)
########################################
if 'sol' in cleaned_elements:
solenoids = cleaned_elements['sol']
for ele_name, ele_vars in solenoids.items():
# TODO: Decide on solenoid implementation
if 'dz' in ele_vars:
env.new(
name = ele_name,
parent = xt.Solenoid,
length = ele_vars['dz'])
continue
else:
env.new(
name = ele_name,
parent = xt.Solenoid)
continue
########################################
# Markers (all types)
########################################
if 'mark' in cleaned_elements:
marks = cleaned_elements['mark']
for ele_name, ele_vars in marks.items():
env.new(
name = ele_name,
parent = xt.Marker)