-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxraytools.py
2881 lines (2605 loc) · 87.8 KB
/
xraytools.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
# utility functions for xray studies
import os
import numpy as np
from scipy.interpolate import interp1d
from scipy.special import dawsn, expi
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import xraylib as xl
import requests
def goodID(matID, item=None):
""" Check if the material ID is defined:
item = None, in xraylib
'density', in density dictionary
'Cp', in heat capacity dictionary
'crystal', in crystal dictionary
"""
good = True
id = matID
if item == 'density':
if matID not in Density:
print('Cannot find the density of ' + matID)
good = False
if item == 'Cp':
if matID not in specificHeatParams and matID not in specificHeat:
print('Cannot find the specific heat of ' + matID)
good = False
if item == 'crystal':
if matID not in latticeType:
print('Cannot find the lattice type of ' + matID)
good = False
if matID not in latticeParameters:
print('Cannot find the lattice parameters of ' + matID)
good = False
else:
if matID in alias:
id = alias[matID]
else:
id = matID
try:
_ = xl.CompoundParser(id)
except: # noqa: E722
print('Cannot find ' + matID + ' in xraylib')
good = False
if not good:
raise Exception('STOP: Missing material properties.')
return id
def eV(E):
""" Returns photon energy in eV if specified in eV or keV """
if np.max(E) < 100:
return E * 1000
else:
return E
def keV(E):
""" Returns photon energy in keV if specified in eV or keV """
if np.min(E) >= 100:
return E / 1000
else:
return E
def lam(E):
""" Computes photon wavelength in m
E is photon energy in eV
"""
return (12398.4/E)*1e-10
def lam2E(l): # noqa: E741
""" Computes photon energy in eV
l is photon wavelength in m
"""
E=12398.4/(l*u['ang'])
return E
def lam2f(l): # noqa: E741
""" Computes the photon frequency in Hz
l is photon wavelength in m
"""
f=c['c']/l
return f
def f2lam(f):
""" Computes the photon wavelength in m
f is the photon frequency in Hz
"""
l=c['c']/f # noqa: E741
return l
def f2E(f):
""" Computes the photon in energy in eV
f is the photon frequency in Hz
"""
E=c['h']*f*u['eV']
return E
def E2f(E):
""" Computes the photon frequency in Hz
E is photon energy in eV or keV
"""
f=E/c['h']/u['eV']
return f
def sind(A):
""" Sin of an angle specified in degrees """
Arad = np.deg2rad(A)
x = np.sin(Arad)
return x
def cosd(A):
""" Cos of an angle specified in degrees """
Arad = np.deg2rad(A)
x = np.cos(Arad)
return x
def tand(A):
""" Tan of an angle specified in degrees """
Arad = np.deg2rad(A)
x = np.tan(Arad)
return x
def asind(x):
""" Arcsin in degrees """
A = np.arcsin(x)
A = np.rad2deg(A)
return A
def acosd(x):
""" Arccos in degrees """
A = np.arccos(x)
A = np.rad2deg(A)
return A
def atand(x):
""" Arctan in degrees """
A = np.arctan(x)
A = np.rad2deg(A)
return A
def defaultDensity(matID):
""" Default material density """
mat = goodID(matID)
if matID in Density:
density = Density[matID]
else:
density = Density[mat]
return density
def atomWeight(matID):
""" Return the average atom weight in g/mol """
mat = goodID(matID)
compound = xl.CompoundParser(mat)
mass = 0.0
for i in range(compound['nElements']):
mass += xl.AtomicWeight(compound['Elements'][i]) * compound['massFractions'][i]
return mass
def molarMass(matID):
""" Return the molar mass as g/mol """
mat = goodID(matID)
compound = xl.CompoundParser(mat)
return atomWeight(matID) * compound['nAtomsAll']
def mu(matID, keV, density=None):
""" Calculate the mass attenuation coefficients (1/m) at given energies
keV: energy in keV (vectorized)
density in g/cm3, None=default density
"""
mat = goodID(matID)
if density is None:
density = defaultDensity(matID)
if np.isscalar(keV):
energies = np.array([keV], dtype=np.double)
else:
energies = np.array(keV, dtype=np.double)
_mu = np.array([xl.CS_Total_CP(mat, eng) * density * u['cm'] for eng in energies])
if np.isscalar(keV):
# return np.asscalar(_mu), numpy-asscalar() has been deprecated since NumPy 1.16
return _mu.item()
else:
return _mu
def mu_en(matID, keV, density=None):
""" Calculate the mass energy-absorption coefficients (1/m) at given energies
keV: energy in keV (vectorized)
density in g/cm3, None=default density
"""
mat = goodID(matID)
if density is None:
density = defaultDensity(matID)
if np.isscalar(keV):
energies = np.array([keV], dtype=np.double)
else:
energies = np.array(keV, dtype=np.double)
_mu = np.array([xl.CS_Energy_CP(mat, eng) * density * u['cm'] for eng in energies])
if np.isscalar(keV):
return _mu.item()
else:
return _mu
def attenuationLength(matID, keV, density=None):
""" Calculate the attenuation length (m) at given energies
E in keV (vectorized)
density in g/cm3, None=default density
"""
return 1.0 / mu(matID, keV, density)
def transmission(matID, t, keV, density=None):
""" Calculate the transmission at given thickness and energies
t: thickness in m
E: energies in keV (vectorized)
density: in g/cm3, None=default density
"""
return np.exp(-mu(matID, keV, density) * t)
def eVatom(matID, keV, mJ, rms_mm, density=None):
""" Calculate the eV/atom at given energies
keV: energies in keV (vectorized)
mJ: pulse energy in mJ (vectorized)
rms_mm: beam size radius in mm (vectorized)
-- E, mJ, rms_mm must match if more than one are vectorized
density: in g/cm3, None=default density
"""
if density is None:
density = defaultDensity(matID)
attL = attenuationLength(matID, keV, density)
EdensityJcm3 = mJ/1000 / (2 * np.pi * attL*u['cm'] * (rms_mm*0.1)**2)
atomVolcm3 = atomWeight(matID) / c['NA'] / density
natoms = xl.CompoundParser(matID)['nAtomsAll']
return EdensityJcm3 * atomVolcm3 / 1.6e-19 / natoms
def eVatom_en(matID, keV, mJ, rms_mm, density=None):
""" Calculate the eV/atom at given energies with mu_en
keV: energies in keV (vectorized)
mJ: pulse energy in mJ (vectorized)
rms_mm: beam size radius in mm (vectorized)
-- E, mJ, rms_mm must match if more than one are vectorized
density: in g/cm3, None=default density
"""
if density is None:
density = defaultDensity(matID)
attL = 1.0 / mu_en(matID, keV, density)
EdensityJcm3 = mJ/1000 / (2 * np.pi * attL*u['cm'] * (rms_mm*0.1)**2)
atomVolcm3 = atomWeight(matID) / c['NA'] / density
natoms = xl.CompoundParser(matID)['nAtomsAll']
return EdensityJcm3 * atomVolcm3 / 1.6e-19 / natoms
def eVatom_keV_plot(matID, keV, mJ, rms_mm, density=None, logx=False, logy=True):
if not isinstance(matID, list):
matID = [matID]
xlist = None
inp_names = ['keV', 'mJ', 'rms_mm']
for inp, name in zip([keV, mJ, rms_mm], inp_names):
if isinstance(inp, (np.ndarray, list)):
if xlist is None:
xlist = inp
xlabel = name
else:
raise Exception('Only one variable of keV, mJ and rms_mm can be an array or list.')
if xlist is None:
for mat in matID:
eVatoms = eVatom(mat, keV, mJ, rms_mm, density)
print('{:s}: {:.2g} eV/atom'.format(mat, eVatoms))
else:
plt.figure(figsize=(5,3), dpi=100, facecolor='white')
for mat in matID:
eVatoms = eVatom(mat, keV, mJ, rms_mm, density)
if logx:
if logy:
plt.loglog(xlist, eVatoms, label=mat)
else:
plt.semilogx(xlist, eVatoms, label=mat)
plt.ylim(0)
plt.gca().xaxis.set_major_formatter(ScalarFormatter())
else:
if logy:
plt.semilogy(xlist, eVatoms, label=mat)
else:
plt.plot(xlist, eVatoms, label=mat)
plt.ylim(0)
if xlabel=='keV':
plt.title('Dose from {:.1f} mJ {:.2g} mm (rms) pulse'.format(mJ, rms_mm))
elif xlabel=='mJ':
plt.title('Dose from {:.1f} keV {:.2g} mm (rms) pulse'.format(keV, rms_mm))
elif xlabel=='rms_mm':
plt.title('Dose from {:.1f} keV {:.1f} mJ pulse'.format(keV, mJ))
plt.xlabel(xlabel)
plt.ylabel('eV/atom')
plt.grid(axis='both', which='both')
plt.legend()
plt.tight_layout()
plt.show()
def drillSpeed(matID, power_W, FWHM_mm):
""" Return the material drill speed (mm/s) based on vaporization heat """
vaporH = { # kJ/mol
# spec heat from room temperature to melting + latent heat of fusion + spec heat from melting to boiling + latent heat of vaporization
# refer https://webbook.nist.gov/chemistry/ for heat capacity, this tool also has some data in specificHeatParams
'Cu': 29.67 + 13.26 + 48.77 + 300,
'Fe': 49.62 + 13.81 + 60.89 + 340,
'W' :119.39 + 52.31 + 89.19 + 774,
'Mo': 89.9 + 37.5 + 71.9 + 598,
'Al': 17.97 + 10.71 + 59.06 + 284,
'C': 29.23 + 715 # Graphite: use 8.12 J/mol/K from webbook (a small heat capacity from Sheindlin 1972 for 263-3650K); sublimation from 3900 K at normal pressure (no melting), https://en.wikipedia.org/wiki/Heats_of_vaporization_of_the_elements_(data_page)
}
if matID not in vaporH.keys():
raise ValueError(f'No vaporization data for {matID}: available in {vaporH.keys()}')
mol_mmD = 2 * np.pi * (FWHM_mm/2.355)**2 / 1000 * defaultDensity(matID) / molarMass(matID)
return power_W / (mol_mmD * vaporH[matID] * 1000)
def drillTime(matID, thickness_mm, W, FWHM_mm):
""" Return the material drill time based on vaporization heat """
return thickness_mm / drillSpeed(matID, W, FWHM_mm)
def getCp(matID, T):
goodID(matID, 'Cp')
if matID in specificHeatParams:
TT = T / 1000
A = specificHeatParams[matID]
return A[0] + A[1] * TT + A[2] * TT**2 + A[3] * TT**3 + A[4] / TT**2
else:
raise Exception(f'No heat capacity data for {matID}')
def getIntCp(matID, T1_K, T2_K):
""" Get integrated heat capacity in J/mol
* T1, T2 in K
"""
goodID(matID, 'Cp')
if matID in specificHeatParams:
A = specificHeatParams[matID]
return intCp2(T1_K, T2_K, A)
else:
raise Exception(f'Wrong material {matID}: Only support materials within specificHeatParams.')
def intCp(T, A):
TT = T / 1000
return 1000 * (A[0] * TT + A[1]/2 * TT**2 + A[2]/3 * TT**3 + A[3]/4 * TT**4 - A[4] / TT)
def intCp2(T1, T2, A):
return intCp(T2, A) - intCp(T1, A)
def pulseT(matID, keV, mJ, rms_mm, density=None, baseT=298.15):
""" Calculate the instant temperature (K) from single pulse
* keV: energies in keV (vectorized)
* mJ: pulse energy in mJ (vectorized)
* rms_mm: beam size radius in mm (vectorized)
-- Size E, mJ, rms_mm must match if more than one are vectorized
* density: in g/cm3, None=default density
* baseT: base temperature (K), 298 K in default
"""
if density is None:
density = defaultDensity(matID)
attL = attenuationLength(matID, keV, density)
EdensityJcm3 = mJ / 1000. / (2. * np.pi * attL*u['cm'] * (rms_mm*0.1)**2)
EdensityJmol = EdensityJcm3 / (density / molarMass(matID))
# build temperature as a fuction of J/cm3
goodID(matID, 'Cp')
if matID in specificHeatParams:
CpParam = specificHeatParams[matID]
if type(CpParam) is tuple:
CpParam = [[baseT, meltPoint[matID], CpParam]]
if baseT < CpParam[0][0]:
CpParam[0][0] = baseT
if baseT > CpParam[-1][1]:
raise Exception('Base temperature cannot be higher than the melting point of {:s} ({:d} K)'.format(matID, int(CpParam[-1][1])))
nzone = len(CpParam)
for i in range(nzone):
if baseT >= CpParam[0][0] and baseT <= CpParam[0][1]:
CpParam[0][0] = baseT
break
else:
del CpParam[0]
dT = 10
T = np.array([])
Jmol = np.array([])
J0 = 0
for i in range(len(CpParam)):
Ti = np.arange(CpParam[i][0], CpParam[i][1], dT)
Ji = intCp2(CpParam[i][0], Ti, CpParam[i][2]) + J0
T = np.concatenate((T, Ti))
Jmol = np.concatenate((Jmol, Ji))
if i < len(CpParam) - 1:
J0 = intCp2(CpParam[i][0], CpParam[i+1][0], CpParam[i][2])
Jmol_base = 0.0
else: # use itegrated specific heat directly
T = specificHeat[matID][0]
Jmol = specificHeat[matID][2]
Jmol_base = interp1d(T, Jmol)(baseT)
T_Jmol = interp1d(Jmol, T, fill_value='extrapolate') # T as function of J/mol
return T_Jmol(EdensityJmol + Jmol_base) - baseT
def pulseTC(matID, keV, mJ, rms_mm, density=None, baseT=25):
""" Calculate the instant temperature (C) from single pulse
* keV: energies in keV (vectorized)
* mJ: pulse energy in mJ (vectorized)
* rms_mm: beam size radius in mm (vectorized)
-- Size of E, mJ, rms_mm must match if more than one are vectorized
* density: in g/cm3, None=default density
* baseT: base temperature (K), 298 K in default
"""
return pulseT(matID, keV, mJ, rms_mm, density=density, baseT=C2K(baseT))
def spectrum_cut(spectrum, eVrange=(0.0, 0.0)):
""" Cut spectrum to a given energy range; return [0,0] if out of range """
if eVrange[1] == 0.0:
return spectrum
else:
if spectrum[-1,0] <= eVrange[0] or spectrum[0,0] >= eVrange[1]:
return np.array([[0, 0]], dtype=np.float)
else:
idx1 = np.argmax(spectrum[:,0] >= eVrange[0])
idx2 = np.argmax(spectrum[:,0] > eVrange[1])
if spectrum[0,0] >= eVrange[0]:
idx1 = 0
if spectrum[-1,0] <= eVrange[1]:
idx2 = -1
return spectrum[idx1:idx2]
def spectrum_eV_power_mW(spectrum, eVrange=(0.0,0.0)):
spec = spectrum_cut(spectrum, eVrange)
eV = spec[:,0]
flux = spec[:,1]
W_bin = [(flux[i]+flux[i+1]) / 2 * (eV[i+1]-eV[i]) * (eV[i+1]+eV[i]) / 2 * c['e']
for i in range(len(eV)-1)]
return np.sum(W_bin) * 1000
def spectrum_eV_flux(spectrum, eVrange=(0.0,0.0)):
spec = spectrum_cut(spectrum, eVrange)
eV = spec[:,0]
flux = spec[:,1]
flux_bin = [(flux[i] + flux[i+1]) / 2 * (eV[i+1] - eV[i]) for i in range(len(eV)-1)]
return np.sum(flux_bin)
def spectrum_flux(spectrum, eVrange=(0.0,0.0), specType='bw'):
if specType == 'eV':
return spectrum_eV_flux(spectrum, eVrange)
else:
spec = np.copy(spectrum)
spec[:,1] = spectrum[:,1] / (spectrum[:,0] * 0.001)
return spectrum_eV_flux(spec, eVrange)
def spectrum_power_mW(spectrum, eVrange=(0.0,0.0), specType='bw'):
if specType == 'eV':
return spectrum_eV_power_mW(spectrum, eVrange)
else:
spec = np.copy(spectrum)
spec[:,1] = spectrum[:,1] / (spectrum[:,0] * 0.001)
return spectrum_eV_power_mW(spec, eVrange)
def spectrum_dose(spectrum, area_cm2, eVrange=(0.0,0.0), specType='bw', particle='photon'):
"""
spectrum: [eV, flux]
area_cm2: area of spot
return dose in mrem/h
"""
spec = spectrum_cut(spectrum, eVrange)
eV = spec[:,0]
if specType == 'bw':
flux_eV = spec[:,1] / (eV * 0.001)
else:
flux_eV = spec[:,1]
# Load flux to dose
path = os.path.dirname(os.path.abspath(__file__))
f2d = np.loadtxt(path+'/f2d_' + particle)
f2d[:,0] *= 1.0E9 # from GeV to eV
f2d[:,1] *= 3.6E-4 # from pSv/s to mrem/h
# Linear interpolation for the log-log of f2d
logf2d = np.log(f2d)
f_logf2d = interp1d(logf2d[:,0], logf2d[:,1],
bounds_error=False, fill_value='extrapolate', assume_sorted=True)
d = np.exp(f_logf2d(np.log(eV))) * flux_eV
dose_bin = [(d[i] + d[i+1]) / 2 * (eV[i+1] - eV[i]) for i in range(len(eV)-1)]
return np.sum(dose_bin) / area_cm2
def spectrum_shield(spectrum, area_cm2, matID, density=None, eVrange=(0.0,0.0), specType='bw',
dose_limit=0.05, dt_limit=0.01, particle='photon', verbose=0):
"""
Retrun required shielidng in mm
spectrum: [eV, flux]
area_cm2: area of spot
matID: shielding material ID
density: density of shielding material, use the default density if not specified
eVrange: cut the spectrum to the given range
specType: type of spectrum, 'eV', flux/eV or 'bw', flux/0.1%bw
dose_limit: shielding goal, 0.05 mrem/h by default
dt_limit: smallest shielding thickness step
particle: type of particle
verbose: output details if > 0
"""
spec = spectrum_cut(spectrum, eVrange)
al = np.array([attenuationLength(matID, eV/1000, density=density) for eV in spec[:,0]]) * 1000
d = spectrum_dose(spec, area_cm2, specType=specType)
if verbose > 0:
print('Dose without shielding is {:.3g} mrem/h'.format(d))
if d < dose_limit:
if verbose > 0:
print('No shielding is needed.')
return 0.
else:
t0 = 0.
t1 = 1.
while True: # find the upper bound of shielding
spec_trans = np.copy(spec)
spec_trans[:,1] *= np.exp(-t1/al)
d = spectrum_dose(spec_trans, area_cm2, specType=specType)
if d >= dose_limit:
t0 = t1
t1 *= 2
else:
break
while t1 - t0 >= dt_limit:
t = (t0 + t1) * 0.5
spec_trans = np.copy(spec)
spec_trans[:,1] *= np.exp(-t/al)
d = spectrum_dose(spec_trans, area_cm2, specType=specType)
if verbose > 0:
print(' Dose after {:.3f} mm {:s} is {:.3f} mrem/h'.format(t, matID, d))
if d > dose_limit:
t0 = t
else:
t1 = t
if verbose > 0:
print('Required {:s} thickness is {:.3f} mm'.format(matID, t1))
return t1
def plot(x, y, xlabel=None, ylabel=None, title=None, figsize=(4.5,3), logx=False, logy=False, xmin=None, xmax=None, ymin=None, ymax=None, savefig=None):
''' Plot function
'''
plt.figure(figsize=figsize, dpi=100, facecolor='white')
if not logx and not logy:
plt.plot(x, y)
if not logx and logy:
plt.semilogy(x, y)
if logx and not logy:
plt.semilogx(x, y)
if logx and logy:
plt.loglog(x, y)
if xmin is not None:
plt.xlim(left=xmin)
else:
plt.xlim(left=x[0])
if xmax is not None:
plt.xlim(right=xmax)
else:
plt.xlim(right=x[-1])
if ymin is not None:
plt.ylim(bottom=ymin)
else:
if not logy:
plt.ylim(bottom=0)
if ymax is not None:
plt.ylim(top=ymax)
if title is not None:
plt.title(title, fontsize=11)
if xlabel is not None:
plt.xlabel(xlabel)
if ylabel is not None:
plt.ylabel(ylabel)
plt.grid(True)
plt.tight_layout()
if savefig is not None:
if savefig[-4:] != '.png':
savefig = savefig + '.png'
plt.savefig(savefig)
plt.show()
def C2K(degC):
''' Convert Celsius to Kelvin '''
return degC + 273.15
def K2C(degK):
''' Convert Kelvin to Celsius '''
return degK - 273.15
def temp3d_uniform(x, y, z, power, q, lx, ly, T_surface_avg,
width, height, thickness, K, T_env=300.0, verbose=0):
''' Calculate the temperature for radiation cooling with uniform input power '''
Lx = width * 0.5
Ly = height * 0.5
h = thickness
h_eff = power / (width * height * (T_surface_avg - T_env))
t = 0.00001
Ktwid = h_eff * t
S = 0.5 * (1 - Ktwid / K)
R = 0.5 * (1 + Ktwid / K)
nx = int(Lx / lx)
if nx < 20:
nx = 20
ny = int(Ly / ly)
if ny < 20:
ny = 20
T = q * lx * ly / (2 * Lx * Ly) * (t / Ktwid + (h - z) / K)
if verbose > 1:
print(f'power = {power}, q = {q}, lx = {lx}, ly = {ly}, T_surface_avg = {T_surface_avg}')
print(f'Lx = {Lx}, Ly = {Ly}, h = {h}')
print(f'h_eff = {h_eff:.3g}, Ktwid = {Ktwid:.3g}')
print(f'S = {S}, R = {R}')
print(f'nx = {nx}, ny = {ny}')
for m in range(1, nx+1):
omega = m * np.pi / Lx
gamma = omega
temp = -2 * q * ly * np.sin(omega * lx) * np.cos(omega * x) * (S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z)))
temp /= omega * gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
for n in range(1, ny+1):
phi = n * np.pi / Ly
gamma = phi
temp = -2 * q * lx * np.sin(phi * ly) * np.cos(phi * y) * (S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z)))
temp /= gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
for m in range(1, nx+1):
for n in range(1, ny+1):
omega = m * np.pi / Lx
phi = n * np.pi / Ly
gamma = np.sqrt(omega * omega + phi * phi)
temp = -4 * q * np.sin(omega * lx) * np.sin(phi * ly) * np.cos(omega * x) * np.cos(phi * y)
temp *= S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z))
temp /= omega * gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
return T + T_env
def temp3d_1dGaussian(x, y, z, power, q, lx, sigma_y, T_surface_avg,
width, height, thickness, K, T_env=300.0, verbose=0):
''' Calculate the temperature for radiation cooling with 1D Gaussian input power '''
r2pi = np.sqrt(2 * np.pi)
Lx = width * 0.5
Ly = height * 0.5
h = thickness
h_eff = power / (width * height * (T_surface_avg - T_env))
t = 0.00001
Ktwid = h_eff * t
S = 0.5 * (1 - Ktwid / K)
R = 0.5 * (1 + Ktwid / K)
nx = int(Lx / lx)
if nx < 20:
nx = 20
ny = int(Ly / sigma_y)
if ny < 20:
ny = 20
T = r2pi * sigma_y * q * lx / (2 * Lx * Ly) * (t / Ktwid + (h - z) / K)
if verbose > 1:
print(f'power = {power}, q = {q}, lx = {lx}, sigma_y = {sigma_y}, T_surface_avg = {T_surface_avg}')
print(f'Lx = {Lx}, Ly = {Ly}, h = {h}')
print(f'h_eff = {h_eff:.3g}, Ktwid = {Ktwid:.3g}')
print(f'S = {S}, R = {R}')
print(f'nx = {nx}, ny = {ny}')
for m in range(1, nx+1):
omega = m * np.pi / Lx
gamma = omega
temp = -r2pi * sigma_y * q * np.sin(omega * lx) * np.cos(omega * x) * (S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z)))
temp /= omega * gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
for n in range(1, ny+1):
phi = n * np.pi / Ly
gamma = phi
temp = -r2pi * sigma_y * q * lx * np.exp(-0.5 * (phi * sigma_y)**2) * np.cos(phi * y) * (S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z)))
temp /= gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
for m in range(1, nx+1):
for n in range(1, ny+1):
omega = m * np.pi / Lx
phi = n * np.pi / Ly
gamma = np.sqrt(omega * omega + phi * phi)
temp = -2 * r2pi * sigma_y * q * np.sin(omega * lx) * np.exp(-0.5 * (phi * sigma_y)**2) * np.cos(omega * x) * np.cos(phi * y)
temp *= S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z))
temp /= omega * gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
return T + T_env
def temp3d_2dGaussian(x, y, z, power, q, sigma_x, sigma_y, T_surface_avg,
width, height, thickness, K, T_env=300.0, verbose=0):
''' Calculate the temperature for radiation cooling with 2D Gaussian input power '''
Lx = width * 0.5
Ly = height * 0.5
h = thickness
h_eff = power / (width * height * (T_surface_avg - T_env))
t = 0.00001
Ktwid = h_eff * t
S = 0.5 * (1 - Ktwid / K)
R = 0.5 * (1 + Ktwid / K)
nx = int(Lx / sigma_x)
if nx < 20:
nx = 20
ny = int(Ly / sigma_y)
if ny < 20:
ny = 20
piqxy = np.pi * q * sigma_x * sigma_y
T = piqxy / (2 * Lx * Ly) * (t / Ktwid + (h - z) / K)
if verbose > 1:
print(f'power = {power}, q = {q}, lx = {sigma_x}, sigma_y = {sigma_y}, T_surface_avg = {T_surface_avg}')
print(f'Lx = {Lx}, Ly = {Ly}, h = {h}')
print(f'h_eff = {h_eff:.3g}, Ktwid = {Ktwid:.3g}')
print(f'S = {S}, R = {R}')
print(f'nx = {nx}, ny = {ny}')
for m in range(1, nx+1):
omega = m * np.pi / Lx
gamma = omega
temp = -piqxy * np.exp(-0.5 * (omega * sigma_x)**2) * np.cos(omega * x) * (S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z)))
temp /= gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
for n in range(1, ny+1):
phi = n * np.pi / Ly
gamma = phi
temp = -piqxy * np.exp(-0.5 * (phi * sigma_y)**2) * np.cos(phi * y) * (S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z)))
temp /= gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
for m in range(1, nx+1):
for n in range(1, ny+1):
omega = m * np.pi / Lx
phi = n * np.pi / Ly
gamma = np.sqrt(omega * omega + phi * phi)
temp = -piqxy * np.exp(-0.5 * ((omega * sigma_x)**2 + (phi * sigma_y)**2)) * np.cos(omega * x) * np.cos(phi * y)
temp *= S * np.sinh(gamma * (z + t - h)) + R * np.sinh(gamma * (h + t - z))
temp /= gamma * K * Lx * Ly * (S * np.cosh(gamma * (t-h)) - R * np.cosh(gamma * (t + h)))
T += temp
return T + T_env
def radiation_cooling(power:float, beam_mode:int, q:float, lx:float, ly:float,
target_width:float, target_height:float, target_thickness:float,
target_K:float, target_emissivity:float,
env_emissivity:float, T_env=300.0, back_rad_only=False, verbose=0):
''' Calculate the temperature from radiation cooling (Not Vectorized)
Input:
power: beam power in Watts
beam_mode: 0 - uniform beam; 1 - 1D Gaussian on Y; 2 - 2D Gaussian
q: power density in W/mm2
lx: half beam size on X, mm (rms for Gaussian beam)
ly: half beam size on Y, mm (rms for Gaussian beam)
target_width: target width in mm
target_height: target height in mm
target_thickness: target thickness in mm
target_K: target thermal conductivity in W/mm/K
target_emissivity: target emissivity
env_emissivity: environment emissivity
T_env: environment temperature in K
back_rad_only: whether radiation is on the back side only
verbose: verbose level for output
Return:
Tmax: the maximum temperature on target (K)
T_surface_avg, T000, Tmin, T_env: facilitate temperatures (K)
ratio: if it is >>1, need to set back_rad_only=True
'''
# Step 1: estimate an average surface temperature using radiation cooling of the entire mask surface and calculate h_eff using this ave temperature with radiation cooling of mask back surface only
if back_rad_only:
area = target_width * target_height
else:
area = 2 * (target_width * target_height + target_width * target_thickness + target_height * target_thickness)
emissivity_eff = target_emissivity * env_emissivity / (target_emissivity + env_emissivity - target_emissivity * env_emissivity)
sigma = 5.67e-14 # Stefan-Boltzmann constant in W/mm2/K4
T_surface_avg = (power / (sigma * area * emissivity_eff) + T_env**4) **0.25
# Step 2: calculate the temperature distribution in the mask hot wall (front layer) using h_eff and the analytic two layer model of M302
if beam_mode == 0:
T000 = temp3d_uniform(0, 0, 0, power, q, lx, ly, T_surface_avg,
target_width, target_height, target_thickness, target_K, T_env=T_env, verbose=verbose)
Tmin = temp3d_uniform(target_width/2, target_height/2, target_thickness, power, q, lx, ly, T_surface_avg,
target_width, target_height, target_thickness, target_K, T_env=T_env, verbose=verbose)
elif beam_mode == 1:
T000 = temp3d_1dGaussian(0, 0, 0, power, q, lx, ly, T_surface_avg,
target_width, target_height, target_thickness, target_K, T_env=T_env, verbose=verbose)
Tmin = temp3d_1dGaussian(target_width/2, target_height/2, target_thickness, power, q, lx, ly, T_surface_avg,
target_width, target_height, target_thickness, target_K, T_env=T_env, verbose=verbose)
elif beam_mode == 2:
T000 = temp3d_2dGaussian(0, 0, 0, power, q, lx, ly, T_surface_avg,
target_width, target_height, target_thickness, target_K, T_env=T_env, verbose=verbose)
Tmin = temp3d_2dGaussian(target_width/2, target_height/2, target_thickness, power, q, lx, ly, T_surface_avg,
target_width, target_height, target_thickness, target_K, T_env=T_env, verbose=verbose)
else:
raise Exception(f'Wrong beam mode [{beam_mode}]: must be 0, 1 or 2')
Tmax = T_surface_avg + T000 - Tmin
# Check if it is conservative
# dT1 = T000 - Tmin
# ratio1 = 2 * ((Tmax - dT1)**4 - T_env**4) / ((target_melt - dT1)**4 - T_env**4)
ratio = (T_surface_avg - T_env) / (Tmax - Tmin)
if verbose > 0:
print(f'Tmax = {K2C(Tmax):.1f}, T000 = {K2C(T000):.1f}, Tmin = {Tmin:.1f} deg-C')
return (Tmax, T_surface_avg, T000, Tmin, T_env, ratio)
def dSpace(ID,hkl):
""" Computes the d spacing (m) of the specified material and reflection
ID is chemical fomula : 'Si'
hkl is the reflection : (1,1,1)
"""
ID = goodID(ID, item='crystal')
h=hkl[0]
k=hkl[1]
l=hkl[2] # noqa: E741
lp=latticeParameters[ID]
a=lp[0]/u['ang']
b=lp[1]/u['ang']
c=lp[2]/u['ang']
alpha=lp[3]
beta=lp[4]
gamma=lp[5]
ca=cosd(alpha)
cb=cosd(beta)
cg=cosd(gamma)
sa=sind(alpha)
sb=sind(beta)
sg=sind(gamma)
invdsqr=1/(1+2*ca*cb*cg-ca**2-cb**2-cg**2)*(h**2*sa**2/a**2 + k**2*sb**2/b**2 + l**2*sg**2/c**2 +
2*h*k*(ca*cb-cg)/a/b+2*k*l*(cb*cg-ca)/b/c+2*h*l*(ca*cg-cb)/a/c)
d=invdsqr**-0.5
return d
def BraggAngle(ID,hkl,E=None):
""" Computes the Bragg angle (deg) of the specified material, reflection and photon energy
ID is chemical fomula : 'Si'
hkl is the reflection : (1,1,1)
E is photon energy in eV or keV (default is LCLS value)
"""
E = eV(E)
d = dSpace(ID,hkl)
theta = asind(lam(E)/2/d)
return theta
def BraggEnergy(ID,hkl,twotheta):
""" Computes the photon energy that satisfies the Bragg condition of the specified material, reflection and twotheta angle
ID is chemical fomula : 'Si'
hkl is the reflection : (1,1,1)
twotheta is the scattering angle in degrees
"""
ID=goodID(ID)
d=dSpace(ID,hkl)
l=2*d*sind(twotheta/2.0) # noqa: E741
E=lam2E(l)
return E
def StructureFactor(ID,f,hkl,z=None):
""" Computes the structure factor
ID is chemical fomula : 'Si'
f is the atomic form factor
hkl is the reflection : (1,1,1)
z is the rhombohedral lattice parameter
"""
ID=goodID(ID, item='crystal')
i=complex(0,1)
h=hkl[0]
k=hkl[1]
l=hkl[2] # noqa: E741
L=latticeType[ID]
if L=='fcc':
F=f*(1+np.exp(-i*np.pi*(k+l))+np.exp(-i*np.pi*(h+l))+np.exp(-i*np.pi*(h+k)))
elif L=='bcc':
F=f*(1+np.exp(-i*np.pi*(h+k+l)))
elif L=='cubic':
F=f
elif L=='diamond':
F=f*(1+np.exp(-i*np.pi*(k+l))+np.exp(-i*np.pi*(h+l))+np.exp(-i*np.pi*(h+k)))*(1+np.exp(-i*2*np.pi*(h/4.0+k/4.0+l/4.0)))
# elif L=='rhomb':
# z=latticeParamRhomb[ID]
# F=f*(1+np.exp(2*i*np.pi*(h+k+l)*z))
elif L=='tetr':
F=f
elif L=='hcp':
F=f*(1+np.exp(2*i*np.pi*(h/3.0+2*k/3.0+l/2.0)))
else:
raise Exception(f'Unrecognized L: {L}')
return F
def StructureFactorE(ID,hkl,E=None,z=None):
ID=goodID(ID, item='crystal')
# E = getE(E)
theta=BraggAngle(ID,hkl,E)
f=FF(ID,2*theta,E)
return StructureFactor(ID,f,hkl,z)
def UnitCellVolume(ID):
""" Returns the unit cell volume in m^3
ID is chemical fomula : 'Si'
"""
ID=goodID(ID)
lp=latticeParameters[ID]
a=lp[0]/u['ang']
b=lp[1]/u['ang']
c=lp[2]/u['ang']
alpha=lp[3]
beta=lp[4]
gamma=lp[5]
# L=latticeType[ID]
ca=cosd(alpha)
cb=cosd(beta)
cg=cosd(gamma)
V=a*b*c*np.sqrt(1-ca**2-cb**2-cg**2+2*ca*cb*cg)
return V
# def DebyeWallerFactor(ID,hkl,T=293,E=None):
# """ Computes the Debye Waller factor for a specified reflection
# ID is chemical fomula : 'Si'
# T is the crystal temperature in Kelvin (default is 293)
# E is photon energy in eV or keV (default is LCLS value)
# """
# ID=goodID(ID)
# # E = getE(E)
# theta=BraggAngle(ID,hkl,E)
# l=lam(E)*u['ang']