def loadPulse(wdir): wfr = Wavefront() wfr.load_hdf5(wdir) wfr.initial_intensity = integral_intensity(wfr, bPlot = False) return wfr
def propagate(wfr_directory, sdir, focus, analysis = False, crop = [], append = None, descriptor = "", VERBOSE = True): print("info") print("wavefront directory: {}".format(wfr_directory)) print("save directory: {}".format(sdir)) print("focus (i.e. beamline option): {}".format(focus)) print("analysis: {}".format(analysis)) print("crop: {}".format(crop)) print("append: {}".format(append)) for item in descriptor: print(item) wfr = Wavefront() wfr.load_hdf5(wdir) sdir = sdir + "/{}/".format(focus) bl = get_beamline_object(ekev = 4.96, options = focus, crop = crop) if append is not None: for item in append: bl.append(item[0],item[1]) wfr.log(bl, descriptor) bl.propagate(wfr) if analysis: wfr.analysis() wfr.store_hdf5(sdir)
def testStorage(indir, fname, N=25): for n in range(N): wfr = Wavefront() wfr.load_hdf5(indir + fname) print(wfr.custom_fields['source'])
def superimpose(fname, params): """ function to add wavefronts """ ### TODO: FIX HARDCODING OF FILENAMES ETC. memMap = readMap(params['global'] + params['train'], shape=params['train_shape']) wfr = Wavefront() wfr.load_hdf5(params['indir'] + fname) memMap += wfr.data.arrEhor
def generatePulse(n = 1): wfr = Wavefront(build_gauss_wavefront(nx = 512, ny = 512, nz = 5, ekev = 4.96, xMin = -400e-06, xMax = 400e-06, yMin = -400e-06, yMax = 400e-06, tau = 1e-05, sigX = np.random.random()*125e-06, sigY = np.random.random()*125e-06, d2waist = 1)) wfr.store_hdf5("../../data/tests/pulseTests/gaussianSource/gsn_{}.h5".format(n))
def construct_gaussian(nx, ny, ekev, extent, sigX, sigY, divergence, xoff = 0, yoff = 0, tau = 1, mx = 0, my = 0, tiltX = 0, tiltY = 0): gsnBm = build_gaussian(nx, ny, ekev, xMin = extent[0], xMax = extent[1], yMin = extent[2], yMax = extent[3], sigX = sigX, sigY = sigY, d2waist = 1, xoff = xoff, yoff = yoff, pulseTau = tau, _mx = mx, _my = my, tiltX= tiltX, tiltY = tiltY) wfr = Wavefront(gsnBm) wfr.params.wavelength = ekev2wav(ekev) modify_beam_divergence(wfr,sigX, divergence) return wfr
def trainAnalysis(): params = setup(VERBOSE=False) ID = 0 ## get multipulse profiles getTrain(params['indir'], params=params, mpi=True, nProc=params['nProc']) print("Pulse Train Succesfully Added") ## load relevant train memmap tsi = readMap(params['global'] + params['tsi'], shape=params['tsi_shape']) tss = readMap(params['global'] + params['tss'], shape=params['tss_shape']) tcoh = readMap(params['global'] + params['tcoh'], shape=params['tcoh_shape']) tesi = readMap(params['global'] + params['tesi'], shape=params['tesi_shape']) tesp = readMap(params['global'] + params['tesp'], shape=params['tesp_shape']) tcni = readMap(params['global'] + params['tcni'], shape=params['tcni_shape']) tcnp = readMap(params['global'] + params['tcnp'], shape=params['tcnp_shape']) ## load multipulse for analysis prior to launch tfr = Wavefront() tfr.load_hdf5(params['traindir'] + params['trainwfr']) pulseEnergy(tfr, tesi, ID, mode='integrated') pulseEnergy(tfr, tesp, ID, mode='pulse') print("Train Energy Calculated") centroid(tfr, tcni, ID, mode='integrated') centroid(tfr, tcnp, ID, mode='pulse') print("Train Centrod Calculated") BeamSize(tfr, mode='integrated', memMap=tsi, ID=0) BeamSize(tfr, mode='pulse', memMap=tss, ID=0) print("Train Beam Size Calculated") Coherence(tfr, tcoh, ID=0, VERBOSE=True) print("Train Coherence Calculated") del tsi, tss, tcoh, tesi, tesp, tcni, tcnp
def getIntensity(fname): wfr = Wavefront() wfr.load_hdf5(indir + fname) np.save(outdir1 + fname, wfr.get_intensity()) np.save(outdir2 + fname, wfr.as_complex_array()[0, :, :, :])
def construct_SA1_pulse(nx, ny, nz, ekev, q, mx = 0, my = 0): """ Construct a fully-coherent Gaussian source with properties related to the energy of the radiation and beam charge. Important points: pulseTau (coherence length) is set to tau (pulse length) in the fully coherent case :param nx: number of horizontal pixels [int] :param ny: number of vertical pixels [int] :param nz: number of slices [int] :param ekev: radiation energy [keV] :param q: electron beam bunch charge [nC] :param xoff: horizontal offset of beam maximum [m] :param yoff: vertical offset of beam maximum [m] :param modify_beam_divergenceergence: Choose to set non-diffraction limited div [bool] """ wavelength = (h*c)/(ekev*1e3) xMin, xMax = -400e-06, 400e-06 #based on fwhm of 1 nC, 3 keV beam yMin, yMax = -400e-06, 400e-06 #based on fwhm of 1 nC, 3 keV beam sigX, sigY = analytical_pulse_width(ekev)/fwhm2rms, analytical_pulse_width(ekev)/fwhm2rms pulseEn = analytical_pulse_energy(q, ekev) dtheta = analytical_pulse_divergence(q, ekev) tau = analytical_pulse_duration(q) gsnBm = build_gaussian_3D(nx = nx, ny = ny, nz = nz, ekev = ekev, xMin = xMin, xMax = xMax, yMin = yMin, yMax = yMax, sigX = sigX, sigY = sigY, d2waist = 1, tau = tau, pulseRange = 1, pulseEn = 2*pulseEn, _mx = mx, _my = my) wfr = Wavefront(gsnBm) srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') wfr.params.wavelength = wavelength #modify_beam_divergence(wfr,analytical_pulse_width(ekev),analytical_pulse_divergence(q,ekev)) modify_beam_energy(wfr, desired = 2*pulseEn) return wfr
def propagatePulses(indir, fname, outdir): wfr = Wavefront() wfr.load_hdf5(indir + fname) srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') storeWavefrontInfo(wfr) bl = getSimpleBl() bl.propagate(wfr) wfr.store_hdf5(outdir + fname)
def construct_SA1_wavefront(nx, ny, ekev, q, xoff = 0, yoff = 0, mx = 0, my = 0, tiltX = 0, tiltY = 0, xMin = -400e-06, xMax = 400e-06, yMin = -400e-06, yMax = 400e-06): """ Construct a fully-coherent Gaussian source with properties related to the energy of the radiation and beam charge. Important points: pulseTau (coherence length) is set to tau (pulse length) in the fully coherent case :param nx: number of horizontal pixels [int] :param ny: number of vertical pixels [int] :param nz: number of slices [int] :param ekev: radiation energy [keV] :param q: electron beam bunch charge [nC] :param xoff: horizontal offset of beam maximum [m] :param yoff: vertical offset of beam maximum [m] :param modify_beam_divergenceergence: Choose to set non-diffraction limited div [bool] """ wavelength = (h*c)/(ekev*1e3) sigX, sigY = analytical_pulse_width(ekev)/fwhm2rms, analytical_pulse_width(ekev)/fwhm2rms pulseEn = analytical_pulse_energy(q, ekev) dtheta = analytical_pulse_divergence(q, ekev) tau = analytical_pulse_duration(q) gsnBm = build_gaussian(nx, ny, ekev, xMin, xMax, yMin, yMax, sigX, sigY, 1, xoff = xoff, yoff = yoff, pulseTau = tau, _mx = mx, _my = my, tiltX= tiltX, tiltY = tiltY) wfr = Wavefront(gsnBm) wfr.params.wavelength = wavelength srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') modify_beam_divergence(wfr,sigX, analytical_pulse_divergence(q,ekev)) ## note 300 is hardcoded fix, should not stay past tue 13/01/21 return wfr
def propagatePulses(fname): wfr = Wavefront() wfr.load_hdf5(indir + fname) srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') #storeWavefrontInfo(wfr) bl = getSPB(wfr) #bl = getSimpleBl() bl.propagate_sequential(wfr) wfr.store_hdf5(outdir + fname) plotIntensity(wfr)
def wavefront_from_array(cfr,nx,ny,nz,dx,dy,dz,ekev, pulse_duration = 40e-15, sigma = 4): # Initialize empty wavefront. wfr = Wavefront() # Setup E-field. wfr.data.arrEhor = np.zeros(shape=(nx, ny, nz, 2)) wfr.data.arrEver = np.zeros(shape=(nx, ny, nz, 2)) wfr.params.wEFieldUnit = 'sqrt(W/mm^2)' wfr.params.photonEnergy = ekev * 1000 wfr.params.wDomain = 'time' wfr.params.Mesh.nSlices = nz wfr.params.Mesh.nx = nx wfr.params.Mesh.ny = ny wfr.params.Mesh.sliceMin = -pulse_duration*sigma / 2. wfr.params.Mesh.sliceMax = pulse_duration*sigma / 2. range_x = dx*nx range_y = dy*ny wfr.params.Mesh.xMin = -range_x / 2. wfr.params.Mesh.xMax = range_x / 2. wfr.params.Mesh.yMin = -range_y / 2. wfr.params.Mesh.yMax = range_y / 2. wfr.data.arrEhor = complex_to_wpg(cfr) #wfr.set_electric_field_representation('f') return wfr
def getTrain(indir, params, mpi=True, nProc=1): """ wrapper function linear addition of a set of wavefronts parsed through from some input directory """ ### TODO: FIX HARDCODING OF FILENAMES ETC. from functools import partial if mpi: p = partial(superimpose, params=params) pool = Pool(processes=nProc) pool.map(p, iterable=os.listdir(indir)) wfr = Wavefront() wfr.load_hdf5(params['indir'] + os.listdir(params['indir'])[ np.random.randint(0, len(os.listdir(params['indir'])))]) wfr.data.arrEhor = readMap(params['global'] + params['train'], shape=params['train_shape']) wfr.store_hdf5(params['traindir'] + params['trainwfr'])
bl.propagate(wfr) Ps = wfr.get_phase(slice_number=0) # Is = wfr.get_intensity(slice_number=0) ekev = wfr.params.photonEnergy z1 = 1 z2 = 1 pix_size = wfr.get_spatial_resolution()[0] delta = 1 beta = 1 bg_val = 1 scale = 1 ####################################### wfr = Wavefront() wfr.load_hdf5("coherentSrc.h5") bl = Beamline() bl.append(Drift(2), propagation_parameters(1, 1, 1, 1, mode='normal')) bl.propagate(wfr) Pr = wfr.get_phase(slice_number=0) #% np.pi*2 Ir = wfr.get_intensity(slice_number=0) for I in [Ir, Is]: I[np.where(I == 0)] = 1e-10 results = tiePavlov(Is, Ir, ekev, z1, z2, pix_size, delta, beta, bg_val, scale) % np.pi * 2
def testGeneratedPulses(indir, fname, n): wfr = Wavefront() wfr.load_hdf5(indir + fname + "_{}.h5".format(n))
def load_wfr(indir): wfr = Wavefront() wfr.load_hdf5(indir) return wfr
def wavefront_from_array(cfr, nx, ny, nz, dx, dy, dz, ekev, pulse_duration=40e-15, sigma=4, **kwargs): """ function to produce a wpg wavefront object instance from a complex valued wavefront definition :param cfr: complex valued wavefield array [x,y,t] (complex128) :param nx: number of pixels along x-axis :param ny: number of pixels along y-axis :param nz: number of pixels along z-axis :param dx: pixels size along x-axis :param dy: pixels size along y-axis :param dz: pixels size along z-axis :param ekev: energy in kev :param pulse_duration: duration of the pulse (fwhm) in seconds, defaults to 40e-15 :param sigma: integer number of width multiples over which time-axis should be defined, defaults to 4 :returns: DESCRIPTION """ # Initialize empty wavefront. wfr = Wavefront() # Setup E-field. wfr.data.arrEhor = np.zeros(shape=(nx, ny, nz, 2)) wfr.data.arrEver = np.zeros(shape=(nx, ny, nz, 2)) wfr.params.wEFieldUnit = 'sqrt(W/mm^2)' wfr.params.photonEnergy = ekev * 1000 wfr.params.wDomain = 'time' wfr.params.Mesh.nSlices = nz wfr.params.Mesh.nx = nx wfr.params.Mesh.ny = ny wfr.params.Mesh.sliceMin = -pulse_duration * sigma / 2. wfr.params.Mesh.sliceMax = pulse_duration * sigma / 2. range_x = dx * nx range_y = dy * ny wfr.params.Mesh.xMin = -range_x / 2. wfr.params.Mesh.xMax = range_x / 2. wfr.params.Mesh.yMin = -range_y / 2. wfr.params.Mesh.yMax = range_y / 2. wfr.params.Rx = 2 wfr.params.Ry = 1 wfr.data.arrEhor = complex_to_wpg(cfr) wfr.set_electric_field_representation('f') wfr.custom_fields.update(**kwargs) return wfr
def constructPulse(): wfr = Wavefront(build_gauss_wavefront(512, 512, 10, 5.0, -400e-06, 400e-06, -400e-06, 400e-06, 1e-15, 5e-06, 5e-06, 19)) srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') #look_at_q_space(wfr) return wfr
srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') #look_at_q_space(wfr) return wfr def simpleProp(wfr): print(calculate_fwhm(wfr)) bl = Beamline() #bl.append(Aperture('c','a', 500e-06),propagation_parameters(1,1,1,1,mode = 'normal')) bl.append(Drift(100), propagation_parameters(1,1,1,1,mode = 'quadratic')) #bl.append(Drift(100), propagation_parameters(1,1,1,1,mode = 'quadratic')) bl.propagate(wfr) plotIntensity(wfr) print(calculate_fwhm(wfr)) if __name__ == "__main__": #wfr = constructPulse() wfr = Wavefront() wfr.load_hdf5("../../data/h5/gauss.h5") srwlib.srwl.SetRepresElecField(wfr._srwl_wf, 'f') plotIntensity(wfr) simpleProp(wfr) #comparePulses(wfr, cwfr, "/data/")
__maintainer__ = "Trey Guest" __email__ = "*****@*****.**" __status__ = "Developement" """ import os, shutil from os.path import exists import json import numpy as np import h5py from matplotlib import pyplot as plt import matplotlib as mpl from wpg.wpg_uti_wf import integral_intensity import h5py from felpy.model.wavefront import Wavefront from wpg.wpg_uti_wf import animate, plot_axial_power_density, plot_total_power filename = "../../data/test_h5/XFEL_S1_04.96keV_12.0GeV_0020pC_SASE_U_BLI_2014-05-01_FAST_FXY1_0002020.h5" wfr = Wavefront() wfr.load_hdf5(filename) #animate(wfr, delay = 2, outdir = "../../tmp") plot_axial_power_density(wfr, spectrum=False, outdir="../../tmp") plot_axial_power_density(wfr, spectrum=True, outdir="../../tmp") plot_total_power(wfr, spectrum=False, outdir="../../tmp") plot_total_power(wfr, spectrum=True, outdir="../../tmp") print(integral_intensity(wfr))
def propagate_NVE(): wfr_directory = sys.argv[1].replace("*", "/") job_name = "NKB_4980eV_250pC_NVE_to_EHC" python_command = propagate_NVE input_directory = dCache + "/NanoKB-Pulse/NVE/" save_directory = input_directory.replace("/NVE/", "/EHC/") mkdir_p(save_directory) log_directory = logs focus = "nano" analysis = False filename = __file__ dt = datetime.now().__str__() function = python_command.__name__ description = "Propagate NanoKB Pulses 4.98 keV, 250 pC from Undulator NVE mirror to the EHC Screen" append = None print("info") print("wavefront directory: {}".format(wfr_directory)) print("save directory: {}".format(save_directory)) print("focus (i.e. beamline option): {}".format(focus)) print("analysis: {}".format(analysis)) print("datetime: {}".format(dt)) print("filename: {}".format(filename)) print("function: {}".format(function)) print("description: {}".format(description)) wfr = Wavefront() wfr.load_hdf5(wfr_directory) bl = Beamline() bl.append(Drift(2.2+3.5), propagation_parameters(1/3,1,1/3,1,'quadratic')) bl.propagate(wfr) wfr.custom_fields['focus'] = focus wfr.custom_fields['job name'] = job_name wfr.custom_fields['input directory'] = wfr_directory wfr.custom_fields['datetime'] = dt wfr.custom_fields['function'] = function wfr.custom_fields['filename'] = filename wfr.custom_fields['description'] = description #wfr.custom_fields['bl'] = bl.__str__ if analysis: wfr.analysis() wfr.store_hdf5(wfr_directory.replace("/NVE/", "/EHC/"))
from .examples.NFS.speckle import define_speckle_mask from felpy.analysis.statistics.correlation import norm from PIL import Image ekev = 25 wav = ekev2wav(25) k = np.pi * 2 / wav delta = 4e-07 d2waist = (wav) / (np.arctan(.27 / 8) * np.pi) r = 75e-03 wfr = Wavefront( construct_gaussian(1024, 1024, 25, -15e-02, 15e-02, -15e-02, 15e-02, 3e-2, 3e-02, d2waist)) ### PLOT 1 plot_intensity_map(wfr) bl = Beamline() bl.append(Drift(1), propagation_parameters(1, 1, 1, 1)) bl.propagate(wfr) x = np.linspace(wfr.params.Mesh.xMin, wfr.params.Mesh.xMax, wfr.params.Mesh.nx) y = np.ones([wfr.params.Mesh.nx, wfr.params.Mesh.ny]) thickness = norm(cylinder_thickness(x, r, offset=0), lim=(0, 255))
print("Job ID ", ID) params = setup(VERBOSE=True) bsi = readMap(params['global'] + params['bsi'], shape=params['bsi_shape']) bss = readMap(params['global'] + params['bss'], shape=params['bss_shape']) coh = readMap(params['global'] + params['coh'], shape=params['coh_shape']) esi = readMap(params['global'] + params['esi'], shape=params['esi_shape']) esp = readMap(params['global'] + params['esp'], shape=params['esp_shape']) cni = readMap(params['global'] + params['cni'], shape=params['cni_shape']) cnp = readMap(params['global'] + params['cnp'], shape=params['cnp_shape']) fname = os.listdir(params['indir'])[ID] print("loading wavefront: {}".format(fname)) wfr = Wavefront() wfr.load_hdf5(params['indir'] + fname) pulseEnergy(wfr, esi, ID, mode='integrated') pulseEnergy(wfr, esp, ID, mode='pulse') print("Pulse Energy Calculated") centroid(wfr, cni, ID, mode='integrated') centroid(wfr, cnp, ID, mode='pulse') print("Pulse Centroid Calculated") ### integrated beam profile print("Calculating Integrated Beam Profiles") BeamSize(wfr, mode="integrated", memMap=bsi, ID=ID) print("Integrated Beam Profiles Calculated") ### pulsed beam profile print("calculating pulsed beam profiles") BeamSize(wfr, mode="pulse", memMap=bss, ID=ID, VERBOSE=True)
def test(): wfr = constructPulse(nz=10) zc = fitZernicke(wfr) return zc if __name__ == '__main__': #ph, zc = test() mode = 'integrated' where = 'in' ## source or sample fname = sys.argv[1] outdir = "/gpfs/exfel/data/group/spb-sfx/user/guestt/h5/NanoKB-Pulse/data/zernike/" savdir = outdir + mode + "/" mkdir_p(outdir) mkdir_p(savdir) wfr = Wavefront() wfr.load_hdf5( "/gpfs/exfel/data/group/spb-sfx/user/guestt/h5/NanoKB-Pulse/{}/{}". format(where, fname)) zc = fitZernicke(wfr, mode=mode, nterms=1250) np.save(savdir + fname, zc)
# -*- coding: utf-8 -*- import sys from felpy.model.wavefront import Wavefront from felpy.model.beamline import Beamline from wpg.optical_elements import Drift from felpy.model.tools import propagation_parameters from felpy.utils.os_utils import mkdir_p if __name__ == '__main__': print("working") in_directory = sys.argv[1] print("in: ", in_directory) out_directory = sys.argv[2] print("out: ", out_directory) wfr = Wavefront() wfr.load_hdf5(in_directory) print("wfr loaded") bl = Beamline() bl.append(Drift(3.644 - 2.2), propagation_parameters(1, 1, 1, 1, 'quadratic')) bl.propagate(wfr) print("wfr propagated") wfr.store_hdf5(out_directory) print("wfr stored") wfr.analysis(VERBOSE=True, DEBUG=True) #print(wfr.custom_fields) ## good debug
def propagate_NVE(): wfr_directory = sys.argv[1].replace("*", "/") job_name = "NKB_4980eV_250pC_Source_to_NVE" python_command = propagate_NVE input_directory = dCache + "/NanoKB-Pulse/source/" save_directory = input_directory.replace("/source/", "/NVE/") mkdir_p(save_directory) log_directory = logs focus = "nano" analysis = False filename = __file__ dt = datetime.now().__str__() function = python_command.__name__ description = "Propagate NanoKB Pulses 4.98 keV, 250 pC from Undulator-exit to the NVE" crop = 'NVE' append = None print("info") print("wavefront directory: {}".format(wfr_directory)) print("save directory: {}".format(save_directory)) print("focus (i.e. beamline option): {}".format(focus)) print("analysis: {}".format(analysis)) print("datetime: {}".format(dt)) print("filename: {}".format(filename)) print("function: {}".format(function)) print("description: {}".format(description)) wfr = Wavefront() wfr.load_hdf5(wfr_directory) wfr.set_electric_field_representation('frequency') wfr = scale(wfr) print("wfr domain: {}".format(wfr.params.wDomain)) bl = get_beamline_object(ekev=4.96, options=focus, crop=crop, theta_KB=5e-03, theta_HOM=3.5e-03) wfr.custom_fields['focus'] = focus wfr.custom_fields['job name'] = job_name wfr.custom_fields['input directory'] = wfr_directory wfr.custom_fields['datetime'] = dt wfr.custom_fields['function'] = function.__str__() wfr.custom_fields['filename'] = filename wfr.custom_fields['description'] = description #wfr.custom_fields['bl'] = bl.__str__ bl.propagate(wfr) if analysis: wfr.analysis() wfr.store_hdf5(wfr_directory.replace("/source/", "/NVE/"))
src = SA1_Source([5], [0.2], mesh=m, theta_x=theta_x) src.generator("../data/tmp/test") try: src.store_hdf5("../data/tmp/source.h5") except (KeyError): os.remove("../data/tmp/source.h5") src.store_hdf5("../data/tmp/source.h5") src = Source() src.load_hdf5("../data/tmp/source.h5") from felpy.model.wavefront import Wavefront from wpg.wpg_uti_wf import plot_intensity_map wfr = Wavefront() from felpy.model.beamline import Beamline from wpg.optical_elements import Drift from felpy.model.tools import propagation_parameters from matplotlib import pyplot as plt bl = Beamline() bl.append(Drift(50), propagation_parameters(1, 1, 1, 1, mode='fresnel')) for w in src.pulses: wfr.load_hdf5(w) bl.propagate(wfr) plt.plot(wfr.x_axis, wfr.get_x_profile(),
def loadWavefront(fname): wfr = Wavefront() wfr.load_hdf5(indir + fname) return wfr