def build_beamline(): beamLine = raycing.BeamLine() beamLine.oe = ToroidMirrorDistorted(beamLine, 'warped', center=[0, p, 0], pitch=pitch, R=Rnom, r=rdefocus) dx = beamLine.oe.limPhysX[1] - beamLine.oe.limPhysX[0] dy = beamLine.oe.limPhysY[1] - beamLine.oe.limPhysY[0] # beamLine.source = rs.GeometricSource( # beamLine, 'CollimatedSource', nrays=nrays, dx=source_dX, dz=source_dZ, # dxprime=dx/p/2, dzprime=dy/p*np.sin(pitch)/2) kwargs = dict(eE=3., eI=0.5, eEspread=0, eEpsilonX=eEpsilonX * 1e9 * emittanceFactor, eEpsilonZ=eEpsilonZ * 1e9 * emittanceFactor, betaX=betaX, betaZ=betaZ, period=18.5, n=108, K=K, filamentBeam=(what != 'rays'), xPrimeMax=dx / 2 / p * 1e3, zPrimeMax=dy / 2 / p * np.sin(pitch) * 1e3, xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, eMin=E0 - dE / 2, eMax=E0 + dE / 2) beamLine.source = rs.Undulator(beamLine, nrays=nrays, **kwargs) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM0', [0, p + q, 0]) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', [0, p + q, q * np.tan(2 * pitch)]) return beamLine
def build_beamline(nrays=2e5): beamLine = raycing.BeamLine() rs.Undulator( beamLine, 'P06', nrays=nrays, eEspread=0.0011, eSigmaX=34.64, eSigmaZ=6.285, eEpsilonX=1., eEpsilonZ=0.01, period=31.4, K=2.1392 - 0.002, n=63, eE=6.08, eI=0.1, xPrimeMax=1.5e-2, zPrimeMax=1.5e-2, eMin=eMin, eMax=eMax, distE='BW', xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, # targetOpenCL='CPU', taper=(1.09, 11.254)) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', (0, 90000, 0)) return beamLine
def main(): E = 9000 energy = np.linspace(8500, 9500, 501) theta = np.linspace(-1, 1, 512) * 20e-6 psi = np.linspace(-1, 1, 512) * 20e-6 # kwargs = dict(eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, # betaX=9.539, betaZ=1.982, period=18.5, n=108, K=0.52, # eEspread=1e-3, # xPrimeMax=theta[-1]*1e3, zPrimeMax=psi[-1]*1e3, # targetOpenCL='CPU', # distE='BW') kwargs = dict(eE=6.083, eEpsilonX = 1.3, #0.02,#1.3, #1300 pmrad eEpsilonZ = 0.01,#0.004,#0.01, #10pmrad period=32.8, n=63, targetE=[9000, 3], eMin= E + 500, eMax= E - 500, xPrimeMax=0.02, #xPrimeMax=0.1, zPrimeMax=0.02, #xPrimeMax=0.1, gp=1e-06, distE='BW', taper = (1., 12.), targetOpenCL='GPU') # energy = [200000., 200000.] # theta = np.linspace(-2./25000., 2./25000., 51) # psi = np.linspace(-2./25000., 2./25000., 51) # kwargs = dict(name='IVU18.5', eE=3.0, eI=0.5, # eEpsilonX=0.263, eEpsilonZ=0.008, # betaX=9., betaZ=2., # period=18.5, n=108, K=1.92, # xPrimeMax=theta[-1]*1e3, zPrimeMax=psi[-1]*1e3, distE='BW') if True: # xrt Undulator source = rs.Undulator(**kwargs) I0, l1, l2, l3 = source.intensities_on_mesh(energy, theta, psi) else: # Urgent kwargs['eSigmaX'] = (kwargs['eEpsilonX']*kwargs['betaX']*1e3)**0.5 kwargs['eSigmaZ'] = (kwargs['eEpsilonZ']*kwargs['betaZ']*1e3)**0.5 del(kwargs['distE']) del(kwargs['betaX']) del(kwargs['betaZ']) kwargs['eMin'] = energy[0] kwargs['eMax'] = energy[-1] kwargs['eN'] = len(energy) kwargs['icalc'] = 3 kwargs['nx'] = len(theta)//2 kwargs['nz'] = len(psi)//2 import xrt.backends.raycing as raycing beamLine = raycing.BeamLine(azimuth=0, height=0) source = rs.UndulatorUrgent(beamLine, **kwargs) I0, l1, l2, l3 = source.intensities_on_mesh() I0 = np.concatenate((I0[:, :0:-1, :], I0), axis=1) I0 = np.concatenate((I0[:, :, :0:-1], I0), axis=2) # flux_through_aperture(energy, theta, psi, I0) save_3dMatrix(energy, theta, psi, I0)
def as_xrt( self, gap="min", energy=None, harmonic=1, distE="BW", max_angle_rad=10e-3 / 30, nrays=1000, **kwargs, ): """ use distE = 'eV' for - XRT ray tracing (for example important when using fluxkind='power') use distE = 'BW' for spectral calculations of sr """ import xrt.backends.raycing.sources as rs use_srw = kwargs.get("use_srw", False) if energy is not None: pars = self.find_harmonic_and_gap(energy, sort_harmonics=True, use_srw=use_srw)[0] gap = pars["gap"] harmonic = pars["harmonic"] if isinstance(gap, str) and gap == "min": gap = self.min_gap if "flux" in kwargs: kwargs.pop("flux") try: max_angle_rad[0] except TypeError: max_angle_rad = (max_angle_rad, max_angle_rad) ebeam = self.ebeam kw = dict( eE=ebeam.ebeam_energy, eI=ebeam.sr_cur, eSigmaX=ebeam.sh * 1e6, eSigmaZ=ebeam.sv * 1e6, eEpsilonX=ebeam.emitth * 1e9, eEpsilonZ=ebeam.emittv * 1e9, eEspread=ebeam.rms_energy_spread, period=self.period, n=int(self.length * 1e3 / self.period), K=self.k(gap="min"), xPrimeMax=max_angle_rad[0] * 1e3, # wants in mrad zPrimeMax=max_angle_rad[1] * 1e3, # wants in mrad nrays=nrays, targetE=[ self.photon_energy(gap=gap, harmonic=harmonic) * 1e3, harmonic ], distE=distE, ) kw.update(**kwargs) print(kw) u = rs.Undulator(**kw) return u
def build_beamline(nrays=mynrays): beamLine = raycing.BeamLine() rs.Undulator(beamLine, nrays=nrays, **kwargs) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM0', (0, R0-1, 0)) beamLine.slit = ra.DoubleSlit( beamLine, 'squareSlit', [0, R0, 0], ('left', 'right', 'bottom', 'top'), [-slitDx/2, slitDx/2, -slitDz/2, slitDz/2], shadeFraction=0.1) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', [0, R0+dR, 0]) return beamLine
def build_beamline(nrays=mynrays): beamLine = raycing.BeamLine() beamLine.source = rs.Undulator(beamLine, nrays=nrays, **kwargs) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM0', (0, R0, 0)) beamLine.slit = ra.RectangularAperture(beamLine, 'squareSlit', [0, R0, 0], ('left', 'right', 'bottom', 'top'), [-slitDx, slitDx, -slitDz, slitDz]) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', [0, R0, 0]) return beamLine
def main(): energy = np.linspace(3850, 4150, 601) theta = np.linspace(-1, 1, 51) * 30e-6 psi = np.linspace(-1, 1, 51) * 30e-6 kwargs = dict( eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, betaX=9.539, betaZ=1.982, period=18.5, n=108, K=0.52, # eEspread=1e-3, xPrimeMax=theta[-1] * 1e3, zPrimeMax=psi[-1] * 1e3, # targetOpenCL='CPU', distE='BW') # energy = [200000., 200000.] # theta = np.linspace(-2./25000., 2./25000., 51) # psi = np.linspace(-2./25000., 2./25000., 51) # kwargs = dict(name='IVU18.5', eE=3.0, eI=0.5, # eEpsilonX=0.263, eEpsilonZ=0.008, # betaX=9., betaZ=2., # period=18.5, n=108, K=1.92, # xPrimeMax=theta[-1]*1e3, zPrimeMax=psi[-1]*1e3, distE='BW') if True: # xrt Undulator source = rs.Undulator(**kwargs) I0, l1, l2, l3 = source.intensities_on_mesh(energy, theta, psi) else: # Urgent kwargs['eSigmaX'] = (kwargs['eEpsilonX'] * kwargs['betaX'] * 1e3)**0.5 kwargs['eSigmaZ'] = (kwargs['eEpsilonZ'] * kwargs['betaZ'] * 1e3)**0.5 del (kwargs['distE']) del (kwargs['betaX']) del (kwargs['betaZ']) kwargs['eMin'] = energy[0] kwargs['eMax'] = energy[-1] kwargs['eN'] = len(energy) kwargs['icalc'] = 3 kwargs['nx'] = len(theta) // 2 kwargs['nz'] = len(psi) // 2 import xrt.backends.raycing as raycing beamLine = raycing.BeamLine(azimuth=0, height=0) source = rs.UndulatorUrgent(beamLine, **kwargs) I0, l1, l2, l3 = source.intensities_on_mesh() I0 = np.concatenate((I0[:, :0:-1, :], I0), axis=1) I0 = np.concatenate((I0[:, :, :0:-1], I0), axis=2) flux_through_aperture(energy, theta, psi, I0)
def main(): energy = np.linspace(3850, 4150, 601) theta = np.linspace(-1, 1, 51) * 30e-6 psi = np.linspace(-1, 1, 51) * 30e-6 kwargs = dict( eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, betaX=9.539, betaZ=1.982, period=18.5, n=108, K=0.52, xPrimeMax=theta[-1] * 1e3, zPrimeMax=psi[-1] * 1e3, # targetOpenCL='CPU', distE='BW') source = rs.Undulator(**kwargs) I0, l1, l2, l3 = source.intensities_on_mesh(energy, theta, psi) flux_through_aperture(energy, theta, psi, I0) # intensity_in_transverse_plane(energy, theta, psi, I0) # colored_intensity_in_transverse_plane(energy, theta, psi, I0) if wantUrgentUndulator: kwargs['eSigmaX'] = (kwargs['eEpsilonX'] * kwargs['betaX'] * 1e3)**0.5 kwargs['eSigmaZ'] = (kwargs['eEpsilonZ'] * kwargs['betaZ'] * 1e3)**0.5 del (kwargs['distE']) del (kwargs['betaX']) del (kwargs['betaZ']) kwargs['eMin'] = energy[0] kwargs['eMax'] = energy[-1] kwargs['eN'] = len(energy) kwargs['icalc'] = 3 kwargs['nx'] = len(theta) // 2 kwargs['nz'] = len(psi) // 2 import xrt.backends.raycing as raycing beamLine = raycing.BeamLine(azimuth=0, height=0) sourceU = rs.UndulatorUrgent(beamLine, **kwargs) I0, l1, l2, l3 = sourceU.intensities_on_mesh() I0 = np.concatenate((I0[:, :0:-1, :], I0), axis=1) I0 = np.concatenate((I0[:, :, :0:-1], I0), axis=2) urgentEnergy = sourceU.Es flux_through_aperture(urgentEnergy, theta, psi, I0 * 1e6)
def build_beamline(nrays=mynrays): beamLine = raycing.BeamLine() beamLine.source = rs.Undulator(beamLine, nrays=nrays, **kwargs) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM0', (0, R0, 0)) # beamLine.slit = ra.RectangularAperture( # beamLine, 'squareSlit', [0, R0, 0], ('left', 'right', 'bottom', 'top'), # [-slitDx, slitDx, -slitDz, slitDz]) beamLine.slit = ra.SiemensStar(bl=beamLine, name='SiemensStar', center=[0, R0, 0], nSpokes=nSpokes, rX=slitDx, rZ=slitDz, phi0=0.5 * np.pi / nSpokes) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', [0, R0, 0]) return beamLine
def build_beamline(nrays=mynrays): beamLine = raycing.BeamLine() beamLine.source = rs.Undulator(beamLine, nrays=nrays, **kwargs) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM0', (0, R0, 0)) # beamLine.slit = ra.RectangularAperture( # beamLine, 'squareSlit', [0, R0, 0], ('left', 'right', 'bottom', 'top'), # [-slitDx, slitDx, -slitDz, slitDz]) star = np.linspace(0, 2*np.pi, 6) starX = slitDx*np.sin(star) starY = slitDx*np.cos(star) beamLine.slit = ra.PolygonalAperture( bl=beamLine, name=None, center=[0, R0, 0], opening=[(starX[0], starY[0]), (starX[2], starY[2]), (starX[4], starY[4]), (starX[1], starY[1]), (starX[3], starY[3]), (starX[0], starY[0])]) # opening=list(zip(starX, starY))) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', [0, R0, 0]) return beamLine
def build_beamline(nrays=1e5): beamLine = raycing.BeamLine() beamLine.source = rs.Undulator(beamLine, nrays=nrays, **kwargs) beamLine.fsm1 = rsc.Screen(beamLine, 'FSM1', (0, R0, 0)) return beamLine
def build_beamline(): beamLine = raycing.BeamLine() # rs.GeometricSource( # beamLine, 'source', nrays=nrays, polarization='horizontal', **kw) rs.Undulator(beamLine, nrays=nrays, **kwargs) if case == 'mirror': beamLine.diffoe = roe.OE(beamLine, 'PlaneMirror', (0, p, 0), pitch=pitch, material=coating) phiOffset = 2 * pitch zFlatScreen = q * np.sin(2 * pitch) zHemScreen = 0 elif case == 'mirrorEll': beamLine.diffoe = roe.EllipticalMirrorParam(beamLine, 'EllipticalMirror', (0, p, 0), p=p, q=q, pitch=pitch, material=coating) phiOffset = 2 * pitch zFlatScreen = q * np.sin(2 * pitch) zHemScreen = 0 elif case == '2mirrors': beamLine.oe0 = roe.OE(beamLine, 'PlaneMirror0', (0, p - dp, 0), pitch=pitch, material=coating) zFlatScreen = dp * np.tan(2 * pitch) beamLine.diffoe = roe.OE(beamLine, 'PlaneMirror', (0, p, zFlatScreen), pitch=-pitch, positionRoll=np.pi, material=coating) phiOffset = 0 zHemScreen = zFlatScreen elif case == '2mirrorsEll': beamLine.oe0 = roe.OE(beamLine, 'PlaneMirror0', (0, p - dp, 0), pitch=pitch, material=coating) zFlatScreen = dp * np.tan(2 * pitch) beamLine.diffoe = roe.EllipticalMirrorParam(beamLine, 'EllipticalMirror', (0, p, zFlatScreen), p=p, q=q, pitch=-pitch, positionRoll=np.pi, material=coating) phiOffset = 0 zHemScreen = zFlatScreen elif case == 'aperture': beamLine.diffoe = ra.RectangularAperture( beamLine, 'ra', (0, p, 0), ('left', 'right', 'bottom', 'top')) phiOffset = 0 zFlatScreen = 0 zHemScreen = 0 if case.startswith('mir'): zvec = [0, -np.sin(2 * pitch), np.cos(2 * pitch)]
def build_beamline(azimuth=0): beamLine = raycing.BeamLine(azimuth=azimuth, height=0) beamLine.source = rs.Undulator(beamLine, 'Softi53', nrays=nrays, eE=3.0, eI=0.5, eEspread=0.0008 * energySpreadFactor, eEpsilonX=0.263 * emittanceFactor, eEpsilonZ=0.008 * emittanceFactor, betaX=9., betaZ=2., period=48., n=77, targetE=(E0, targetHarmonic), eMin=E0 - dE * vFactor, eMax=E0 + dE * vFactor, xPrimeMax=acceptanceHor / 2 * 1e3, zPrimeMax=acceptanceVer / 2 * 1e3, xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, uniformRayDensity=True, filamentBeam=True) opening = [ -acceptanceHor * pFE / 2, acceptanceHor * pFE / 2, -acceptanceVer * pFE / 2, acceptanceVer * pFE / 2 ] beamLine.slitFE = ra.RectangularAperture( beamLine, 'FE slit', kind=['left', 'right', 'bottom', 'top'], opening=opening) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM-M1') beamLine.m1 = roe.ToroidMirror(beamLine, 'M1', surface=('Au', ), material=(mAu, ), limPhysX=(-5, 5), limPhysY=(-150, 150), positionRoll=np.pi / 2, R=1e22, alarmLevel=0.1) # beamLine.fsm1 = rsc.Screen(beamLine, 'FSM-M1') beamLine.m2 = roe.OE(beamLine, 'M2', surface=('Au', ), material=(mAu, ), limPhysX=(-5, 5), limPhysY=(-225, 225), alarmLevel=0.1) gratingKW = dict(positionRoll=np.pi, limPhysX=(-2, 2), limPhysY=(-40, 40), alarmLevel=0.1) beamLine.pg = roe.BlazedGrating(beamLine, 'BlazedGrating', material=mGolden, blaze=blaze, rho=rho, **gratingKW) beamLine.pg.order = 1 # beamLine.fsmPG = rsc.Screen(beamLine, 'FSM-PG') beamLine.m3 = roe.ToroidMirror(beamLine, 'M3', surface=('Au', ), material=(mAu, ), positionRoll=-np.pi / 2, limPhysX=(-10., 10.), limPhysY=(-100., 100.), alarmLevel=0.1) beamLine.fsm3 = rsc.Screen(beamLine, 'FSM-M3') # beamLine.exitSlit = ra.RoundAperture( # beamLine, 'ExitSlit', r=ESradius, alarmLevel=None) beamLine.exitSlit = ra.RectangularAperture(beamLine, 'ExitSlit', opening=[ -ESdX * hFactor / 2, ESdX * hFactor / 2, -ESdZ * vFactor / 2, ESdZ * vFactor / 2 ]) beamLine.m4 = roe.EllipticalMirrorParam(beamLine, 'M4', surface=('Au', ), material=(mAu, ), positionRoll=np.pi / 2, pitch=pitch, isCylindrical=True, p=43000., q=dM45 + pExp, limPhysX=(-0.5, 0.5), limPhysY=(-70., 70.), alarmLevel=0.2) beamLine.m5 = roe.EllipticalMirrorParam(beamLine, 'M5', surface=('Au', ), material=(mAu, ), yaw=-2 * pitch, pitch=pitch, isCylindrical=True, p=dM4ES + dM45, q=pExp, limPhysX=(-0.5, 0.5), limPhysY=(-40., 40.), alarmLevel=0.2) beamLine.fsmExp = rsc.Screen(beamLine, 'FSM-Exp') return beamLine
def build_beamline(azimuth=0): beamLine = raycing.BeamLine(azimuth=azimuth, height=0) beamLine.source = rs.Undulator( beamLine, 'Softi53', nrays=nrays, eE=3.0, eI=0.5, eEspread=0.0008*energySpreadFactor, eEpsilonX=0.263*emittanceFactor, eEpsilonZ=0.008*emittanceFactor, betaX=9., betaZ=2., period=48., n=81, targetE=(E0, targetHarmonic), eMin=E0-dE*vFactor, eMax=E0+dE*vFactor, xPrimeMax=acceptanceHor/2*1e3*hShrink, zPrimeMax=acceptanceVer/2*1e3*vShrink, xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, targetOpenCL='CPU', uniformRayDensity=True, filamentBeam=(what != 'rays')) opening = [-acceptanceHor*pFE/2*hShrink, acceptanceHor*pFE/2*hShrink, -acceptanceVer*pFE/2*vShrink, acceptanceVer*pFE/2*vShrink] beamLine.slitFE = ra.RectangularAperture( beamLine, 'FE slit', kind=['left', 'right', 'bottom', 'top'], opening=opening) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM-M1') xShrink = vShrink if what == 'wave' else 1 yShrink = hShrink if what == 'wave' else 1 beamLine.m1 = roe.ToroidMirror( beamLine, 'M1', surface=('Au',), material=(material,), limPhysX=(-5*xShrink, 5*xShrink), limPhysY=(-150*yShrink, 150*yShrink), positionRoll=np.pi/2, R=1e22, alarmLevel=0.1) # beamLine.fsm1 = rsc.Screen(beamLine, 'FSM-M1') xShrink = hShrink if what == 'wave' else 1 yShrink = vShrink if what == 'wave' else 1 beamLine.m2 = roe.OE( beamLine, 'M2', surface=('Au',), material=(material,), limPhysX=(-5*xShrink, 5*xShrink), limPhysY=(-225*yShrink, 225*yShrink), alarmLevel=0.1) gratingKW = dict( positionRoll=np.pi, limPhysX=(-2*xShrink, 2*xShrink), limPhysY=(-40*yShrink, 40*yShrink), alarmLevel=0.1) if what == 'rays': beamLine.pg = Grating(beamLine, 'PlaneGrating', material=gratingMaterial, **gratingKW) beamLine.pg.material.efficiency = [(1, 0.4)] else: beamLine.pg = roe.BlazedGrating( beamLine, 'BlazedGrating', material=material, blaze=blaze, rho=rho, **gratingKW) beamLine.pg.order = 1 # beamLine.fsmPG = rsc.Screen(beamLine, 'FSM-PG') beamLine.m3 = roe.ToroidMirror( beamLine, 'M3', surface=('Au',), material=(material,), positionRoll=-np.pi/2, limPhysX=(-2*vShrink, 2*vShrink), limPhysY=(-80*hShrink*hExtraFactor, 80*hShrink*hExtraFactor), #limPhysY=(-80*hShrink, 80*hShrink), alarmLevel=0.1) beamLine.fsm3 = rsc.Screen(beamLine, 'FSM-M3') # beamLine.exitSlit = ra.RoundAperture( # beamLine, 'ExitSlit', r=ESradius, alarmLevel=None) beamLine.exitSlit = ra.RectangularAperture( beamLine, 'ExitSlit', opening=[-ESdX/2*hFactor*hShrink, ESdX/2*hFactor*hShrink, -ESdZ/2*vFactor*vShrink, ESdZ/2*vFactor*vShrink]) beamLine.fzp = roe.NormalFZP( beamLine, 'FZP', pitch=np.pi/2, material=mAuFZP, f=focus, E=E0, N=Nzone) beamLine.fzp.order = 1 beamLine.fzp.material.efficiency = [(1, 0.1)] # used with rays print('outerzone = {0} mm'.format(beamLine.fzp.rn[-1]-beamLine.fzp.rn[-2])) beamLine.fzp.area = np.pi * beamLine.fzp.rn[-1]**2 / 2 beamLine.fsmFZP = rsc.Screen(beamLine, 'FSM-FZP') beamLine.fsmExp = rsc.Screen(beamLine, 'FSM-Exp') return beamLine
# path to xrt: import os, sys sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter import xrt.backends.raycing.sources as rs print("please wait...") source = rs.Undulator(eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, betaX=9.539, betaZ=1.982, period=18.5, n=108, K=0.52, eEspread=0 * 8e-4, distE='BW', gIntervals=2) energy = np.linspace(2000, 30000, 5601) theta = np.linspace(-1, 1, 11) * 30e-6 # 60 µrad opening psi = np.linspace(-1, 1, 11) * 30e-6 # 60 µrad opening xlims, ylims = (3, 24), (1e14, 5e15) Ks = np.linspace(0.3, 2.2, 20) Kmax, gmin = 1.92, 4.2 # needed to calculate gap(K) gaps = np.log(Kmax / Ks) / np.pi * source.L0 + gmin harmonics = [1, 2, 3, 4, 5, 7, 9] colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
def main(): und = rs.Undulator( name='MAX IV U19', eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, betaX=9., betaZ=2., # """Compare with # Harry Westfahl Jr et al. J. Synchrotron Rad. (2017). 24, 566–575. # But notice their non-equidistant (in energy) harmonics.""" # name='Sirius U19', eE=3.0, eI=0.35, # eEpsilonX=0.245, eEpsilonZ=0.0024, # betaX=1.5, betaZ=1.5, period=19, n=105, targetE=(10000, 7), xPrimeMax=thetaMax*1e3, zPrimeMax=psiMax*1e3, xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, eEspread=1e-3, # targetOpenCL='CPU', precisionOpenCL='float32') print(u"Electron beam linear sizes = {0:.3f} µm × {1:.3f} µm".format( und.dx*1e3, und.dz*1e3)) print(u"Electron beam angular sizes = {0:.3f} µrad × {1:.3f} µrad".format( und.dxprime*1e6, und.dzprime*1e6)) E = np.linspace(1400., 20000., 1860+1) sx0, sz0 = und.get_SIGMA(E, with0eSpread=True) sPx0, sPz0 = und.get_SIGMAP(E, with0eSpread=True) sx, sz = und.get_SIGMA(E) sPx, sPz = und.get_SIGMAP(E) fig1 = plt.figure(1) ax1 = fig1.add_subplot(111) ax1.set_title("{0} undulator: linear source size".format(und.name)) ax1.set_xlabel(u'energy (keV)') ax1.set_ylabel(u'rms linear source size (µm)') l1, = ax1.plot(E*1e-3, sx0*1e3, '--C0') l2, = ax1.plot(E*1e-3, sz0*1e3, '--C1') l3, = ax1.plot(E*1e-3, sx*1e3, '-C0') l4, = ax1.plot(E*1e-3, sz*1e3, '-C1') ax1.set_xlim(0, 20) ax1.set_ylim(0, None) ax1.xaxis.set_ticks([0, 5, 10, 15, 20]) ax1.grid() leg1 = ax1.legend([(l1, l3), (l2, l4)], [r"$\sigma_x$", r"$\sigma_y$"], handler_map={tuple: TwoLineObjectsHandler()}, loc='center left') leg2 = ax1.legend([(l1, l2), (l3, l4)], [r'$\sigma_E$ = 0', r'$\sigma_E$ = 0.1%'], handler_map={tuple: TwoLineObjectsHandler()}, title='at energy spread', loc='right') ax1.add_artist(leg1) ax1.add_artist(leg2) fig2 = plt.figure(2) ax2 = fig2.add_subplot(111) ax2.set_title("{0} undulator: angular source size".format(und.name)) ax2.set_xlabel(u'energy (keV)') ax2.set_ylabel(u'rms angular source size (µrad)') ax2.plot(E*1e-3, sPx0*1e6, '--C0') ax2.plot(E*1e-3, sPz0*1e6, '--C1') ax2.plot(E*1e-3, sPx*1e6, '-C0') ax2.plot(E*1e-3, sPz*1e6, '-C1') ax2.set_xlim(0, 20) ax2.set_ylim(0, None) ax2.xaxis.set_ticks([0, 5, 10, 15, 20]) ax2.grid() leg1 = ax2.legend([(l1, l3), (l2, l4)], [r"$\sigma'_x$", r"$\sigma'_y$"], handler_map={tuple: TwoLineObjectsHandler()}, loc='upper center') leg2 = ax2.legend([(l1, l2), (l3, l4)], [r'$\sigma_E$ = 0', r'$\sigma_E$ = 0.1%'], handler_map={tuple: TwoLineObjectsHandler()}, title='at energy spread', loc='lower center') ax2.add_artist(leg1) ax2.add_artist(leg2) if withXrtSampling: theta = np.linspace(-1, 1, 201) * thetaMax psi = np.linspace(-1, 1, 101) * psiMax Eh = (np.arange(1, 14, 2) * und.E1 + 10*np.arange(-10, 7)[:, np.newaxis]) sh = Eh.shape flux, sigma2theta, sigma2psi, dx2, dz2 = und.real_photon_source_sizes( Eh.ravel(), theta, psi) sigma2theta += und.dxprime**2 sigma2psi += und.dzprime**2 dx2 += und.dx**2 dz2 += und.dz**2 fluxsh = flux.reshape(sh) fluxMax = fluxsh.max(axis=0) l5 = ax2.scatter(Eh*1e-3, sigma2theta**0.5*1e6, s=fluxsh/fluxMax[np.newaxis, :]*50, facecolors='none', edgecolors='C0') l6 = ax2.scatter(Eh*1e-3, sigma2psi**0.5*1e6, s=fluxsh/fluxMax*50, facecolors='none', edgecolors='C1') leg3 = ax2.legend([(l5, l6)], [r'sampled by xrt'], handler_map={tuple: TwoScatterObjectsHandler()}, loc='lower right') l7 = ax1.scatter(Eh*1e-3, dx2**0.5*1e3, s=fluxsh/fluxMax[np.newaxis, :]*50, facecolors='none', edgecolors='C0') l8 = ax1.scatter(Eh*1e-3, dz2**0.5*1e3, s=fluxsh/fluxMax*50, facecolors='none', edgecolors='C1') leg4 = ax1.legend([(l7, l8)], [r'sampled by xrt'], handler_map={tuple: TwoScatterObjectsHandler()}, bbox_to_anchor=(1.0, 0.38)) # inset2 axS2 = fig2.add_axes([0.17, 0.16, 0.22, 0.3]) axS2.plot(E*1e-3, sPx*1e6, '-C0') axS2.plot(E*1e-3, sPz*1e6, '-C1') axS2.scatter(Eh*1e-3, sigma2theta**0.5*1e6, s=fluxsh/fluxMax[np.newaxis, :]*50, facecolors='none', edgecolors='C0') axS2.scatter(Eh*1e-3, sigma2psi**0.5*1e6, s=fluxsh/fluxMax*50, facecolors='none', edgecolors='C1') axS2.set_xlim(10-0.1, 10+0.06) axS2.set_ylim(8, 16) ax2.arrow(7, 6.5, 2.3, 2.8, head_width=0.3, head_length=0.75) # inset1 axS1 = fig1.add_axes([0.37, 0.36, 0.22, 0.3]) axS1.plot(E*1e-3, sz0*1e3, '--C1') axS1.plot(E*1e-3, sz*1e3, '-C1') axS1.scatter(Eh*1e-3, dx2**0.5*1e3, s=fluxsh/fluxMax[np.newaxis, :]*50, facecolors='none', edgecolors='C0') axS1.scatter(Eh*1e-3, dz2**0.5*1e3, s=fluxsh/fluxMax*50, facecolors='none', edgecolors='C1') axS1.set_xlim(10-0.1, 10+0.06) axS1.set_ylim(3, 10) ax1.arrow(8.5, 16., 1.1, -7.5, head_width=0.3, head_length=2.) fig1.savefig("undulatorLinearSize.png") fig2.savefig("undulatorAngularSize.png")
# -*- coding: utf-8 -*- # path to xrt: import os, sys sys.path.append(os.path.join('..', '..', '..')) # analysis:ignore import numpy as np import matplotlib.pyplot as plt import xrt.backends.raycing.sources as rs source = rs.Undulator(eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, betaX=9., betaZ=2., period=19.3, n=101, K=0.52, eEspread=0 * 1e-3, distE='BW') energy = np.linspace(1000, 31000, 1501) theta = np.linspace(-1, 1, 21) * 30e-6 psi = np.linspace(-1, 1, 21) * 30e-6 Ks = np.linspace(0.3, 2.2, 20) Kmax, gmin = 2.2, 4.2 gaps = np.log(Kmax / Ks) / np.pi * source.L0 + gmin harmonics = range(1, 17) powers = source.power_vs_K(energy, theta, psi, harmonics, Ks) plt.plot(gaps, powers, 'o-')
def main(): und = rs.Undulator( name='MAX IV U19', eE=3.0, eI=0.5, eEpsilonX=0.263, eEpsilonZ=0.008, betaX=9., betaZ=2., # """Compare with # Harry Westfahl Jr et al. J. Synchrotron Rad. (2017). 24, 566–575. # But notice their non-equidistant (in energy) harmonics.""" # name='Sirius U19', eE=3.0, eI=0.35, # eEpsilonX=0.245, eEpsilonZ=0.0024, # betaX=1.5, betaZ=1.5, period=19, n=105, targetE=(10000, 7), xPrimeMax=thetaMax * 1e3, zPrimeMax=psiMax * 1e3, xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, eEspread=1e-3, targetOpenCL='CPU', precisionOpenCL='float32') print(u"Electron beam linear sizes = {0:.3f} µm × {1:.3f} µm".format( und.dx * 1e3, und.dz * 1e3)) print(u"Electron beam angular sizes = {0:.3f} µrad × {1:.3f} µrad".format( und.dxprime * 1e6, und.dzprime * 1e6)) E = np.linspace(1400., 16000., 1460 + 1) sx0, sz0 = und.get_SIGMA(E, with0eSpread=True) sPx0, sPz0 = und.get_SIGMAP(E, with0eSpread=True) sx, sz = und.get_SIGMA(E) sPx, sPz = und.get_SIGMAP(E) fig1 = plt.figure(1) ax1 = fig1.add_subplot(111) ax1.set_title("{0} undulator: linear source size".format(und.name)) ax1.set_xlabel(u'energy (keV)') ax1.set_ylabel(u'rms linear source size (µm)') l1, = ax1.plot(E * 1e-3, sx0 * 1e3, '--C0') l2, = ax1.plot(E * 1e-3, sz0 * 1e3, '--C1') l3, = ax1.plot(E * 1e-3, sx * 1e3, '-C0') l4, = ax1.plot(E * 1e-3, sz * 1e3, '-C1') ax1.set_ylim(0, None) leg1 = ax1.legend([(l1, l3), (l2, l4)], [r"$\sigma_x$", r"$\sigma_y$"], handler_map={tuple: TwoLineObjectsHandler()}, loc=(0.86, 0.73)) leg2 = ax1.legend([(l1, l2), (l3, l4)], [r'$\sigma_E$ = 0', r'$\sigma_E$ = 0.1%'], handler_map={tuple: TwoLineObjectsHandler()}, title='at energy spread', loc=(0.73, 0.5)) ax1.add_artist(leg1) ax1.add_artist(leg2) fig2 = plt.figure(2) ax2 = fig2.add_subplot(111) ax2.set_title("{0} undulator: angular source size".format(und.name)) ax2.set_xlabel(u'energy (keV)') ax2.set_ylabel(u'rms angular source size (µrad)') ax2.plot(E * 1e-3, sPx0 * 1e6, '--C0') ax2.plot(E * 1e-3, sPz0 * 1e6, '--C1') ax2.plot(E * 1e-3, sPx * 1e6, '-C0') ax2.plot(E * 1e-3, sPz * 1e6, '-C1') ax2.set_ylim(0, None) leg1 = ax2.legend([(l1, l3), (l2, l4)], [r"$\sigma'_x$", r"$\sigma'_y$"], handler_map={tuple: TwoLineObjectsHandler()}, loc=(0.56, 0.83)) leg2 = ax2.legend([(l1, l2), (l3, l4)], [r'$\sigma_E$ = 0', r'$\sigma_E$ = 0.1%'], handler_map={tuple: TwoLineObjectsHandler()}, title='at energy spread', loc='upper right') ax2.add_artist(leg1) ax2.add_artist(leg2) if withXrtSampling: theta = np.linspace(-1, 1, 401) * thetaMax * 2 psi = np.linspace(-1, 1, 201) * psiMax * 2 Eh = (np.arange(1, 12, 2) * und.E1 + np.linspace(-14, 10, 13)[:, np.newaxis]) sh = Eh.shape Efine = np.linspace(10000 - 14., 10000 + 10., 1400 + 1) sx0fine, sz0fine = und.get_SIGMA(Efine, with0eSpread=True) sxfine, szfine = und.get_SIGMA(Efine) sPxfine, sPzfine = und.get_SIGMAP(Efine) und.eEspread = 0. print('please wait...') flux, sigma2theta, sigma2psi, dx2, dz2 = und.real_photon_source_sizes( Eh.ravel(), theta, psi, method=0.39) sigma2theta += und.dxprime**2 sigma2psi += und.dzprime**2 dx2 += und.dx**2 dz2 += und.dz**2 fluxsh = flux.reshape(sh) fluxMax = fluxsh.max(axis=0) l5 = ax2.scatter(Eh * 1e-3, sigma2theta**0.5 * 1e6, s=fluxsh / fluxMax[np.newaxis, :] * 50, facecolors='none', edgecolors='C0') l6 = ax2.scatter(Eh * 1e-3, sigma2psi**0.5 * 1e6, s=fluxsh / fluxMax * 50, facecolors='none', edgecolors='C1') l7 = ax1.scatter(Eh * 1e-3, dx2**0.5 * 1e3, s=fluxsh / fluxMax[np.newaxis, :] * 50, facecolors='none', edgecolors='C0') l8 = ax1.scatter(Eh * 1e-3, dz2**0.5 * 1e3, s=fluxsh / fluxMax * 50, facecolors='none', edgecolors='C1') if withCoisson: cE, cA2, cS2 = coisson(und.E1 * 7, und.L0 * und.Np, und.Np, 7) cXP = (und.dxprime**2 + cA2)**0.5 cZP = (und.dzprime**2 + cA2)**0.5 cX = (und.dx**2 + cS2)**0.5 cZ = (und.dz**2 + cS2)**0.5 # inset2 axS2 = fig2.add_axes([0.17, 0.17, 0.22, 0.3]) axS2.plot(Efine, sPxfine * 1e6, '-C0') axS2.plot(Efine, sPzfine * 1e6, '-C1') if withCoisson: l9 = axS2.scatter(cE, cXP * 1e6, marker='+', s=40, facecolors='C0', edgecolors='C0') l10 = axS2.scatter(cE, cZP * 1e6, marker='+', s=40, facecolors='C1', edgecolors='C1') axS2.scatter(Eh, sigma2theta**0.5 * 1e6, s=fluxsh / fluxMax[np.newaxis, :] * 50, facecolors='none', edgecolors='C0') axS2.scatter(Eh, sigma2psi**0.5 * 1e6, s=fluxsh / fluxMax * 50, facecolors='none', edgecolors='C1') axS2.set_xlim(10000 - 14, 10000 + 10) axS2.set_xticklabels(['', '-10 eV', r'$E_{\rm harm}$', '+10 eV'], minor=False) axS2.set_ylim(6, 14) ax2.arrow(6.3, 6.5, 3.0, 2.8, head_width=0.3, head_length=0.75) # inset1 axS1 = fig1.add_axes([0.35, 0.36, 0.22, 0.3]) axS1.plot(Efine, sz0fine * 1e3, '--C1') axS1.plot(Efine, szfine * 1e3, '-C1') if withCoisson: l11 = axS1.scatter(cE, cX * 1e3, marker='+', s=40, facecolors='C0', edgecolors='C0') l12 = axS1.scatter(cE, cZ * 1e3, marker='+', s=40, facecolors='C1', edgecolors='C1') axS1.scatter(Eh, dx2**0.5 * 1e3, s=fluxsh / fluxMax[np.newaxis, :] * 50, facecolors='none', edgecolors='C0') axS1.scatter(Eh, dz2**0.5 * 1e3, s=fluxsh / fluxMax * 50, facecolors='none', edgecolors='C1') axS1.set_xlim(10000 - 14, 10000 + 10) axS1.set_xticklabels(['', '-10 eV', r'$E_{\rm harm}$', '+10 eV'], minor=False) axS1.set_ylim(4.5, 6) ax1.arrow(8.5, 16., 1.1, -7.5, head_width=0.3, head_length=2.) lCur, lLab = [(l5, l6)], [r'xrt'] if withCoisson: lCur.append((l9, l10)) lLab.append('Coïsson, SPIE 88') leg3 = ax2.legend(lCur, lLab, title=r'sampled at $\sigma_E$ = 0 by:', handler_map={tuple: TwoScatterObjectsHandler()}, loc=(0.37, 0.03)) lCur, lLab = [(l7, l8)], [r'xrt'] if withCoisson: lCur.append((l11, l12)) lLab.append('Coïsson, SPIE 88') leg4 = ax1.legend(lCur, lLab, title=r'sampled at $\sigma_E$ = 0 by:', handler_map={tuple: TwoScatterObjectsHandler()}, loc=(0.66, 0.25)) fig1.savefig("undulatorLinearSize.png") fig2.savefig("undulatorAngularSize.png")
fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111) ax.set_xlabel(u'energy (keV)') apX = angleMaxX * 2 * 1e6 apZ = angleMaxZ * 2 * 1e6 ax.set_ylabel(u'flux through {0:.1f}×{1:.1f} µrad² (ph/s/0.1%bw)'.format( apX, apZ)) axplot = ax.semilogy if 'log-y' in plot else ax.plot # xrt Undulator kwargs = kwargsCommon.copy() kwargs.update(kwargsXRT) dtheta = theta[1] - theta[0] dpsi = psi[1] - psi[0] source = rs.Undulator(**kwargs) print('please wait...') I0x, l1, l2, l3 = source.intensities_on_mesh(energy, theta, psi) whereTheta = np.argwhere(abs(theta) <= angleMaxX) wherePsi = np.argwhere(abs(psi) <= angleMaxZ) fluxX = I0x[:, slice(whereTheta.min(), whereTheta.max()+1), slice(wherePsi.min(), wherePsi.max()+1)]\ .sum(axis=(1, 2)) * dtheta * dpsi axplot(energy * 1e-3, fluxX, label='xrt') # end xrt Undulator if case == 3: eS, fS = np.loadtxt("misc/bessy.dc0.gz", skiprows=2, usecols=(0, 1),
def build_beamline(azimuth=0): beamLine = raycing.BeamLine(azimuth=azimuth, height=0) beamLine.source = rs.Undulator(beamLine, 'Softi53', nrays=nrays, eE=3.0, eI=0.5, eEspread=0.0008 * energySpreadFactor, eEpsilonX=0.263 * emittanceFactor, eEpsilonZ=0.008 * emittanceFactor, betaX=9., betaZ=2., period=48., n=77, targetE=(E0, targetHarmonic), eMin=E0 - dE * vFactor, eMax=E0 + dE * vFactor, xPrimeMax=acceptanceHor / 2 * 1e3 * hShrink, zPrimeMax=acceptanceVer / 2 * 1e3 * vShrink, xPrimeMaxAutoReduce=False, zPrimeMaxAutoReduce=False, uniformRayDensity=True, filamentBeam=(what != 'rays'), targetOpenCL='auto') opening = [ -acceptanceHor * pFE / 2 * hShrink, acceptanceHor * pFE / 2 * hShrink, -acceptanceVer * pFE / 2 * vShrink, acceptanceVer * pFE / 2 * vShrink ] # opening = [-acceptanceHor*pFE/2*hShrink*hFactor, # acceptanceHor*pFE/2*hShrink*hFactor, # -acceptanceVer*pFE/2*vShrink, # acceptanceVer*pFE/2*vShrink] beamLine.slitFE = ra.RectangularAperture( beamLine, 'FE slit', kind=['left', 'right', 'bottom', 'top'], opening=opening) beamLine.fsm0 = rsc.Screen(beamLine, 'FSM-M1') xShrink = vShrink if what == 'wave' else 1 yShrink = hShrink if what == 'wave' else 1 beamLine.m1 = roe.ToroidMirror(beamLine, 'M1', surface=('Au', ), material=material, limPhysX=(-5 * xShrink, 5 * xShrink), limPhysY=(-150 * yShrink, 150 * yShrink), positionRoll=np.pi / 2, R=1e22, alarmLevel=0.1) # beamLine.fsm1 = rsc.Screen(beamLine, 'FSM-M1') xShrink = hShrink if what == 'wave' else 1 yShrink = vShrink if what == 'wave' else 1 beamLine.m2 = roe.OE(beamLine, 'M2', surface=('Au', ), material=material, limPhysX=(-5 * xShrink, 5 * xShrink), limPhysY=(-225 * yShrink, 225 * yShrink), alarmLevel=0.1) gratingKW = dict( positionRoll=np.pi, limPhysX=(-2 * xShrink, 2 * xShrink), #limPhysX=(-2*xShrink*hFactor, 2*xShrink*hFactor), limPhysY=(-40 * yShrink, 40 * yShrink), alarmLevel=0.1) if what == 'rays': beamLine.pg = Grating(beamLine, 'PlaneGrating', material=gratingMaterial, **gratingKW) beamLine.pg.material.efficiency = [(1, 0.4)] else: beamLine.pg = roe.BlazedGrating(beamLine, 'BlazedGrating', material=material, blaze=blaze, rho=rho, **gratingKW) beamLine.pg.order = 1 # beamLine.fsmPG = rsc.Screen(beamLine, 'FSM-PG') beamLine.m3 = roe.ToroidMirror( beamLine, 'M3', surface=('Au', ), material=material, positionRoll=-np.pi / 2, limPhysX=(-10. * vShrink, 10. * vShrink), limPhysY=(-100. * hShrink, 100. * hShrink), #limPhysY=(-100.*hShrink*hFactor, 100.*hShrink*hFactor), alarmLevel=0.1) beamLine.fsm3 = rsc.Screen(beamLine, 'FSM-M3') # beamLine.exitSlit = ra.RoundAperture( # beamLine, 'ExitSlit', r=ESradius, alarmLevel=None) beamLine.exitSlit = ra.RectangularAperture( beamLine, 'ExitSlit', # opening=[-ESdX*hFactor/2, ESdX*hFactor/2, # -ESdZ*vFactor/2, ESdZ*vFactor/2]) opening=[-ESdX / 2, ESdX / 2, -ESdZ / 2, ESdZ / 2]) beamLine.m4 = roe.EllipticalMirrorParam( beamLine, 'M4', surface=('Au', ), material=material, positionRoll=np.pi / 2, pitch=pitch, isCylindrical=True, p=43000., q=dM45 + pExp, limPhysX=(-0.5 * vShrink, 0.5 * vShrink), limPhysY=(-70. * hShrink, 70. * hShrink), #limPhysY=(-70.*hShrink*hFactor, 70.*hShrink*hFactor), alarmLevel=0.2) beamLine.fsm4 = rsc.Screen(beamLine, 'FSM-M4') beamLine.m5 = roe.EllipticalMirrorParam(beamLine, 'M5', surface=('Au', ), material=material, yaw=-2 * pitch, pitch=pitch, isCylindrical=True, p=dM4ES + dM45, q=pExp, limPhysX=(-0.5 * hShrink, 0.5 * hShrink), limPhysY=(-40. * vShrink, 40. * vShrink), alarmLevel=0.2) beamLine.fsm5 = rsc.Screen(beamLine, 'FSM-M5') beamLine.fsmExp = rsc.Screen(beamLine, 'FSM-Exp') beamLine.waveOnSampleA = [np.zeros(abins) for sP in dFocus] beamLine.waveOnSampleB = [np.zeros(abins) for sP in dFocus] beamLine.waveOnSampleC = [np.zeros(abins) for sP in dFocus] return beamLine
def main(): und = rs.Undulator(**kw) for harmonic in harmonics: Eh = harmonic * und.E1 # Eh = Eh * (1 - 1./harmonic/und.Np) # detuned to harmonic's maximum und.eMin = Eh * (1 - bw / 2) und.eMax = Eh * (1 + bw / 2) und.reset() energy = np.ones(repeats) * Eh st = 'st' if harmonic == 1 else 'nd' if harmonic == 2 else 'rd'\ if harmonic == 3 else 'th' for energySpread in energySpreads: und.eEspread = energySpread for emittancex in emittances: if energySpread > 1e-12: ses = '{0:.1e}'.format(energySpread) ses = ses[:-2] + ses[-1] # removes "0" from power else: ses = '0' txt = '{0}{1} harmonic ({2:.0f} eV){5}{3} energy spread{5}' +\ '$\\epsilon_x$ = {4:.0f} pmrad' cap = txt.format(harmonic, st, Eh, ses, emittancex, ', ') baseName = 'h{0:02d}-esp{1}-em{2:04.0f}'.format( harmonic, energySpread, emittancex) emittancez = 10 if emittancex > 1e-12 else 0 und.dx = np.sqrt(emittancex * betaX) * 1e-3 # in mm und.dz = np.sqrt(emittancez * betaZ) * 1e-3 # in mm und.dxprime = \ emittancex*1e-9 / und.dx if und.dx > 0 else 0. # rad und.dzprime = \ emittancez*1e-9 / und.dz if und.dz > 0 else 0. # rad Es, Ep = und.multi_electron_stack(energy, theta, psi) print("Es.shape", Es.shape) k = binsx * binsz D = np.array(Es).reshape((repeats, k), order='F').T J = np.dot(D, D.T.conjugate()) # / repeats print("solving eigenvalue problem...") start = time.time() dotc4 = rco.calc_degree_of_transverse_coherence_4D(J) # print('dotc4', dotc4) wN, vN = rco.calc_eigen_modes_4D(J, eigenN=4) stop = time.time() print( "the eigenvalue problem has taken {0:.4} s".format(stop - start)) print("vN.shape", vN.shape) print("Top 4 eigen values (4D) = {0}".format(wN)) figE4 = rco.plot_eigen_modes(theta * p, psi * p, wN, vN, xlabel='x (mm)', ylabel='z (mm)') figE4.axes[0].xaxis.set_ticklabels([]) figE4.axes[1].xaxis.set_ticklabels([]) figE4.suptitle('Eigen modes of mutual intensity,\n' + cap, fontsize=11) plt.text(0.05, 0.05, 'DoTC={0:.3f}'.format(dotc4), transform=figE4.axes[0].transAxes, ha='left', va='bottom', color='w', size=10) figE4.savefig('Modes-{0}-{1}.png'.format('s', baseName)) print("solving PCA problem...") start = time.time() dotcP = rco.calc_degree_of_transverse_coherence_PCA(Es) # print('dotcP', dotcP) wPCA, vPCA = rco.calc_eigen_modes_PCA(Es, eigenN=4) stop = time.time() print("the PCA problem has taken {0:.4} s".format(stop - start)) print("vPCA.shape", vPCA.shape) print("Top 4 eigen values (PCA) = {0}".format(wPCA)) figEP = rco.plot_eigen_modes(theta * p, psi * p, wPCA, vPCA, xlabel='x (mm)', ylabel='z (mm)') figEP.axes[0].xaxis.set_ticklabels([]) figEP.axes[1].xaxis.set_ticklabels([]) figEP.suptitle( 'Principal components of one-electron images,\n' + cap, fontsize=11) plt.text(0.05, 0.05, 'DoTC={0:.3f}'.format(dotcP), transform=figEP.axes[0].transAxes, ha='left', va='bottom', color='w', size=10) figEP.savefig('Components-{0}-{1}.png'.format('s', baseName)) xdata = rco.calc_1D_coherent_fraction(Es, 'x', theta * p, p) ydata = rco.calc_1D_coherent_fraction(Es, 'z', psi * p, p) fig2D1, figXZ = rco.plot_1D_degree_of_coherence( xdata, 'x', theta * p) fig2D2, figXZ = rco.plot_1D_degree_of_coherence(ydata, 'z', psi * p, fig2=figXZ) fig2D1.suptitle('Mutual intensity for horizontal cut,\n ' + cap, size=11) fig2D2.suptitle('Mutual intensity for vertical cut,\n ' + cap, size=11) figXZ.suptitle('Intensity and Degree of Coherence,\n ' + cap, size=11) fig2D1.savefig('MutualI-x-{0}-{1}.png'.format('s', baseName)) fig2D2.savefig('MutualI-z-{0}-{1}.png'.format('s', baseName)) figXZ.savefig('DOC-{0}-{1}.png'.format('s', baseName)) plt.show()