-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrustbca.py
1703 lines (1419 loc) · 65.3 KB
/
rustbca.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
import os
import time
import toml
import numpy as np
from shapely.geometry import Point, Polygon, box
from scipy import constants
import matplotlib.pyplot as plt
from matplotlib import rcParams, cm
import matplotlib as mpl
import matplotlib.colors as colors
from materials import *
from formulas import *
#from generate_ftridyn_input import *
rcParams.update({'figure.autolayout': True})
#Constants
Q = constants.physical_constants["elementary charge"][0]
PI = constants.pi
AMU = constants.physical_constants["unified atomic mass unit"][0]
ANGSTROM = constants.angstrom
MICRON = constants.micro
NM = constants.nano
CM = constants.centi
EPS0 = constants.epsilon_0
A0 = constants.physical_constants["Bohr radius"][0]
K = constants.physical_constants["atomic unit of permittivity"][0]
ME = constants.physical_constants["electron mass"][0]
SQRTPI = np.sqrt(PI)
SQRT2PI = np.sqrt(2 * PI)
C = constants.physical_constants["speed of light in vacuum"][0]
INTERPOLATED = "INTERPOLATED"
LOW_ENERGY_NONLOCAL = "LOW_ENERGY_NONLOCAL"
LOW_ENERGY_LOCAL= "LOW_ENERGY_LOCAL"
LOW_ENERGY_EQUIPARTITION = "LOW_ENERGY_EQUIPARTITION"
LIQUID = "LIQUID"
GASEOUS = "GASEOUS"
MOLIERE = "MOLIERE"
KR_C = "KR_C"
ZBL = "ZBL"
LENZ_JENSEN = "LENZ_JENSEN"
QUADRATURE = "MENDENHALL_WELLER"
MAGIC = "MAGIC"
def do_trajectory_plot(name, thickness=None, depth=None, boundary=None, plot_final_positions=True, plot_origins=True, show=True):
'''
Plots trajectories of ions and recoils from [name]trajectories.output.
Optionally marks final positions/origins and draws material geometry.
Geometry input is in same length_unit as the rustbca particles.
Args:
name (string): name of rustbca simulation
thickness list(float): thickness of target, or None to not draw target
depth list(float): depth of target, or None to not draw target
boundary list((float, float)): points that make up boundary, or None to not draw boundary
plot_final_positions (bool): mark final positions (reflected: X sputtered: * deposited ^)
plot_origins (bool): mark originating locations of particles (o)
show (bool): whether or not to show plots
'''
reflected = np.atleast_2d(np.genfromtxt(name+'reflected.output', delimiter=','))
sputtered = np.atleast_2d(np.genfromtxt(name+'sputtered.output', delimiter=','))
deposited = np.atleast_2d(np.genfromtxt(name+'deposited.output', delimiter=','))
trajectories = np.atleast_2d(np.genfromtxt(name+'trajectories.output', delimiter=','))
trajectory_data = np.atleast_1d(np.genfromtxt(name+'trajectory_data.output', delimiter=',').transpose().astype(int))
if np.size(trajectories) > 0:
min_Z = np.min(trajectories[:, 1])
max_Z = np.max(trajectories[:, 1])
colormap = cm.ScalarMappable(norm=colors.SymLogNorm( min_Z*4, vmin=min_Z, vmax=max_Z), cmap='tab20')
fig1, axis1 = plt.subplots()
index = 0
x_max = 0
if np.size(trajectories) > 0:
for trajectory_length in trajectory_data:
M = trajectories[index, 0]
Z = trajectories[index, 1]
E = trajectories[index:(trajectory_length + index), 2]
x = trajectories[index:(trajectory_length + index), 3]
y = trajectories[index:(trajectory_length + index), 4]
z = trajectories[index:(trajectory_length + index), 5]
if np.max(x) > x_max:
x_max = np.max(x)
if plot_origins: plt.scatter(x[0], y[0], color=colormap.to_rgba(Z), marker='.', s=5)
plt.plot(x, y, color = colormap.to_rgba(Z), linewidth = 1)
index += trajectory_length
if plot_final_positions:
if np.size(sputtered) > 0:
sputtered_colors = [colormap.to_rgba(Z) for Z in sputtered[:,1]]
plt.scatter(sputtered[:,3], sputtered[:,4], s=50, color=sputtered_colors, marker='*')
if np.size(reflected) > 0:
reflected_colors = [colormap.to_rgba(Z) for Z in reflected[:,1]]
plt.scatter(reflected[:,3], reflected[:,4], s=50, color=reflected_colors, marker='x')
if np.size(deposited) > 0:
deposited_colors = [colormap.to_rgba(Z) for Z in deposited[:,1]]
plt.scatter(deposited[:,2], deposited[:,3], s=50, color=deposited_colors, marker='^')
if thickness and depth:
x_box = [0., 0., depth, depth, 0.]
y_box = [-thickness/2., thickness/2., thickness/2., -thickness/2., -thickness/2.]
plt.plot(x_box, y_box, color='dimgray', linewidth=3)
elif boundary:
x = [x_ for (x_, y_) in boundary]
y = [y_ for (x_, y_) in boundary]
x.append(x[0])
y.append(y[0])
plt.plot(x, y, linewidth=3, color="dimgray")
plt.xlabel('x [um]')
plt.ylabel('y [um]')
plt.title(name+' Trajectories')
plt.axis('square')
if show: plt.show()
plt.savefig(name+'trajectories_.png')
plt.close()
def do_trajectory_plot_3d(name, thickness=None, depth=None, boundary=None, plot_final_positions=True, plot_origins=True, radius=None, cube_length=None, input_file=None):
'''
Plots trajectories of ions and recoils from [name]trajectories.output.
Optionally marks final positions/origins and draws material geometry.
Geometry input is in same length_unit as the rustbca particles.
Args:
name (string): name of rustbca simulation
thickness list(float): thickness of target, or None to not draw target
depth list(float): depth of target, or None to not draw target
boundary list((float, float)): points that make up boundary, or None to not draw boundary
plot_final_positions (bool): mark final positions (reflected: X sputtered: * deposited ^)
plot_origins (bool): mark originating locations of particles (o)
show (bool): whether or not to show plots
'''
from mayavi.mlab import points3d, plot3d, mesh, triangular_mesh
reflected = np.atleast_2d(np.genfromtxt(name+'reflected.output', delimiter=','))
sputtered = np.atleast_2d(np.genfromtxt(name+'sputtered.output', delimiter=','))
deposited = np.atleast_2d(np.genfromtxt(name+'deposited.output', delimiter=','))
trajectories = np.atleast_2d(np.genfromtxt(name+'trajectories.output', delimiter=','))
trajectory_data = np.atleast_1d(np.genfromtxt(name+'trajectory_data.output', delimiter=',').transpose().astype(int))
if np.size(trajectories) > 0:
min_Z = np.min(trajectories[:, 1])
max_Z = np.max(trajectories[:, 1])
colormap = cm.ScalarMappable(norm=colors.SymLogNorm( min_Z*4, vmin=min_Z, vmax=max_Z), cmap='tab20')
index = 0
x_max = 0
min_length = 1
scale_factor = 1.0
if np.size(trajectories) > 0:
for trajectory_length in trajectory_data:
M = trajectories[index, 0]
Z = trajectories[index, 1]
E = trajectories[index:(trajectory_length + index), 2]
x = trajectories[index:(trajectory_length + index), 3]*scale_factor
y = trajectories[index:(trajectory_length + index), 4]*scale_factor
z = trajectories[index:(trajectory_length + index), 5]*scale_factor
if np.max(x) > x_max:
x_max = np.max(x)
if plot_origins: points3d(x[0], y[0], z[0], color=colormap.to_rgba(Z)[:3], scale_factor=1)
if len(x) > min_length: plot3d(x, y, z, color = colormap.to_rgba(Z)[:3], tube_radius=0.5)
index += trajectory_length
if plot_final_positions:
if np.size(sputtered) > 0:
sputtered_colors = [colormap.to_rgba(Z)[:3] for Z in sputtered[:,1]]
for x, y, z, c in zip(sputtered[:,3], sputtered[:,4], sputtered[:,5], sputtered_colors):
points3d(x*scale_factor, y*scale_factor, z*scale_factor, color=c, scale_factor=2)
if np.size(reflected) > 0:
reflected_colors = [colormap.to_rgba(Z)[:3] for Z in reflected[:,1]]
for x, y, z, c in zip(reflected[:,3], reflected[:,4], reflected[:,5], reflected_colors):
points3d(x*scale_factor, y*scale_factor, z*scale_factor, color=c, scale_factor=2)
if np.size(deposited) > 0:
deposited_colors = [colormap.to_rgba(Z)[:3] for Z in deposited[:,1]]
for x, y, z, c in zip(deposited[:,2], deposited[:,3], deposited[:,4], deposited_colors):
points3d(x*scale_factor, y*scale_factor, z*scale_factor, color=c, scale_factor=2)
if boundary:
x = [x_ for (x_, y_) in boundary]
y = [y_ for (x_, y_) in boundary]
z = [0. for (x_, y_) in boundary]
x.append(x[0])
y.append(y[0])
z.append(z[0])
plot3d(x, y, z, color=(0.1, 0.1, 0.1))
if radius:
[phi, theta] = np.mgrid[0:2 * np.pi:64j, 0:np.pi:64j]
x = np.cos(phi)*np.sin(theta)
y = np.sin(phi)*np.sin(theta)
z = np.cos(theta)
mesh(radius*x, radius*y, radius*z, color=(0.1,0.7,0.3), opacity=0.2)
if cube_length:
faces = []
xmin = -cube_length/2.*scale_factor
xmax = cube_length/2.*scale_factor
ymin = -cube_length/2.*scale_factor
ymax = cube_length/2.*scale_factor
zmin = -cube_length/2.*scale_factor
zmax = cube_length/2.*scale_factor
x,y = np.mgrid[xmin:xmax:3j,ymin:ymax:3j]
z = np.ones(y.shape)*zmin
faces.append((x,y,z))
x,y = np.mgrid[xmin:xmax:3j,ymin:ymax:3j]
z = np.ones(y.shape)*zmax
faces.append((x,y,z))
x,z = np.mgrid[xmin:xmax:3j,zmin:zmax:3j]
y = np.ones(z.shape)*ymin
faces.append((x,y,z))
x,z = np.mgrid[xmin:xmax:3j,zmin:zmax:3j]
y = np.ones(z.shape)*ymax
faces.append((x,y,z))
y,z = np.mgrid[ymin:ymax:3j,zmin:zmax:3j]
x = np.ones(z.shape)*xmin
faces.append((x,y,z))
y,z = np.mgrid[ymin:ymax:3j,zmin:zmax:3j]
x = np.ones(z.shape)*xmax
faces.append((x,y,z))
for grid in faces:
x,y,z = grid
mesh(x, y, z, opacity=0.4, color=(0.1,0.7,0.3))
if input_file:
input = toml.load(input_file)
vertices = input['geometry_input']['vertices']
triangles = input['geometry_input']['indices']
x = [vertex[0]*scale_factor for vertex in vertices]
y = [vertex[1]*scale_factor for vertex in vertices]
z = [vertex[2]*scale_factor for vertex in vertices]
triangular_mesh(x, y, z, triangles, opacity=0.3, color=(0.1, 0.7, 0.3), representation='surface')
def generate_rustbca_input(Zb, Mb, n, Eca, Ecb, Esa, Esb, Eb, Ma, Za, E0, N, N_, theta,
thickness, depth, track_trajectories=True, track_recoils=True,
track_recoil_trajectories=True, name='test_',
track_displacements=True, track_energy_losses=True,
electronic_stopping_mode=LOW_ENERGY_NONLOCAL,
weak_collision_order=3, ck=1., mean_free_path_model=LIQUID,
interaction_potential="KR_C", high_energy=False, energy_barrier_thickness=(6.306E10)**(-1/3.),
initial_particle_position = -1*ANGSTROM/MICRON, integral="MENDENHALL_WELLER",
root_finder = "DEFAULTNEWTON",
delta_x_angstrom=5., uniformly_distributed_ions=False):
'''
Generates a rustbca input file. Assumes eV, amu, and microns for units.
'''
options = {
'name': name,
'track_trajectories': track_trajectories,
'track_recoils': track_recoils,
'track_recoil_trajectories': track_recoil_trajectories,
'write_buffer_size': 8000,
'weak_collision_order': weak_collision_order,
'suppress_deep_recoils': False,
'high_energy_free_flight_paths': high_energy,
'num_threads': 8,
'num_chunks': 10,
'use_hdf5': False,
'electronic_stopping_mode': electronic_stopping_mode,
'mean_free_path_model': mean_free_path_model,
'track_displacements': track_displacements,
'track_energy_losses': track_energy_losses,
}
material_parameters = {
'energy_unit': 'EV',
'mass_unit': 'AMU',
'Eb': Eb,
'Es': Esb,
'Ec': Ecb,
'Z': Zb,
'm': Mb,
'interaction_index': np.zeros(len(n), dtype=int),
'surface_binding_model': "AVERAGE",
'bulk_binding_model': "AVERAGE"
}
dx = delta_x_angstrom*ANGSTROM/MICRON
minx, miny, maxx, maxy = 0.0, -thickness/2., depth, thickness/2.
surface = box(minx, miny, maxx, maxy)
simulation_surface = surface.buffer(10*dx, cap_style=2, join_style=2)
geometry_input = {
'length_unit': 'MICRON',
'triangles': [[0., depth, 0., thickness/2., -thickness/2., -thickness/2.], [0., depth, depth, thickness/2., thickness/2., -thickness/2.]],
'densities': [np.array(n)*(MICRON)**3, np.array(n)*(MICRON)**3],
'material_boundary_points': [[0., thickness/2.], [depth, thickness/2.], [depth, -thickness/2.], [0., -thickness/2.]],
'simulation_boundary_points': list(simulation_surface.exterior.coords),
'energy_barrier_thickness': energy_barrier_thickness,
'electronic_stopping_correction_factors': [ck, ck],
}
cosx = np.cos(theta*np.pi/180.)
sinx = np.sin(theta*np.pi/180.)
if uniformly_distributed_ions:
positions = [(initial_particle_position, np.random.uniform(-thickness/2., thickness/2.), 0.) for _ in range(N)]
else:
positions = [(initial_particle_position, 0., 0.) for _ in range(N)]
particle_parameters = {
'length_unit': 'MICRON',
'energy_unit': 'EV',
'mass_unit': 'AMU',
'N': [N_ for _ in range(N)],
'm': [Ma for _ in range(N)],
'Z': [Za for _ in range(N)],
'E': [E0 for _ in range(N)],
'Ec': [Eca for _ in range(N)],
'Es': [Esa for _ in range(N)],
'interaction_index': np.zeros(N, dtype=int),
'pos': positions,
'dir': [(cosx, sinx, 0.) for _ in range(N)],
'particle_input_filename': ''
}
input_file = {
'material_parameters': material_parameters,
'particle_parameters': particle_parameters,
'geometry_input': geometry_input,
'options': options,
}
with open(f'{name}.toml', 'w') as file:
toml.dump(input_file, file, encoder=toml.TomlNumpyEncoder())
with open(f'{name}.toml', 'a') as file:
file.write(f'root_finder = [[{root_finder}]]\n')
file.write(f'interaction_potential = [[{interaction_potential}]]\n')
file.write(f'scattering_integral = [[{integral}]]\n')
def plot_distributions_rustbca(name, beam, target,
incident_energy=1, incident_angle=0,
max_collision_contours=4, plot_2d_reflected_contours=False,
collision_contour_significance_threshold=0.1, plot_garrison_contours=False,
plot_reflected_energies_by_number_collisions=True,
plot_scattering_energy_curve=False):
'''
Plots rustbca distributions.
Args:
name (string): name of rustbca simulation.
beam (dict): ions striking target; dictionary with fields symbol and Z
target (dict): target upon which ions are incdient; dictionary with fields symbol and Z
incident_energy (float): energy in energy_units; used to scale energy spectra
incident_angle (float): angle in degrees; currently used to generate titles only
max_collision_contours (int): number of collision event contours to plot on reflected EAD; default 4
plot_2d_reflected_contours (bool): whether to plot collision event contours on reflected EAD; default False
collision_contour_significance_threshold (int): threshold of significance for contour plotting; default 0.1
../target/release/RustBCA (bool): separte reflected energy spectrum into collision number distributions; default False
plot_scattering_energy_curve (bool): plot bold, translucent white curve showing theoretical single-collision reflected energies; default False
'''
num_bins = 120
r = np.atleast_2d(np.genfromtxt(name+'reflected.output', delimiter=','))
s = np.atleast_2d(np.genfromtxt(name+'sputtered.output', delimiter=','))
d = np.atleast_2d(np.genfromtxt(name+'deposited.output', delimiter=','))
if np.size(r) > 0:
ux = r[:,6]
uy = r[:,7]
uz = r[:,8]
theta = -np.arctan2(ux, np.sqrt(uy**2 + uz**2))*180./np.pi
theta = 180. - np.arccos(ux)*180./np.pi
#theta = (np.arccos(r[:,7]) - np.pi/2.)*180./np.pi
number_collision_events = r[:, -1]
fig = plt.figure(num='polar_scatter')
ax = fig.add_subplot(111, projection='polar')
normalized_energies_rust = r[:,2]/incident_energy
c2 = ax.scatter(np.arccos(r[:,7]), normalized_energies_rust, s=1, c=number_collision_events)
plt.legend(['ftridyn'], loc='upper left')
ax.set_thetamax(180.)
ax.set_thetamin(0.)
ax.set_xlabel('E/E0')
ax.set_yticks([0., 0.5, 1.])
ax.set_xticks([0., np.pi/6., 2*np.pi/6., 3*np.pi/6., 4*np.pi/6., 5*np.pi/6., np.pi])
ax.set_xticklabels(['0', '30', '60', '90', '', '', ''])
plt.title(f'{beam["symbol"]} on {target["symbol"]} E0 = {np.round(incident_energy, 1)} eV {np.round(incident_angle, 1)} deg', fontsize='small')
plt.savefig(name+'polar_scatter.png')
plt.close()
plt.figure(num='rustbca_r2d')
bin_energy = np.linspace(0., 1.2*np.max(r[:, 2]), num_bins)
bin_angle = np.linspace(0., 90., num_bins)
bins = (bin_angle, bin_energy)
heights, xedges, yedges, image = plt.hist2d(theta, r[:, 2], bins=bins)
np.savetxt(name+'refl_ead.dat', heights)
np.savetxt(name+'refl_energies.dat', yedges)
np.savetxt(name+'refl_angles.dat', xedges)
if plot_2d_reflected_contours:
n_max = min(int(np.max(number_collision_events)), max_collision_contours)
cmap = mpl.cm.get_cmap('Wistia')
colors = [cmap((n - 1)/n_max) for n in range(1, n_max + 1)]
for k in range(1, n_max + 1):
if k < n_max:
mask = number_collision_events == k
else:
mask = number_collision_events > k
heights, xedges, yedges = np.histogram2d(r[mask, 2], theta[mask], density=True, bins=num_bins//2)
x_centers = (xedges[1:] + xedges[:-1])/2.
y_centers = (yedges[1:] + yedges[:-1])/2.
plt.contour(x_centers, y_centers, heights.transpose()/np.max(heights), levels=np.linspace(collision_contour_significance_threshold, 1., 1), colors=[colors[k - 1]], linewidths=1, linestyles='--', alpha=0.75)
norm = mpl.colors.Normalize(vmin=1, vmax=n_max)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
cbar = plt.colorbar(sm, ticks=np.array(range(1, n_max + 1))-0.5, boundaries=np.array(range(0, n_max + 1)))
cbar.set_label('# of Collision Events')
cbar_labels = list(range(1, n_max + 1))
cbar_labels[-1] = '≥'+str(cbar_labels[-1])
cbar.ax.set_yticklabels(cbar_labels)
if plot_scattering_energy_curve:
for mass in [titanium['m'], oxygen['m']]:
energies = bins[1]
angles = bins[0]*np.pi/180.
scattering_angles = -angles + np.pi
final_energies = incident_energy*((np.cos(scattering_angles) + np.sqrt((mass/beam['m'])**2 - np.sin(scattering_angles)**2))/(1. + mass/beam['m']))**2.
handle = plt.plot(angles*180./np.pi, final_energies, linestyle='-', color='white', alpha=0.25, linewidth=7)
plt.legend(handle, ['Single-Collision Scattering'], loc='lower right', fontsize='x-small')
plt.ylabel('E [eV]')
plt.xlabel('angle [deg]')
plt.title(f'Reflected EAD {beam["symbol"]} on {target["symbol"]}' , fontsize='small')
plt.savefig(name+'rustbca_r_ead.png')
plt.close()
if np.size(s) > 0:
plt.figure(num='rustbca_s2d')
bin_energy = np.linspace(0., 1.2*np.max(s[:, 2]), num_bins//2)
bin_angle = np.linspace(0., 90., num_bins//2)
bins = (bin_angle, bin_energy)
ux = s[:,6]
uy = s[:,7]
uz = s[:,8]
#theta = -np.arctan2(ux, np.sqrt(uy**2 + uz**2))
theta = 180. - np.arccos(ux)*180./np.pi
heights, xedges, yedges, image = plt.hist2d(theta, s[:, 2], bins=bins)
np.savetxt(name+'sput_ead.dat', heights)
np.savetxt(name+'sput_energies.dat', yedges)
np.savetxt(name+'sput_angles.dat', xedges)
plt.ylabel('E [eV]')
plt.xlabel('angle [deg]')
plt.title(f'Sputtered EAD {beam["symbol"]} on {target["symbol"]}' , fontsize='small')
plt.savefig(name+'rustbca_s_ead.png')
plt.close()
#Deposited ion depth distributions
if np.size(d) > 0:
plt.figure(num='d')
plots = []
labels = []
heights, bins, rust = plt.hist(d[d[:,2]>0., 2], histtype='step', bins=num_bins, density=True, color='black')
np.savetxt(name+'depo_dist.dat', heights)
np.savetxt(name+'depo_depths.dat', bins)
plots.append(rust[0])
labels.append('rustbca')
if len(plots) > 0: plt.legend(plots, labels, fontsize='small', fancybox=True, shadow=True, loc='upper right')
plt.title(f'Depth Distributions {beam["symbol"]} on {target["symbol"]} E0 = {np.round(incident_energy, 1)} eV {np.round(incident_angle, 1)} deg', fontsize='small')
plt.xlabel('x [um]')
plt.ylabel('f(x)')
#axis = plt.gca()
#axis.set_yscale('log')
plt.savefig(name+'dep.png')
plt.close()
#Reflected ion energy distributions
if np.size(r) > 0:
plt.figure(num='re')
plots = []
labels = []
heights, bins, rust = plt.hist(r[:, 2]/incident_energy, histtype='step', bins=num_bins, density=True, color='black')
number_collision_events = r[:, -1]
n_max = min(int(np.max(number_collision_events)), max_collision_contours)
cmap = mpl.cm.get_cmap('brg')
colors = [cmap((n - 1)/n_max) for n in range(1, n_max + 1)]
if plot_reflected_energies_by_number_collisions:
for k in range(1, n_max + 1):
if k < n_max:
mask = number_collision_events == k
else:
mask = number_collision_events > k
plt.hist(r[mask, 2]/incident_energy, histtype='step', bins = np.linspace(0.0, 1.0, num_bins), density=True, color=colors[k - 1])
norm = mpl.colors.Normalize(vmin=1, vmax=n_max)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
cbar = plt.colorbar(sm, ticks=np.array(range(1, n_max + 1))-0.5, boundaries=np.array(range(0, n_max + 1)))
cbar.set_label('# of Collision Events')
cbar_labels = list(range(1, n_max + 1))
cbar_labels[-1] = '≥'+str(cbar_labels[-1])
cbar.ax.set_yticklabels(cbar_labels)
plots.append(rust[0])
labels.append('rustbca')
if len(plots) > 0: plt.legend(plots, labels, fontsize='small', fancybox=True, shadow=True, loc='upper left')
plt.title(f'Refl. Energies {beam["symbol"]} on {target["symbol"]} E0 = {np.round(incident_energy, 1)} eV {np.round(incident_angle, 1)} deg', fontsize='small')
plt.xlabel('E/E0')
plt.ylabel('f(E)')
plt.gca().set_xlim(0., 1.)
plt.gca().set_ylim(bottom=0)
plt.savefig(name+'ref_e.png')
plt.close()
if np.size(s) > 0:
#Sputtered atom energy distributions
plt.figure(num='se')
plots = []
labels = []
_, _, rust = plt.hist(s[:,2], histtype='step', bins=num_bins, density=True, color='black')
plots.append(rust[0])
labels.append('rustbca')
energies = np.linspace(0., np.max(s[:,2]), num_bins*10)
de = energies[1] - energies[0]
thompson = energies/(energies + target['Es'])**(3)
thompson /= (np.sum(thompson)*de)
thompson = plt.plot(energies, thompson, linestyle='-.')
plots.append(thompson[0])
labels.append('Thompson (n=2)')
if len(plots) > 0: plt.legend(plots, labels, fontsize='small', fancybox=True, shadow=True, loc='upper right')
plt.title(f'Sputtered Energies {beam["symbol"]} on {target["symbol"]} E0 = {np.round(incident_energy, 1)} eV {np.round(incident_angle, 1)} deg', fontsize='small')
plt.xlabel('E [eV]')
plt.ylabel('f(E)')
plt.savefig(name+'spt_e.png')
plt.close()
plt.figure(num='so')
depth_origin = s[:, 10]
plt.hist(depth_origin, bins=num_bins, histtype='step', color='black')
plt.title('Depth of Origin of Sputtered Particles')
plt.xlabel('x [um]')
plt.ylabel('f(x)')
plt.savefig(name+'spt_o.png')
plt.close()
#Sputtered atom angular distributions
plt.figure(num='sa')
plots = []
labels = []
ax = None
bins = np.linspace(0, np.pi, num_bins)
if np.size(s) > 0:
hist, bins = np.histogram(np.arccos(s[:,6]), bins=bins, density=True)
rust1 = plt.polar(bins[:-1], hist/np.max(hist))
plots.append(rust1[0])
labels.append('rustbca cosx')
ax = plt.gca()
hist, bins = np.histogram(np.arccos(s[:,7]), bins=bins, density=True)
rust2 = plt.polar(bins[:-1], hist/np.max(hist))
plots.append(rust2[0])
labels.append('rustbca cosy')
ax = plt.gca()
hist, bins = np.histogram(np.arccos(s[:,8]), bins=bins, density=True)
rust3 = plt.polar(bins[:-1], hist/np.max(hist))
plots.append(rust3[0])
labels.append('rustbca cosz')
ax = plt.gca()
if len(plots) > 0: plt.legend(plots, labels, fontsize='small', bbox_to_anchor=(0.0, 1.05), fancybox=True, shadow=True, loc='upper left')
if ax:
ax.set_thetamin(0.)
ax.set_thetamax(180.)
ax.set_yticks([0., 0.5, 1.])
ax.set_xticks([0., np.pi/6., 2*np.pi/6., 3*np.pi/6., 4*np.pi/6., 5*np.pi/6., np.pi])
ax.set_xticklabels(['0', '30', '60', '90', '', '', ''])
plt.title(f'Sputtered Angles {beam["symbol"]} on {target["symbol"]} E0 = {np.round(incident_energy, 1)} eV {np.round(incident_angle, 1)} deg', fontsize='small')
plt.savefig(name+'spt_ang.png')
plt.close()
#Reflected atom angular distributions
plt.figure(num='ra')
plots = []
labels = []
ax = None
bins = np.linspace(0, np.pi, num_bins)
if np.size(r) > 0:
hist, bins = np.histogram(np.arccos(-r[:,6]), bins=bins, density=True)
rust1 = plt.polar(bins[:-1], hist/np.max(hist))
plots.append(rust1[0])
labels.append('rustbca cosx')
hist, bins = np.histogram(np.arccos(r[:,7]), bins=bins, density=True)
rust2 = plt.polar(bins[:-1], hist/np.max(hist))
plots.append(rust2[0])
labels.append('rustbca cosy')
ax = plt.gca()
hist, bins = np.histogram(np.arccos(r[:,8]), bins=bins, density=True)
rust3 = plt.polar(bins[:-1], hist/np.max(hist))
plots.append(rust3[0])
labels.append('rustbca cosz')
ax = plt.gca()
if len(plots) > 0: plt.legend(plots, labels, fontsize='small', fancybox=True, shadow=True, bbox_to_anchor=(-0.25, 0.5), loc='upper left')
if ax:
ax.set_thetamin(0.)
ax.set_thetamax(180.)
ax.set_yticks([0., 0.5, 1.])
ax.set_xticks([0., np.pi/6., 2*np.pi/6., 3*np.pi/6., 4*np.pi/6., 5*np.pi/6., np.pi])
ax.set_xticklabels(['0', '30', '60', '90', '', '', ''])
plt.title(f'Refl. Angles {beam["symbol"]} on {target["symbol"]} E0 = {np.round(incident_energy, 1)} eV {np.round(incident_angle, 1)} deg', fontsize='small')
plt.savefig(name+'ref_ang.png')
plt.close()
def plot_displacements(name, displacement_energy, num_bins=100):
'''
Plots displacements given a threshold displacement energy.
Args:
name (string): name of rustbca simulation.
displacement_energy (float): threshold energy needed to produce a permanent frenkel pair in energy_units
num_bins (int): number of histogram bins to use; default 100
'''
displacements = np.genfromtxt(f'{name}displacements.output', delimiter=',')
M = displacements[:,0]
Z = displacements[:,1]
Er = displacements[:,2]
x = displacements[Er>displacement_energy,3]
y = displacements[Er>displacement_energy,4]
plt.figure(1)
plt.hist(x, bins=num_bins, histtype='step', color='black', density=True)
plt.xlabel('x [um]')
plt.ylabel('f(x)')
plt.title(f'Frenkel Pair Production Distribution {name}')
plt.savefig(name+'displacements.png')
plt.close()
plt.figure(2)
plt.hist2d(x, y, bins=num_bins)
plt.xlabel('x [um]')
plt.ylabel('y [um]')
plt.title(f'Frenkel Pair Production {name}')
plt.savefig(name+'displacements2D.png')
plt.close()
def plot_energy_loss(name, N, num_bins=50, thickness=None, depth=None):
'''
Plots energy loss plots separated by electronic and nuclear losses from rustbca.
Args:
name (string): name of rustbca simulation
N (int): number of incident ions
num_bins (int): number of histogram bins; default 100
'''
#energy_loss = np.genfromtxt(f'{name}energy_loss.output', delimiter=',', dtype=np.float32)
energy_loss = np.loadtxt(f'{name}energy_loss.output', delimiter=',', usecols=[2,3,4,5], dtype=np.float32)
En = energy_loss[:,0]
Ee = energy_loss[:,1]
x = energy_loss[:,2]
y = energy_loss[:,3]
plt.figure(1)
plt.hist(x, weights=En/N, bins=num_bins, histtype='step', color='black')
plt.hist(x, weights=Ee/N, bins=num_bins, histtype='step', color='red')
plt.xlabel('x [um]')
plt.ylabel('E [eV/ion]')
plt.legend(['Nuclear', 'Electronic'])
plt.title(f'Energy Losses {name}')
plt.savefig(name+'energy_loss.png')
plt.close()
if depth and thickness:
num_bins = (np.linspace(0., depth, num_bins), np.linspace(-thickness/2., thickness/2., num_bins))
plt.figure(2)
plt.xlabel('x [um]')
plt.ylabel('y [um]')
#plt.axis('square')
plt.title(f'Nuclear Energy Loss {name}')
Hn, bins_x, bins_y, _ = plt.hist2d(x, y, weights=En/N, bins=num_bins, norm=colors.SymLogNorm(0.1))
plt.savefig(name+'nuclear_energy_loss.png')
plt.close()
plt.figure(3)
plt.xlabel('x [um]')
plt.ylabel('y [um]')
plt.title(f'Electronic Energy Loss {name}')
#plt.axis('square')
He, bins_x, bins_y, _ = plt.hist2d(x, y, weights=Ee/N, bins=num_bins, norm=colors.SymLogNorm(0.1))
plt.savefig(name+'electronic_energy_loss.png')
plt.close()
np.savetxt(f'{name}_electronic_energy_loss_2D.dat', He)
np.savetxt(f'{name}_electronic_energy_loss_2D_bins.dat', [bins_x, bins_y])
np.savetxt(f'{name}_nuclear_energy_loss_2D.dat', Hn)
np.savetxt(f'{name}_nuclear_energy_loss_2D_bins.dat', [bins_x, bins_y])
d = np.genfromtxt(f'{name}deposited.output', delimiter=',')
plt.figure(4)
plt.xlabel('x [um]')
plt.ylabel('y [um]')
plt.title(f'Deposition {name}')
#plt.axis('square')
plt.hist2d(d[:,2], d[:,3], bins=num_bins, norm=colors.SymLogNorm(0.1))
plt.savefig(name+'deposited2d.png')
plt.close()
def plot_all_depth_distributions(name, displacement_energy, N, num_bins=100):
'''
Plots all available depth distributions (energy losses, displacements, implantation profiles) on one plot.
Args:
name (string): name of rustbca simulation
displacement_energy (float): threshold energy needed to produce a permanent frenkel pair in energy_units
N (int): number of incident ions
num_bins (int): number of histogram bins to use; default 100
'''
energy_loss = np.genfromtxt(f'{name}energy_loss.output', delimiter=',')
M = energy_loss[:,0]
Z = energy_loss[:,1]
En = energy_loss[:,2]
Ee = energy_loss[:,3]
x = energy_loss[:,4]
y = energy_loss[:,5]
plt.figure(1)
plt.hist(x, weights=En/N, bins=num_bins, histtype='step', color='black', linewidth=2, linestyle='--', density=True)
plt.hist(x, weights=Ee/N, bins=num_bins, histtype='step', color='red', linewidth=2, linestyle='--', density=True)
plt.hist(x, weights=(Ee + En)/N, bins=num_bins, histtype='step', color='green', linewidth=2, density=True)
displacements = np.genfromtxt(f'{name}displacements.output', delimiter=',')
M = displacements[:,0]
Z = displacements[:,1]
Er = displacements[:,2]
x = displacements[Er>displacement_energy,3]
y = displacements[Er>displacement_energy,4]
plt.hist(x, bins=num_bins, histtype='step', color='blue', linewidth=2, density=True)
deposited = np.genfromtxt(f'{name}deposited.output', delimiter=',')
x = deposited[:, 2]
plt.hist(x, bins=num_bins, histtype='step', color='purple', linewidth=2, density=True)
plt.legend(['ΔE Nuclear', 'ΔE Electronic', 'ΔE Total', f'Damage Ed = {displacement_energy}', 'Deposited'])
plt.xlabel('x [um]')
plt.ylabel('A.U.')
plt.title(f'Depth Distributions {name}')
plt.savefig(name+'plot_all_depth_distributions.png')
plt.close()
def run_iead(ions, target, energies, angles, iead, name="default_", N=1):
'''
Given an IEAD in the from of a 2D array of counts, run rustbca for the ions that make up the IEAD.
Args:
ions (dict): ion dictionary (see top of file)
target (dict): target dictionary (see top of file)
energies list(float): list of energies for each column of IEAD
angles list(float): list of angles for each row of IEAD
name (string): name of rustbca simulation; default: 'default_'
N (int): number of BCA ions to run per PIC particle; default 1
'''
import itertools
energy_angle_pairs = list(itertools.product(energies, angles))
E0 = np.array([pair[0] for pair in energy_angle_pairs])
theta = np.array([pair[1] for pair in energy_angle_pairs])
#skip last row of hPIC input because it's usually garbage
N_ = np.array([iead[i, j]*N for i in range(len(energies)) for j in range(len(angles))], dtype=int)
E0 = E0[N_>0]
theta = theta[N_>0]
N_ = N_[N_>0]
Zb = [target['Z']]
Mb = [target['m']]
n = [target['n']*(MICRON)**3]
Esb = [target['Es']] #Surface binding energy
Ecb = [target['Ec']] #Cutoff energy
Eb = [target['Eb']] #Bulk binding energy
Za = ions['Z']
Ma = ions['m']
Esa = ions['Es']
Eca = ions['Ec']
thickness = 100
depth = 100
print(f'Generating input file {name}.toml')
options = {
'name': name,
'track_trajectories': False,
'track_recoils': True,
'track_recoil_trajectories': False,
'write_buffer_size': 8000,
'weak_collision_order': 3,
'suppress_deep_recoils': False,
'high_energy_free_flight_paths': False,
'num_threads': 8,
'num_chunks': 10,
'use_hdf5': False,
'electronic_stopping_mode': LOW_ENERGY_LOCAL,
'mean_free_path_model': LIQUID,
'interaction_potential': [["KR_C"]],
'scattering_integral': [["MENDENHALL_WELLER"]],
'track_displacements': True,
'track_energy_losses': False,
}
material_parameters = {
'energy_unit': 'EV',
'mass_unit': 'AMU',
'Eb': Eb,
'Es': Esb,
'Ec': Ecb,
'Z': Zb,
'm': Mb,
'interaction_index': np.zeros(len(n), dtype=int),
'surface_binding_model': "AVERAGE",
'bulk_binding_model': "AVERAGE"
}
dx = 5.*ANGSTROM/MICRON
minx, miny, maxx, maxy = 0.0, -thickness/2., depth, thickness/2.
surface = box(minx, miny, maxx, maxy)
simulation_surface = surface.buffer(10.*dx, cap_style=2, join_style=2)
geometry_input = {
'length_unit': 'MICRON',
'energy_barrier_thickness': sum(n)**(-1./3.)/np.sqrt(2.*np.pi),
'triangles': [[0., depth, 0., thickness/2., -thickness/2., -thickness/2.], [0., depth, depth, thickness/2., thickness/2., -thickness/2.]],
'densities': [n, n],
'material_boundary_points': [[0., thickness/2.], [depth, thickness/2.], [depth, -thickness/2.], [0., -thickness/2.]],
'simulation_boundary_points': list(simulation_surface.exterior.coords),
'electronic_stopping_correction_factors': [1.0, 1.0],
}
cosx = np.cos(theta*np.pi/180.)
sinx = np.sin(theta*np.pi/180.)
positions = [(-dx, 0., 0.) for _ in range(len(N_))]
particle_parameters = {
'length_unit': 'MICRON',
'energy_unit': 'EV',
'mass_unit': 'AMU',
'N': N_,
'm': [Ma for _ in range(len(N_))],
'Z': [Za for _ in range(len(N_))],
'E': E0,
'Ec': [Eca for _ in range(len(N_))],
'Es': [Esa for _ in range(len(N_))],
'interaction_index': np.zeros(len(N_), dtype=int),
'pos': positions,
'dir': [(cx, sx, 0.) for cx, sx in zip(cosx, sinx)],
'particle_input_filename': ''
}
input_file = {
'material_parameters': material_parameters,
'particle_parameters': particle_parameters,
'geometry_input': geometry_input,
'options': options,
}
with open(f'{name}.toml', 'w') as file:
toml.dump(input_file, file, encoder=toml.TomlNumpyEncoder())
with open(f'{name}.toml', 'a') as file:
file.write(r'root_finder = [[{"NEWTON"={max_iterations = 100, tolerance=1E-3}}]]')
os.system(f'../target/release/RustBCA {name}.toml')
plot_distributions_rustbca(name, ions, target, incident_energy=np.max(energies))
s = np.atleast_2d(np.genfromtxt(f'{name}sputtered.output', delimiter=','))
r = np.atleast_2d(np.genfromtxt(f'{name}reflected.output', delimiter=','))
d = np.atleast_2d(np.genfromtxt(f'{name}deposited.output', delimiter=','))
if np.size(s) > 0:
Y = np.shape(s)[0]/np.sum(N_)
if np.size(r) > 0:
R = np.shape(r)[0]/np.sum(N_)
return Y, R
def beam_target(ions, target, energy, angle, N_=10000, N=1, run_sim=True,
high_energy=False, integral='"GAUSS_LEGENDRE"',
interaction_potential='"KR_C"',
root_finder='"DEFAULTNEWTON"', tag=None,
track_trajectories = False,
plot_trajectories = False,
plot_distributions = False,
track_energy_losses = False,
track_displacements = False,
plot_depth_distributions = False,
track_recoils = True,
do_plots = False,
thickness=100,
depth=100, ck=1.,
weak_collision_order=3,
electronic_stopping_mode=LOW_ENERGY_NONLOCAL,
uniformly_distributed_ions=False,
mean_free_path_model="LIQUID"):
'''
Simplified generation of a monoenergetic, mono-angular beam on target simulation using rustbca.
'''
Zb = [target['Z']]
Mb = [target['m']]
n = [target['n']]
Esb = [target['Es']] #Surface binding energy
Ecb = [target['Ec']] #Cutoff energy
Eb = [target['Eb']] #Bulk binding energy
Za = ions['Z']
Ma = ions['m']
Esa = ions['Es']
Eca = ions['Ec']
name = ions['name']+'_'+target['name']+'_'
if tag: name += tag+'_'
pmax = (target['n']**(-1/3)/MICRON)/np.sqrt(PI)
generate_rustbca_input(Zb, Mb, n, Eca, Ecb, Esa, Esb, Eb, Ma, Za, energy, N, N_,
angle, thickness, depth, name=name, track_trajectories=track_trajectories,
track_recoil_trajectories=track_trajectories, track_energy_losses=track_energy_losses,
track_displacements=track_displacements, track_recoils=track_recoils,
electronic_stopping_mode=electronic_stopping_mode, high_energy=high_energy,
interaction_potential=interaction_potential, integral=integral,
root_finder=root_finder, delta_x_angstrom=2.*pmax*MICRON/ANGSTROM,
initial_particle_position = -2.01*pmax, weak_collision_order=weak_collision_order, ck=ck,
uniformly_distributed_ions=uniformly_distributed_ions, mean_free_path_model=mean_free_path_model)
if run_sim: os.system(f'../target/release/RustBCA {name}.toml')
if do_plots:
if track_energy_losses: plot_energy_loss(name, N*N_, num_bins=100)
if plot_depth_distributions and track_displacements and track_recoils: plot_all_depth_distributions(name, 38., N_*N, num_bins=200)
if plot_distributions: plot_distributions_rustbca(name, ions, target, incident_angle=angle, incident_energy=energy)