-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrwl_bl.py
2809 lines (2410 loc) · 153 KB
/
srwl_bl.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
# -*- coding: utf-8 -*-
#############################################################################
# SRWLib SR Beamline Base Class
# Contains a set of member objects and functions for simulating basic operation and characteristics
# of a complete user beamline in a synchrotron radiation source.
# Under development!!!
# Authors/Contributors: O.C., Maksim Rakitin
# v 0.05
#############################################################################
from __future__ import print_function #Python 2.7 compatibility
from srwlib import *
from srwl_uti_mag import *
from srwl_uti_und import *
from uti_plot import *
import uti_math
#import optparse #MR081032016 #Consider placing import argparse here
import time
#****************************************************************************
class SRWLBeamline(object):
"""Basic Synchrotron Radiation Beamline (in a storage ring based source)
Several different types of simulations are planned to be supported, including:
- single-electron UR intensity spectrum;
- UR spectrum through a slit (finite aperture), taking into account e-beam emittance and energy spread;
- single-electron (fully-coherent) and multi-electron (partially-coherent) wavefront propagation calculations;
- simulation of (coherent scattering type) experiments for different types of samples and beamline settings;
- misc. auxiliary calculations/estimations facilitating beamline operation (e.g. estimation of undulator gap and crystal monochromator angle for a required photon energy, etc.)
"""
#------------------------------------------------------------------------
def __init__(self, _name='', _e_beam=None, _mag_approx=None, _mag=None, _gsn_beam=None, _op=None): #, _det=None):
"""
:param _name: beamline name string
:param _e_beam: electron beam (SRWLPartBeam instance)
:param _mag_approx: approximate magnetic field container (SRWLMagFldC instance)
:param _mag: accurate magnetic field container (SRWLMagFldC instance)
:param _gsn_beam: coherent Gaussian beam (SRWLGsnBm instance)
:param _op: optics sequence (SRWLOptC instance)
:param _det: detector (SRWLDet instance)
"""
if _e_beam != None:
if(isinstance(_e_beam, SRWLPartBeam) == False):
raise Exception("Incorrect Electron Beam structure")
if _mag_approx != None:
if(isinstance(_mag_approx, SRWLMagFldC) == False):
raise Exception("Incorrect Magnetic Field Container structure")
if _mag != None:
if(isinstance(_mag, SRWLMagFldC) == False):
raise Exception("Incorrect Magnetic Field Container structure")
if _gsn_beam != None:
if(isinstance(_gsn_beam, SRWLGsnBm) == False):
raise Exception("Incorrect Gaussian Beam structure")
if _op != None:
if(isinstance(_op, SRWLOptC) == False):
raise Exception("Incorrect Optical Container structure")
#if _det != None:
# if(isinstance(_det, SRWLDet) == False):
# raise Exception("Incorrect Detector structure")
self.name = _name
self.eBeam = SRWLPartBeam() if _e_beam is None else _e_beam
self.mag_approx = _mag_approx
self.mag = _mag
self.gsnBeam = _gsn_beam
self.optics = _op
#self.detector = _det
#------------------------------------------------------------------------
## def set_e_beam(self, _e_beam_name='', _e_beam=None, _i=-1, _sig_e=-1, _emit_x=-1, _emit_y=-1, _drift=0, _x=0, _y=0, _xp=0, _yp=0, _dE=0):
## """Setup Electron Beam.
## NOTE: The beam is assumed to be first set up at z = 0 longitudinal position, and then it is propagated according to _drift (if _drift != 0.)
## :param _e_beam_name: e-beam unique name, e.g. 'NSLS-II Low Beta Day 1' (see srwl_uti_src.py)
## :param _e_beam: e-beam structure (SRWLPartBeam instance)
## :param _i: e-beam current [A]
## :param _sig_e: e-beam relative energy spread
## :param _emit_x: e-beam horizontal emittance
## :param _emit_y: e-beam vertical emittance
## :param _drift: e-beam drift length in [m] from center of straight section
## :param _x: initial average horizontal position [m]
## :param _y: initial average vertical position [m]
## :param _xp: initial average horizontal angle [m]
## :param _yp: initial average vertical angle [m]
## :param _dE0: average energy deviation [GeV]
## """
## #add more parameters when/if necessary
##
## if(_sig_e < 0.): _sig_e = None
## if(_emit_x < 0.): _emit_x = None
## if(_emit_y < 0.): _emit_y = None
##
## sIncInpElecBeam = 'Incorrect input for setting up Electron Beam structure'
## if(len(_e_beam_name) > 0):
## self.eBeam = srwl_uti_src_e_beam(_e_beam_name, _sig_e=_sig_e, _emit_x=_emit_x, _emit_y=_emit_y)
## if(self.eBeam == None):
## if((_e_beam == None) or (isinstance(_e_beam, SRWLPartBeam) == False)):
## raise Exception(sIncInpElecBeam)
## else: self.eBeam = _e_beam
## else:
## if((_e_beam == None) or (isinstance(_e_beam, SRWLPartBeam) == False)):
## raise Exception(sIncInpElecBeam)
## else: self.eBeam = _e_beam
##
## #OC: Add Twiss parameters and 2nd order moments to function arguments and program logic of switching bw these definitions
## #OC: consider treating _sig_e=-1, _emit_x=-1, _emit_y=-1 is defined, in all cases!
##
## if(_i > 0): self.eBeam.Iavg = _i
## if(_drift != 0): self.eBeam.drift(_drift)
## self.eBeam.partStatMom1.x = _x
## self.eBeam.partStatMom1.y = _y
## self.eBeam.partStatMom1.xp = _xp
## self.eBeam.partStatMom1.yp = _yp
##
## if(_dE != 0):
## elRestMassGeV = 0.51099890221e-03
## curE0 = self.eBeam.partStatMom1.gamma*self.eBeam.partStatMom1.relE0*elRestMassGeV
## self.eBeam.partStatMom1.gamma = (curE0 + _dE)/(self.eBeam.partStatMom1.relE0*elRestMassGeV)
#------------------------------------------------------------------------
def set_e_beam(self, _e_beam_name='', _e_beam=None, _i=-1, _ens=-1, _emx=-1, _emy=-1, _dr=0, _x=0, _y=0, _xp=0, _yp=0, _e=None, _de=0,
_betax=None, _alphax=None, _etax=None, _etaxp=None, _betay=None, _alphay=None, _etay=0, _etayp=0,
_sigx=None, _sigxp=None, _mxxp=None, _sigy=None, _sigyp=None, _myyp=None):
"""Setup Electron Beam
:param _e_beam_name: e-beam unique name, e.g. 'NSLS-II Low Beta Day 1' (see srwl_uti_src.py)
:param _e_beam: e-beam structure (SRWLPartBeam instance)
:param _i: e-beam current [A]
:param _ens: e-beam relative energy spread
:param _emx: e-beam horizontal emittance
:param _emy: e-beam vertical emittance
:param _dr: e-beam drift length in [m] from center of straight section
:param _x: initial average horizontal position [m]
:param _y: initial average vertical position [m]
:param _xp: initial average horizontal angle [m]
:param _yp: initial average vertical angle [m]
:param _e: energy [GeV]
:param _de: average energy deviation [GeV]
#MR28092016 - added parameters to define the beam explicitly:
# Parameters for SRWLPartBeam.from_Twiss():
# def from_Twiss(self, _Iavg=0, _e=0, _sig_e=0, _emit_x=0, _beta_x=0, _alpha_x=0, _eta_x=0, _eta_x_pr=0, _emit_y=0, _beta_y=0, _alpha_y=0, _eta_y=0, _eta_y_pr=0):
:param _betax: horizontal beta-function [m]
:param _alphax: horizontal alpha-function [rad]
:param _etax: horizontal dispersion function [m]
:param _etaxp: horizontal dispersion function derivative [rad]
:param _betay: vertical beta-function [m]
:param _alphay: vertical alpha-function [rad]
:param _etay: vertical dispersion function [m]
:param _etayp: vertical dispersion function derivative [rad]
# Parameters for SRWLPartBeam.from_RMS():
# def from_RMS(self, _Iavg=0, _e=0, _sig_e=0, _sig_x=0, _sig_x_pr=0, _m_xx_pr=0, _sig_y=0, _sig_y_pr=0, _m_yy_pr=0):
:param _sigx: horizontal RMS size [m]
:param _sigxp: horizontal RMS divergence [rad]
:param _mxxp: <(x-<x>)(x'-<x'>)> [m]
:param _sigy: vertical RMS size [m]
:param _sigyp: vertical RMS divergence [rad]
:param _myyp: <(y-<y>)(y'-<y'>)> [m]
"""
#add more parameters when/if necessary
#print('In set_e_beam: x=', _x, ' xp=', _xp)
varParamStd = srwl_uti_std_options()
help_dict = {}
for v in varParamStd:
help_dict[v[0]] = '{}{}'.format(v[3][0].upper(), v[3][1:])
def check_positive(d):
for k, v in d.items():
if v is None or v < 0:
return False, k
return True, None
if(_ens < 0.): _ens = None
if(_emx < 0.): _emx = None
if(_emy < 0.): _emy = None
sIncInpElecBeam = 'Incorrect input for setting up Electron Beam structure'
eBeamWasSetFromDB = False #OC28092016
if len(_e_beam_name) > 0:
self.eBeam = srwl_uti_src_e_beam(_e_beam_name, _sig_e=_ens, _emit_x=_emx, _emit_y=_emy)
eBeamWasSetFromDB = True
if self.eBeam is None:
if (_e_beam is None) or (isinstance(_e_beam, SRWLPartBeam) is False):
# raise ValueError(sIncInpElecBeam)
raise ValueError('The beam name "{}" was not found in the database and _e_beam is empty'.format(_e_beam_name))
else:
self.eBeam = _e_beam
eBeamWasSetFromInObj = False
if((eBeamWasSetFromDB is False) and (isinstance(_e_beam, SRWLPartBeam) is True)):
self.eBeam = _e_beam
eBeamWasSetFromInObj = True
if((eBeamWasSetFromDB is False) and (eBeamWasSetFromInObj is False)): #Try to set up e-beam from input Twiss params or Moments
#beam_inputs = {'_i': _i, '_e': _e, '_ens': _ens}
#beam_check, beam_bad_var = check_positive(beam_inputs)
#if beam_check:
##OC15092017 removed the above check because for partially-coherent calculations with Gaussian beam _i, _e, _ens can be 0 or undefined
twiss_inputs = {'_emx': _emx, '_betax': _betax, '_etax': _etax,
'_emy': _emy, '_betay': _betay, '_etay': _etay}
moments_inputs = {'_sigx': _sigx, '_sigxp': _sigxp,
'_sigy': _sigy, '_sigyp': _sigyp}
twiss_check, twiss_bad_var = check_positive(twiss_inputs)
if((_alphax is None) or (_alphay is None)): twiss_check = False #OC28092016
if((_etaxp is None) or (_etayp is None)): twiss_check = False
moments_check, moments_bad_var = check_positive(moments_inputs)
if((_mxxp is None) or (_myyp is None)): moments_check = False #OC28092016
if twiss_check:
# Defined by Twiss parameters:
self.eBeam.from_Twiss(
_Iavg=_i, _e=_e, _sig_e=_ens,
_emit_x=_emx, _beta_x=_betax, _alpha_x=_alphax, _eta_x=_etax, _eta_x_pr=_etaxp,
_emit_y=_emy, _beta_y=_betay, _alpha_y=_alphay, _eta_y=_etay, _eta_y_pr=_etayp,
)
elif moments_check:
# Defined by Moments:
self.eBeam.from_RMS(
_Iavg=_i, _e=_e, _sig_e=_ens,
_sig_x=_sigx, _sig_x_pr=_sigxp, _m_xx_pr=_mxxp,
_sig_y=_sigy, _sig_y_pr=_sigyp, _m_yy_pr=_myyp,
)
else:
# raise ValueError(sIncInpElecBeam)
err_msg = 'Twiss and/or Moments parameters are not set correctly:\n - {} ({}): {}\n - {} ({}): {}\n'
raise ValueError(err_msg.format(
help_dict['ebm{}'.format(twiss_bad_var)], twiss_bad_var, twiss_inputs[twiss_bad_var],
help_dict['ebm{}'.format(moments_bad_var)], moments_bad_var, moments_inputs[moments_bad_var],
))
#else:
# err_msg = 'Beam parameters are not set correctly:\n - {} ({}): {}\n'
# raise ValueError(err_msg.format(
# help_dict['ebm{}'.format(beam_bad_var)], beam_bad_var, beam_inputs[beam_bad_var],
# ))
else: #Allow overriding some 2nd order moments if eBeamWasSetFromDB or eBeamWasSetFromInObj
if((_ens is not None) and (_ens > 0)): self.eBeam.arStatMom2[10] = _ens*_ens
if((_sigx is not None) and (_sigx > 0)): self.eBeam.arStatMom2[0] = _sigx*_sigx
if((_sigxp is not None) and (_sigxp > 0)): self.eBeam.arStatMom2[2] = _sigxp*_sigxp
if((_mxxp is not None) and (_mxxp != 1.e+23)): self.eBeam.arStatMom2[1] = _mxxp
if((_sigy is not None) and (_sigy > 0)): self.eBeam.arStatMom2[3] = _sigy*_sigy
if((_sigyp is not None) and (_sigyp > 0)): self.eBeam.arStatMom2[5] = _sigyp*_sigyp
if((_myyp is not None) and (_myyp != 1.e+23)): self.eBeam.arStatMom2[4] = _myyp
#Allow applying drift and overriding 1st order moments in any case
#if((_dr is not None) and (_dr != 0)): self.eBeam.drift(_dr) #OC16032017: moved to after the following lines
if((_i is not None) and (_i > 0)): self.eBeam.Iavg = _i
if(_x is not None): self.eBeam.partStatMom1.x = _x
if(_y is not None): self.eBeam.partStatMom1.y = _y
if(_xp is not None): self.eBeam.partStatMom1.xp = _xp
if(_yp is not None): self.eBeam.partStatMom1.yp = _yp
if((_dr is not None) and (_dr != 0)): self.eBeam.drift(_dr) #OC16032017 (see above)
if((_de is not None) and (_de != 0)):
elRestMassGeV = 0.51099890221e-03
curE0 = self.eBeam.partStatMom1.gamma*self.eBeam.partStatMom1.relE0*elRestMassGeV
self.eBeam.partStatMom1.gamma = (curE0 + _de)/(self.eBeam.partStatMom1.relE0*elRestMassGeV)
#------------------------------------------------------------------------
def set_und_sin(self, _per=0.02, _len=1, _bx=0, _by=0, _phx=0, _phy=0, _sx=1, _sy=1, _zc=0, _add=0):
"""Setup magnetic field container with basic undulator having sinusoidal magnetic field
:param _per: period length [m]
:param _len: undulator length [m]
:param _bx: horizontal magnetic field amplitude [m]
:param _by: vertical magnetic field amplitude [m]
:param _phx: initial phase of the horizontal magnetic field [rad]
:param _phx: initial phase of the vertical magnetic field [rad]
:param _sx: symmetry of the horizontal magnetic field vs longitudinal position 1 - symmetric (B ~ cos(2*Pi*n*z/per + ph)) , -1 - anti-symmetric (B ~ sin(2*Pi*n*z/per + ph))
:param _sy: symmetry of the vertical magnetic field vs longitudinal position
:param _zc: longitudinal position of the undulator center
:param _reset: add (=1) or reset (=0) the new undulator structure to the existing approximate magnetic field container
"""
if(_add == 0):
if(self.mag_approx != None):
del self.mag_approx
if(self.mag_approx == None): self.mag_approx = SRWLMagFldC()
und = SRWLMagFldU()
und.set_sin(_per, _len, _bx, _by, _phx, _phy, _sx, _sy)
self.mag_approx.arMagFld.append(und)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
#print(self.mag_approx.arVx)
return self.mag_approx
#------------------------------------------------------------------------
def set_mag_multipole(self, _bx=0, _by=1., _gn=0, _gs=0, _len=1.5, _led=0, _r=0, _zc=0, _add=0):
"""Setup magnetic field container with basic dipole / quadrupole magnet
:param _bx: horizontal magnetic field [m]
:param _by: vertical magnetic field [m]
:param _gn: magnetic field gradient of normal quad [m]
:param _gs: magnetic field gradient of skew quad [m]
:param _len: magnet length [m]
:param _led: "soft" edge length for field variation from 10% to 90% [m]; G/(1 + ((z-zc)/d)^2)^2 fringe field dependence is assumed [m]
:param _zc: longitudinal position of the magnet center
:param _add: add (=1) or reset (=0) the new magnet structure to the existing approximate magnetic field container
"""
if(_add == 0):
if(self.mag_approx != None):
del self.mag_approx
if(self.mag_approx == None): self.mag_approx = SRWLMagFldC()
if(_bx != 0):
dipBx = SRWLMagFldM(_G=_bx, _m=1, _n_or_s='s', _Leff=_len, _Ledge=_led, _R=_r) #?
self.mag_approx.arMagFld.append(dipBx)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
if(_by != 0):
dipBy = SRWLMagFldM(_G=_by, _m=1, _n_or_s='n', _Leff=_len, _Ledge=_led, _R=_r)
self.mag_approx.arMagFld.append(dipBy)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
if(_gn != 0):
quadN = SRWLMagFldM(_G=_gn, _m=2, _n_or_s='n', _Leff=_len, _Ledge=_led, _R=_r)
self.mag_approx.arMagFld.append(quadN)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
if(_gs != 0):
quadS = SRWLMagFldM(_G=_gs, _m=2, _n_or_s='s', _Leff=_len, _Ledge=_led, _R=_r)
self.mag_approx.arMagFld.append(quadS)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
#print('At the end of set_mag_multipole, mag_approx:', self.mag_approx)
return self.mag_approx
#------------------------------------------------------------------------
def set_mag_kick(self, _angx=1., _angy=0, _len=1., _led=0, _zc=0, _add=0):
"""Setup magnetic field container with basic dipole "kick" magnet
:param _angx: horizontal kick angle [rad]
:param _angy: vertical kick angle [rad]
:param _len: magnet length [m]
:param _led: "soft" edge length for field variation from 10% to 90% [m]; G/(1 + ((z-zc)/d)^2)^2 fringe field dependence is assumed [m]
:param _zc: longitudinal position of the magnet center
:param _add: add (=1) or reset (=0) the new magnet structure to the existing approximate magnetic field container
"""
if(self.eBeam == None): raise Exception('Electron Beam structure is not defined (it is required for defining kick magnet parameters from angle)')
elEn_GeV = self.eBeam.partStatMom1.get_E(_unit='GeV')
if(_add == 0):
if(self.mag_approx != None): del self.mag_approx
if(_angx != 0.):
kickMag = srwl_mag_kick(_el_en=elEn_GeV, _ang=_angx, _x_or_y='x', _len=_len, _led=_led)
self.mag_approx.arMagFld.append(kickMag)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
if(_angy != 0.):
kickMag = srwl_mag_kick(_el_en=elEn_GeV, _ang=_angy, _x_or_y='y', _len=_len, _led=_led)
self.mag_approx.arMagFld.append(kickMag)
self.mag_approx.arXc.append(0)
self.mag_approx.arYc.append(0)
self.mag_approx.arZc.append(_zc)
return self.mag_approx
#------------------------------------------------------------------------
def set_und_tab(self, _gap, _ph_mode='p1', _phase=0., _zc=0., _interp_ord=1, _meas_or_calc='m', _per=0.02, _c1=0, _c2=0, _a=0, _dg_by_len=0, _y0=0, _yp=0):
"""Setup magnetic field container with magnetic measurements or calculation data interpolated for given gap and phase
:param _gap: magnetic gap [mm] for which the field should be set up
:param _ph_mode: type of phase (shift of magnet arrays) motion
:param _phase: shift of magnet arrays [mm] for which the field should be set up
:param _zc: center position [m]
:param _interp_ord: order of interpolation: 1- (bi-)linear, 2- (bi-)quadratic, 3- (bi-)cubic
:param _meas_or_calc: use magnetic measurements ('m') or calculation ('c') data
:param _per: undulator period [m]
:param _c1: constant defining (approximate) undulator field dependence on gap (i.e. c1 in b0*exp(-c1*gap/per + c2*(gap/per)^2))
:param _c2: constant defining (approximate) undulator field dependence on gap (i.e. c2 in b0*exp(-c1*gap/per + c2*(gap/per)^2))
:param _a: constant defining (approximate) undulator field dependence on vertical position (i.e. a in cosh(2*Pi*a*y/per)
:param _dg_by_len: gap taper (exit minus entrance) divided by undulator length
:param _y0: vertical electron position in the center of undulator relative to undulator median plane [m]
:param _dydz: vertical electron angle in the center of undulator relative to undulator median plane [rad]
"""
fPathSum = ''
if(_meas_or_calc == 'm'):
if(hasattr(self, 'dir_magn_meas') and hasattr(self, 'fn_magn_meas_sum')):
fPathSum = os.path.join(os.getcwd(), self.dir_main, self.dir_magn_meas, self.fn_magn_meas_sum)
else: raise Exception('No magnetic measurements data are supplied')
elif(_meas_or_calc == 'c'):
raise Exception('No magnetic calculation data are supplied')
f = open(fPathSum, 'r')
lines = f.readlines() #read-in all lines
nRows = len(lines)
strSep = '\t'
arGaps = []; arPhases = []; arMagFld3D = []
arXc = []; arYc = []; arZc = []
arCoefBx = []; arCoefBy = []
phaseIsVar = False
phasePrev = None
#print('Setting up tabulated magnetic field')
#print('Starting to read-in', nRows, 'files')
for i in range(nRows):
curLine = lines[i]
curLineParts = curLine.split(strSep)
curLenLineParts = len(curLineParts)
if(curLenLineParts >= 4):
curPhaseMode = curLineParts[1]
if(curPhaseMode != _ph_mode): continue
arGaps.append(float(curLineParts[0]))
curPhase = float(curLineParts[2])
if((phasePrev != None) and (curPhase != phasePrev)): phaseIsVar = True
arPhases.append(curPhase)
phasePrev = curPhase
#curFileName = curLineParts[3]
curFileName = curLineParts[3].strip() #MR13012017
#print(curFileName)
if(len(curFileName) > 0):
curFilePath = os.path.join(os.getcwd(), self.dir_main, self.dir_magn_meas, curFileName)
curFldCnt = srwl_uti_read_mag_fld_3d(curFilePath, '#')
arMagFld3D.append(curFldCnt.arMagFld[0])
arXc.append(curFldCnt.arXc[0])
arYc.append(curFldCnt.arYc[0])
arZc.append(curFldCnt.arZc[0] + _zc)
if(curLenLineParts >= 6):
arCoefBx.append(float(curLineParts[4]))
arCoefBy.append(float(curLineParts[5]))
f.close()
#print('Done reading-in magnetic field files')
fldCnt = SRWLMagFldC(arMagFld3D, array('d', arXc), array('d', arYc), array('d', arZc))
nElem = len(arMagFld3D)
if((nElem != len(arGaps)) or (nElem != len(arPhases))):
raise Exception('Inconsistent magnetic field data summary file')
fldCnt.arPar1 = array('d', arGaps)
fldCnt.arPar2 = array('d', arPhases)
if(len(arCoefBx) == nElem): fldCnt.arPar3 = array('d', arCoefBx)
if(len(arCoefBy) == nElem): fldCnt.arPar4 = array('d', arCoefBy)
#print(' Gaps:', fldCnt.arPar1)
#print(' Phase Mode:', _ph_mode)
#print(' Phases:', fldCnt.arPar2)
#if(phaseIsVar is True): print(' Phase is variable')
#else: print(' Phase is constant')
fldCntRes = SRWLMagFldC(arMagFld3D[0], arXc[0], arYc[0], arZc[0])
numDims = 1
if(phaseIsVar): numDims += 1
precPar = [numDims, _gap, _phase, _interp_ord]
#precPar = [1, _gap, _phase, _interp_ord]
self.mag = srwl.CalcMagnField(fldCntRes, fldCnt, precPar)
if((_dg_by_len != 0.) or (_y0 != 0.) or (_yp != 0.)):
self.mag.arMagFld[0] = srwl_und_fld_1d_mis(self.mag.arMagFld[0], _per, _dg_by_len, _c1, _c2, 0.001*_gap, _a, _y0, _yp)
return self.mag
#------------------------------------------------------------------------
def set_und_tab_faster(self, _gap, _ph_mode='p1', _phase=0., _zc=0., _interp_ord=1, _meas_or_calc='m', _per=0.02, _c1=0, _c2=0, _a=0, _dg_by_len=0, _y0=0, _yp=0):
"""Setup magnetic field container with magnetic measurements or calculation data interpolated for given gap and phase. Faster version, reading only requiired field files.
:param _gap: magnetic gap [mm] for which the field should be set up
:param _ph_mode: type of phase (shift of magnet arrays) motion
:param _phase: shift of magnet arrays [mm] for which the field should be set up
:param _zc: center position [m]
:param _interp_ord: order of interpolation: 1- (bi-)linear, 2- (bi-)quadratic, 3- (bi-)cubic
:param _meas_or_calc: use magnetic measurements ('m') or calculation ('c') data
:param _per: undulator period [m]
:param _c1: constant defining (approximate) undulator field dependence on gap (i.e. c1 in b0*exp(-c1*gap/per + c2*(gap/per)^2))
:param _c2: constant defining (approximate) undulator field dependence on gap (i.e. c2 in b0*exp(-c1*gap/per + c2*(gap/per)^2))
:param _a: constant defining (approximate) undulator field dependence on vertical position (i.e. a in cosh(2*Pi*a*y/per)
:param _dg_by_len: gap taper (exit minus entrance) divided by undulator length
:param _y0: vertical electron position in the center of undulator relative to undulator median plane [m]
:param _dydz: vertical electron angle in the center of undulator relative to undulator median plane [rad]
"""
fPathSum = ''
if(_meas_or_calc == 'm'):
if(hasattr(self, 'dir_magn_meas') and hasattr(self, 'fn_magn_meas_sum')):
fPathSum = os.path.join(os.getcwd(), self.dir_main, self.dir_magn_meas, self.fn_magn_meas_sum)
else: raise Exception('No magnetic measurements data are supplied')
elif(_meas_or_calc == 'c'):
raise Exception('No magnetic calculation data are supplied')
f = open(fPathSum, 'r')
lines = f.readlines() #read-in all lines
nRows = len(lines)
strSep = '\t'
arGaps = []; arPhases = []; arFieldFileNames = []; arIndReqFiles = []
#arXc = []; arYc = []; arZc = []
arCoefBx = []; arCoefBy = []
phaseIsVar = False
phasePrev = None
#print('Setting up tabulated magnetic field')
#Read-in summary file and setup aux. arrays
for i in range(nRows):
curLine = lines[i]
curLineParts = curLine.split(strSep)
curLenLineParts = len(curLineParts)
if(curLenLineParts >= 4):
curPhaseMode = curLineParts[1]
if(curPhaseMode != _ph_mode): continue
curFileName = curLineParts[3].strip() #MR13012017
#print(curFileName)
if(len(curFileName) > 0):
arFieldFileNames.append(curFileName)
arGaps.append(float(curLineParts[0]))
curPhase = float(curLineParts[2])
if((phasePrev != None) and (curPhase != phasePrev)): phaseIsVar = True
arPhases.append(curPhase)
phasePrev = curPhase
arIndReqFiles.append(-1) #Array to be filled-out from C
if(curLenLineParts >= 6):
arCoefBx.append(float(curLineParts[4]))
arCoefBy.append(float(curLineParts[5]))
f.close()
numDims = 1
if(phaseIsVar): numDims += 1
precPar = [numDims, _gap, _phase, _interp_ord]
nIndReq = srwl.UtiUndFindMagFldInterpInds(arIndReqFiles, arGaps, arPhases, precPar) #to implement
if((nIndReq <= 0) or (nIndReq > nRows)):
raise Exception('Inconsistent magnetic field data summary file')
arResMagFld3D = [];
arResGaps = []; arResPhases = [];
arResXc = []; arResYc = []; arResZc = []
arResCoefBx = []; arResCoefBy = []
for j in range(nIndReq):
curInd = arIndReqFiles[j]
curFileName = arFieldFileNames[curInd]
curFilePath = os.path.join(os.getcwd(), self.dir_main, self.dir_magn_meas, curFileName)
curFldCnt = srwl_uti_read_mag_fld_3d(curFilePath, '#')
if(curFldCnt is not None):
arResMagFld3D.append(curFldCnt.arMagFld[0])
arResXc.append(curFldCnt.arXc[0])
arResYc.append(curFldCnt.arYc[0])
arResZc.append(curFldCnt.arZc[0] + _zc)
arResGaps.append(arGaps[curInd])
arResPhases.append(arPhases[curInd])
if(len(arCoefBx) > curInd): arResCoefBx.append(arCoefBx[curInd])
if(len(arCoefBy) > curInd): arResCoefBy.append(arCoefBy[curInd])
fldResCnt = SRWLMagFldC(arResMagFld3D, array('d', arResXc), array('d', arResYc), array('d', arResZc))
#nElem = len(arMagFld3D)
#if((nElem != len(arGaps)) or (nElem != len(arPhases))):
# raise Exception('Inconsistent magnetic field data summary file')
fldResCnt.arPar1 = array('d', arResGaps)
fldResCnt.arPar2 = array('d', arResPhases)
if(len(arResCoefBx) == nIndReq): fldResCnt.arPar3 = array('d', arResCoefBx)
if(len(arResCoefBy) == nIndReq): fldResCnt.arPar4 = array('d', arResCoefBy)
#print(' Gaps:', fldCnt.arPar1)
#print(' Phase Mode:', _ph_mode)
#print(' Phases:', fldCnt.arPar2)
#if(phaseIsVar is True): print(' Phase is variable')
#else: print(' Phase is constant')
fldCntFinRes = SRWLMagFldC(arResMagFld3D[0], arResXc[0], arResYc[0], arResZc[0])
#numDims = 1
#if(phaseIsVar): numDims += 1
#precPar = [numDims, _gap, _phase, _interp_ord]
##precPar = [1, _gap, _phase, _interp_ord]
precPar.append(1) #this means that search for necessary subset of indexes should not be done, i.e. the field container is assumed to include only the fields necessary for the interpolaton
self.mag = srwl.CalcMagnField(fldCntFinRes, fldResCnt, precPar)
if((_dg_by_len != 0.) or (_y0 != 0.) or (_yp != 0.)):
self.mag.arMagFld[0] = srwl_und_fld_1d_mis(self.mag.arMagFld[0], _per, _dg_by_len, _c1, _c2, 0.001*_gap, _a, _y0, _yp)
return self.mag
#------------------------------------------------------------------------
def set_und_per_from_tab(self, _rel_ac_thr=0.05, _max_nh=5, _max_per=0.1):
"""Setup periodic Magnetic Field from Tabulated one
:param _rel_ac_thr: relative accuracy threshold
:param _max_nh: max. number of harmonics to create
:param _max_per: max. period length to consider
"""
sErMes = 'Magnetic Field is not defined'
if(self.mag == None): Exception(sErMes)
if(isinstance(self.mag, SRWLMagFldC) == False): raise Exception(sErMes)
arHarm = []
for i in range(_max_nh): arHarm.append(SRWLMagFldH())
self.mag_approx = SRWLMagFldC(SRWLMagFldU(arHarm))
srwl.UtiUndFromMagFldTab(self.mag_approx, self.mag, [_rel_ac_thr, _max_nh, _max_per])
return self.mag_approx
#------------------------------------------------------------------------
def set_mag_tab(self, _fpath, _zc=0, _interp_ord=1):
"""Setup magnetic field container with tabulated magnetic field data
:param _fpath: path to magnetic field data file
:param _zc: center position[m]
:param _interp_ord: order of interpolation: 1- (bi-)linear, 2- (bi-)quadratic, 3- (bi-)cubic
"""
fpath = _fpath.strip() #MR13012017 #OC13012017
#if(os.path.exists(_fpath) == False):
if(os.path.exists(fpath) == False): #OC13012017
raise Exception('No magnetic field data are supplied')
#self.mag = srwl_uti_read_mag_fld_3d(_fpath)
self.mag = srwl_uti_read_mag_fld_3d(fpath) #OC13012017
self.mag.arZc[0] += _zc #?
#print('mag was set up in srwl_bl')
return self.mag
#------------------------------------------------------------------------
def set_gsn_beam(self, _x=0, _y=0, _z=0, _xp=0, _yp=0, _avgPhotEn=1, _pulseEn=1, _repRate=1, _polar=1,
_sigX=10e-06, _sigY=10e-06, _sigT=1e-15, _mx=0, _my=0, _presCA='c', _presFT='t'):
"""Setup Gaussian beam source
:param _x: average horizontal coordinates of waist [m]
:param _y: average vertical coordinates of waist [m]
:param _z: average longitudinal coordinate of waist [m]
:param _xp: average horizontal angle at waist [rad]
:param _yp: average verical angle at waist [rad]
:param _avgPhotEn: average photon energy [eV]
:param _pulseEn: energy per pulse [J]
:param _repRate: rep. rate [Hz]
:param _polar: polarization 1- lin. hor., 2- lin. vert., 3- lin. 45 deg., 4- lin.135 deg., 5- circ. right, 6- circ. left
:param _sigX: RMS beam size vs horizontal position [m] at waist (for intensity)
:param _sigY: RMS beam size vs vertical position [m] at waist (for intensity)
:param _sigT: RMS pulse duration [s] (for intensity)
:param _mx: transverse Gauss-Hermite mode order in horizontal direction
:param _my: transverse Gauss-Hermite mode order in vertical direction
:param _presCA: treat _sigX, _sigY as sizes in [m] in coordinate representation (_presCA="c") or as angular divergences in [rad] in angular representation (_presCA="a")
:param _presFT: treat _sigT as pulse duration in [s] in time domain/representation (_presFT="t") or as bandwidth in [eV] in frequency domain/representation (_presFT="f")
"""
if(self.gsnBeam != None): del self.gsnBeam
sigX = _sigX
sigY = _sigY
if(_presCA == 'a'):
convConstCA = _LightSp*_PlanckConst_eVs/(4*_Pi*_avgPhotEn)
sigX = convConstCA/sigX
sigY = convConstCA/sigY
sigT = _sigT
if(_presFT == 'f'):
convConstFT = _PlanckConst_eVs/(4*_Pi)
sigT = convConstFT/sigT
self.gsnBeam = SRWLGsnBm(_x, _y, _z, _xp, _yp, _avgPhotEn, _pulseEn, _repRate, _polar, sigX, sigY, sigT, _mx, _my)
return self.gsnBeam
#------------------------------------------------------------------------
def set_optics(self, _op):
"""Setup optical element container
:param _op: optical element container (SRWLOptC instance)
"""
if((_op == None) or (isinstance(_op, SRWLOptC) == False)):
raise Exception('Incorrect optics container (SRWLOptC) structure')
if(self.optics != None): del self.optics
self.optics = _op
#------------------------------------------------------------------------
def set_detector(self, _x=0, _rx=0, _nx=0, _dx=0, _y=0, _ry=0, _ny=0, _dy=0, _ord=1, _fname=''):
"""Setup detector
:param _x: horizontal center position of active area [m]
:param _rx: horizontal size of active area [m]
:param _nx: number of pixels in horizontal direction
:param _dx: horizontal pixel size [m]
:param _y: vertical center position of active area [m]
:param _ry: vertical size of active area [m]
:param _ny: number of pixels in vertical direction
:param _dy: vertical pixel size [m]
:param _ord: interpolation order (i.e. order of polynomials to be used at 2D interpolation)
:param _fname: file name with detector spectral efficiency data
"""
if((_rx <= 0) and (_nx <= 0) and (_ry <= 0) and (_ny <= 0)):
raise Exception('Incorrect detector parameters')
detSpecEff = 1
eStartDetSpecEff = 0
eFinDetSpecEff = 0
#if(len(_fname) > 0):
#Read-in detector spectral efficiency
#detSpecEff = ...
xHalfRangeDet = 0.5*_rx
yHalfRangeDet = 0.5*_ry
#self.detector = SRWLDet(
return SRWLDet(
_xStart = _x - xHalfRangeDet, _xFin = _x + xHalfRangeDet, _nx = _nx,
_yStart = _y - yHalfRangeDet, _yFin = _y + yHalfRangeDet, _ny = _ny,
_dx = _dx, _dy = _dy,
_spec_eff = detSpecEff, _eStart = eStartDetSpecEff, _eFin = eFinDetSpecEff)
#------------------------------------------------------------------------
def calc_el_trj(self, _ctst, _ctfi, _np=50000, _mag_type=1, _fname=''):
"""Calculates electron trajectory
:param _ctst: initial time (ct) for trajectory calculation
:param _ctfi: final time (ct) for trajectory calculation
:param _np: number of points for trajectory calculation
:param _mag_type: "type" of magnetic field to use:
1- "Approximate", referenced by self.mag_approx;
2- "Accurate" (tabulated), referenced by self.mag;
:param _fname: name of file to save the resulting data to (for the moment, in ASCII format)
:return: trajectory structure
"""
if(self.eBeam == None): Exception('Electron Beam structure is not defined')
if(_mag_type == 1):
if(self.mag_approx == None): Exception('Approximate Magnetic Field is not defined')
elif(_mag_type == 2):
if(self.mag == None): Exception('Magnetic Field is not defined')
else: Exception('Incorrect Magnetic Field type identificator')
magToUse = self.mag_approx
if(_mag_type == 2):
magToUse = self.mag
#print('Using tabulated magnetic field...')
partTraj = SRWLPrtTrj()
partTraj.partInitCond = self.eBeam.partStatMom1
partTraj.allocate(_np, True)
partTraj.ctStart = _ctst #Start Time (ct) for the calculation
partTraj.ctEnd = _ctfi
arPrecPar = [1] #General Precision parameters for Trajectory calculation:
#[0]: integration method No:
#1- fourth-order Runge-Kutta (precision is driven by number of points)
#2- fifth-order Runge-Kutta
#[1],[2],[3],[4],[5]: absolute precision values for X[m],X'[rad],Y[m],Y'[rad],Z[m] (yet to be tested!!) - to be taken into account only for R-K fifth order or higher
#[6]: tolerance (default = 1) for R-K fifth order or higher
#[7]: max. number of auto-steps for R-K fifth order or higher (default = 5000)
print('Electron trajectory calculation ... ', end='')
#print('Magnetic Field Object:', magToUse)
srwl.CalcPartTraj(partTraj, magToUse, arPrecPar)
print('completed')
if(len(_fname) > 0):
print('Saving trajectory data to a file ... ', end='')
partTraj.save_ascii(_fname)
print('completed')
return partTraj
#------------------------------------------------------------------------
#def calc_sr_se(self, _mesh, _samp_fact=-1, _meth=2, _rel_prec=0.01, _pol=6, _int_type=0, _mag_type=1, _fname=''):
#def calc_sr_se(self, _mesh, _samp_fact=-1, _meth=2, _rel_prec=0.01, _pol=6, _int_type=0, _mag_type=1, _fname='', _det=None): #OC06122016
def calc_sr_se(self, _mesh, _samp_fact=-1, _meth=2, _rel_prec=0.01, _pol=6, _int_type=0, _mag_type=1, _fname='', _det=None, _zi=0, _zf=0): #OC27122016
"""Calculates single-electron intensity
:param _mesh: mesh on which the intensity has to be calculated (SRWLRadMesh instance)
:param _samp_fact: sampling factor for adjusting nx, ny (effective if > 0)
:param _meth: SR calculation method: 0- "manual", 1- "auto-undulator", 2- "auto-wiggler"
:param _rel_prec: relative precision
:param _pol: polarization component to extract:
0- Linear Horizontal;
1- Linear Vertical;
2- Linear 45 degrees;
3- Linear 135 degrees;
4- Circular Right;
5- Circular Left;
6- Total
:param _int_type: "type" of a characteristic to be extracted:
-1- No Intensity / Electric Field components extraction is necessary (only Wavefront will be calculated)
0- "Single-Electron" Intensity;
1- "Multi-Electron" Intensity;
2- "Single-Electron" Flux;
3- "Multi-Electron" Flux;
4- "Single-Electron" Radiation Phase;
5- Re(E): Real part of Single-Electron Electric Field;
6- Im(E): Imaginary part of Single-Electron Electric Field;
7- "Single-Electron" Intensity, integrated over Time or Photon Energy (i.e. Fluence);
:param _mag_type: "type" of magnetic field to use:
1- "Approximate", referenced by self.mag_approx;
2- "Accurate" (tabulated), referenced by self.mag;
:param _fname: name of file to save the resulting data to (for the moment, in ASCII format)
:param _det: detector (instance of SRWLDet)
:param _zi: initial lonngitudinal position [m] of electron trajectory for SR calculation
:param _zf: final lonngitudinal position [m] of electron trajectory for SR calculation
:return: 1D array with (C-aligned) resulting intensity data
"""
if((_mesh == None) or (isinstance(_mesh, SRWLRadMesh) == False)):
raise Exception('Incorrect SRWLRadMesh structure')
depType = -1
if((_mesh.ne >= 1) and (_mesh.nx == 1) and (_mesh.ny == 1)): depType = 0
elif((_mesh.ne == 1) and (_mesh.nx > 1) and (_mesh.ny == 1)): depType = 1
elif((_mesh.ne == 1) and (_mesh.nx == 1) and (_mesh.ny > 1)): depType = 2
elif((_mesh.ne == 1) and (_mesh.nx > 1) and (_mesh.ny > 1)): depType = 3
elif((_mesh.ne > 1) and (_mesh.nx > 1) and (_mesh.ny == 1)): depType = 4
elif((_mesh.ne > 1) and (_mesh.nx == 1) and (_mesh.ny > 1)): depType = 5
elif((_mesh.ne > 1) and (_mesh.nx > 1) and (_mesh.ny > 1)): depType = 6
if(depType < 0): Exception('Incorrect numbers of points in the mesh structure')
if(self.eBeam == None): Exception('Electron Beam structure is not defined')
#print('In the beginning of calc_sr_se, mag_approx:', self.mag_approx)
if(_mag_type == 1):
if(self.mag_approx == None): Exception('Approximate Magnetic Field is not defined')
elif(_mag_type == 2):
if(self.mag == None): Exception('Magnetic Field is not defined')
else: Exception('Incorrect Magnetic Field type identificator')
magToUse = self.mag_approx
if(_mag_type == 2):
magToUse = self.mag
#print('Using tabulated magnetic field...')
wfr = SRWLWfr()
wfr.allocate(_mesh.ne, _mesh.nx, _mesh.ny) #Numbers of points vs Photon Energy, Horizontal and Vertical Positions
wfr.mesh = deepcopy(_mesh)
wfr.partBeam = self.eBeam
#zStartInteg = 0 #longitudinal position to start integration (effective if < zEndInteg)
#zEndInteg = 0 #longitudinal position to finish integration (effective if > zStartInteg)
zStartInteg = _zi #longitudinal position to start integration (effective if < zEndInteg)
zEndInteg = _zf #longitudinal position to finish integration (effective if > zStartInteg)
npTraj = 50000 #Number of points for trajectory calculation
useTermin = 1 #Use "terminating terms" (i.e. asymptotic expansions at zStartInteg and zEndInteg) or not (1 or 0 respectively)
arPrecPar = [_meth, _rel_prec, zStartInteg, zEndInteg, npTraj, useTermin, _samp_fact]
#print('calc_sr_se: magToUse=', magToUse)
#print('calc_sr_se: magToUse.arMagFld[0]=', magToUse.arMagFld[0])
print('Single-electron SR calculation ... ', end='')
t0 = time.time();
#DEBUG
#print(' e-beam z=', wfr.partBeam.partStatMom1.z)
#print('Eel=', wfr.partBeam.partStatMom1.get_E(), ' GeV')
#print('xe=', wfr.partBeam.partStatMom1.x, ' xpe=', wfr.partBeam.partStatMom1.xp, ' ye=', wfr.partBeam.partStatMom1.y, ' ype=', wfr.partBeam.partStatMom1.yp)
#print('nx=', wfr.mesh.nx, ' xStart=', wfr.mesh.xStart, ' xFin=', wfr.mesh.xFin)
#print('ny=', wfr.mesh.ny, ' yStart=', wfr.mesh.yStart, ' yFin=', wfr.mesh.yFin)
#END DEBUG
srwl.CalcElecFieldSR(wfr, 0, magToUse, arPrecPar) #calculate SR
print('completed (lasted', round(time.time() - t0, 6), 's)')
arI = None
if(_int_type >= 0):
print('Extracting intensity and saving it to a file ... ', end='')
t0 = time.time();
sNumTypeInt = 'f'
if(_int_type == 4): sNumTypeInt = 'd' #Phase?
#resMeshI = wfr.mesh
resMeshI = deepcopy(wfr.mesh)
arI = array(sNumTypeInt, [0]*resMeshI.ne*resMeshI.nx*resMeshI.ny)
srwl.CalcIntFromElecField(arI, wfr, _pol, _int_type, depType, resMeshI.eStart, resMeshI.xStart, resMeshI.yStart)
if(_det is not None): #OC06122016
#resStkDet = _det.treat_int(arI, resMeshI, _ord_interp=1)
resStkDet = _det.treat_int(arI, resMeshI) #OC11012017
arI = resStkDet.arS
resMeshI = resStkDet.mesh
if(len(_fname) > 0): srwl_uti_save_intens_ascii(arI, resMeshI, _fname, 0, ['Photon Energy', 'Horizontal Position', 'Vertical Position', ''], _arUnits=['eV', 'm', 'm', 'ph/s/.1%bw/mm^2'])
print('completed (lasted', round(time.time() - t0, 6), 's)')
#return wfr, arI
return wfr, arI, resMeshI #OC06122016
#------------------------------------------------------------------------
#def calc_rad_gsn(self, _mesh, _samp_fact=-1, _pol=6, _int_type=0, _presFT='f', _unitE=2, _fname=''):
def calc_rad_gsn(self, _mesh, _samp_fact=-1, _pol=6, _int_type=0, _presFT='f', _unitE=2, _fname='', _det=None): #OC06122016
"""Calculates Gaussian beam wavefront (electric field) and intensity
:param _mesh: mesh on which the intensity has to be calculated (SRWLRadMesh instance)
:param _samp_fact: sampling factor for adjusting nx, ny (effective if > 0)
:param _pol: polarization component to extract:
0- Linear Horizontal;
1- Linear Vertical;
2- Linear 45 degrees;
3- Linear 135 degrees;
4- Circular Right;
5- Circular Left;
6- Total
:param _int_type: "type" of a characteristic to be extracted:
-1- No Intensity / Electric Field components extraction is necessary (only Wavefront will be calculated)
0- "Single-Electron" / Coherent Beam Intensity;
1- "Multi-Electron" / Partially-Coherent Beam Intensity;
2- "Single-Electron" / Coherent Beam Flux;
3- "Multi-Electron" / Partially-Coherent Beam Flux;
4- "Single-Electron" / Coherent Beam Radiation Phase;
5- Re(E): Real part of Single-Electron / Coherent Beam Electric Field;
6- Im(E): Imaginary part of Single-Electron / Coherent Beam Electric Field;
7- "Single-Electron" / Coherent Beam Intensity, integrated over Time or Photon Energy (i.e. Fluence);
:param _presFT: calculate electric field (and intensity) in time domain/representation (="t") or in frequency domain/representation (="f")
:param _unitE: #electric field units: 0- arbitrary, 1- sqrt(Phot/s/0.1%bw/mm^2), 2- sqrt(J/eV/mm^2) or sqrt(W/mm^2), depending on representation (freq. or time)
:param _fname: name of file to save the resulting data to (for the moment, in ASCII format)
:return: 1D array with (C-aligned) resulting intensity data
"""
if((_mesh == None) or (isinstance(_mesh, SRWLRadMesh) == False)):
raise Exception('Incorrect SRWLRadMesh structure')
depType = -1
if((_mesh.ne >= 1) and (_mesh.nx == 1) and (_mesh.ny == 1)): depType = 0
elif((_mesh.ne == 1) and (_mesh.nx > 1) and (_mesh.ny == 1)): depType = 1
elif((_mesh.ne == 1) and (_mesh.nx == 1) and (_mesh.ny > 1)): depType = 2
elif((_mesh.ne == 1) and (_mesh.nx > 1) and (_mesh.ny > 1)): depType = 3
elif((_mesh.ne > 1) and (_mesh.nx > 1) and (_mesh.ny == 1)): depType = 4
elif((_mesh.ne > 1) and (_mesh.nx == 1) and (_mesh.ny > 1)): depType = 5
elif((_mesh.ne > 1) and (_mesh.nx > 1) and (_mesh.ny > 1)): depType = 6
if(depType < 0): Exception('Incorrect numbers of points in the mesh structure')
wfr = SRWLWfr()
wfr.allocate(_mesh.ne, _mesh.nx, _mesh.ny) #Numbers of points vs Photon Energy, Horizontal and Vertical Positions
wfr.mesh = deepcopy(_mesh)
wfr.presFT = 0 #presentation/domain: 0- frequency (photon energy), 1- time
if(_presFT == "t"): wfr.presFT = 1
wfr.unitElFld = _unitE;
wfr.partBeam.partStatMom1.x = self.gsnBeam.x #Some information about the source in the Wavefront structure
wfr.partBeam.partStatMom1.y = self.gsnBeam.y
wfr.partBeam.partStatMom1.z = self.gsnBeam.z
wfr.partBeam.partStatMom1.xp = self.gsnBeam.xp
wfr.partBeam.partStatMom1.yp = self.gsnBeam.yp
print('Gaussian beam electric field calculation ... ', end='')
t0 = time.time();
srwl.CalcElecFieldGaussian(wfr, self.gsnBeam, [_samp_fact])
print('completed (lasted', round(time.time() - t0, 6), 's)')
arI = None
if(_int_type >= 0):
print('Extracting intensity and saving it to a file ... ', end='')
t0 = time.time();
sNumTypeInt = 'f'
if(_int_type == 4): sNumTypeInt = 'd'
#print('depType=', depType)
#resMeshI = wfr.mesh
resMeshI = deepcopy(wfr.mesh)
arI = array(sNumTypeInt, [0]*resMeshI.ne*resMeshI.nx*resMeshI.ny)
srwl.CalcIntFromElecField(arI, wfr, _pol, _int_type, depType, resMeshI.eStart, resMeshI.xStart, resMeshI.yStart)
#print('_det=', _det)
if(_det is not None): #OC06122016
#resStkDet = _det.treat_int(arI, resMeshI, _ord_interp=1)
resStkDet = _det.treat_int(arI, resMeshI) #OC11012017
arI = resStkDet.arS
resMeshI = resStkDet.mesh
if(len(_fname) > 0): srwl_uti_save_intens_ascii(arI, resMeshI, _fname, 0, ['Photon Energy', 'Horizontal Position', 'Vertical Position', ''], _arUnits=['eV', 'm', 'm', 'ph/s/.1%bw/mm^2'])
print('completed (lasted', round(time.time() - t0, 6), 's)')
#print('wfr.mesh.eStart=', wfr.mesh.eStart, 'wfr.mesh.eFin=', wfr.mesh.eFin, 'wfr.mesh.ne=', wfr.mesh.ne)
#print('resMeshI.eStart=', resMeshI.eStart, 'resMeshI.eFin=', resMeshI.eFin, 'resMeshI.ne=', resMeshI.ne)
#print('wfr.mesh.xStart=', wfr.mesh.xStart, 'wfr.mesh.xFin=', wfr.mesh.xFin, 'wfr.mesh.nx=', wfr.mesh.nx)
#print('resMeshI.xStart=', resMeshI.xStart, 'resMeshI.xFin=', resMeshI.xFin, 'resMeshI.nx=', resMeshI.nx)