예제 #1
0
def sseed_2(input_file,
            output_files,
            E_ev,
            chicane,
            run_dir,
            delay=0.0,
            debug=True,
            output_file=None,
            xt_couple=False,
            filterfilename='',
            method='hxr_wake_calc',
            paral=False):

    h = 4.135667516e-15
    c = 299792458.0

    g = readGenesisOutput(input_file, readall=0)
    print 'read sliced field ', g('ncar'), g.nSlices
    ncar = int(g('ncar'))
    dgrid = float(g('dgrid'))
    xlamds = float(g('xlamds'))
    #nslice = len(g.spec)
    nslice = int(g.nSlices)
    print 'nslice = ', nslice
    zsep = float(g('zsep'))
    print zsep

    k0 = 2 * np.pi / xlamds
    ds = zsep * xlamds  #interval ds
    srange = nslice * zsep * xlamds  #range in s

    dkold = 2 * np.pi / srange
    krange = dkold * nslice
    #idx_max = np.argmax(g.I)
    #s_imax = -srange/2.0 + idx_max*ds

    #SHF = np.int((delay-s_imax)/ds)

    SHF = int(delay)  #np.int(delay/ds) #or divided ds

    #print 'imax = ', idx_imax
    #print 'delay = ', delay
    #print 'delay-s_imax', delay-s_imax
    #print 'SHF*ds', SHF*ds

    #SHF = np.int((-0.5e-5+s_imax)/ds)
    ####SHF = np.int((delay)/ds)
    #print np.int((delay+s_imax)/ds)*ds
    #print 'due=', SHF*ds
    #exit()

    #g.idx_max = idx_max
    #print 'ss idx_max:', g.idx_max

    if method == 'hxr_wake_calc':

        r = Ray()
        r.lamb = 2 * pi * hbar * c / E_ev
        print 'wavelength', r.lamb, '(', E_ev, 'eV), filetring...'

        ref_idx = chicane.cryst.ref_idx
        filt = get_crystal_filter(chicane.cryst, r, nk=1000, ref_idx=ref_idx)

        chicane.cryst.filter = filt

        klpos, krpos, cwidth = FWHM(filt.k, 1.0 - np.abs(filt.tr))
        cmid_idx = int((krpos - klpos) / 2.0)
        cmid = filt.k[cmid_idx]

        H, d, phi = find_bragg(lambd=r.lamb,
                               lattice=chicane.cryst.lattice,
                               ord_max=15)
        dhkl = d[ref_idx]
        thetaB = phi[ref_idx] * np.pi / 180.0

        dk = cwidth / 6.0  #The filter transmissivity defines this quantity by taking 5 points on the bottom of T; if not good separation, must tune!!!
        dr = ncar / (
            dgrid * np.tan(thetaB)
        )  #dr prepares for inclusion of the spatiotemporal coupling; it is transverse pix size/cot(thetaB)
        #dr=1.0
        print '#################'
        print 'dgrid = ', dgrid
        print 'ncar = ', ncar
        print 'dr = ', dr
        print 'thetaB = ', thetaB
        print 'ds = ', ds
        print 'SHF = ', SHF
        print '#################'

        mult = np.int(dkold / dk)

        if int(mult / 2) - mult / 2 == 0: mult = mult - 1
        if mult == 0: mult = 1
        print 'MULT = ', mult
        dk = dkold / mult  #Important! Otherwise the np.int in the line changes the k scale substantially

        phases = unfold_angles(np.angle(np.conj(filt.tr)))

        f1 = open(output_files[1], 'w')
        f2 = open(output_files[2], 'w')

        for i in range(len(filt.k)):
            f1.write('%s ' % (filt.k[i]) + '%s' % np.abs(filt.tr[i]) + '\n')
            f2.write('%s ' % (filt.k[i]) + '%s' % phases[i] + '\n')

        f1.close()
        f2.close()

    if method == 'sxr_filter_read':
        # f = open(filterfilename, 'r')
        #[abs, dlpl]
        # import numpy as np
        # from math import pi
        #        E_ev=1000.
        #icf_path='d:\Work\!PROJECTS\ocelot_test\ICF_1000.ascii'
        f = open(filterfilename, 'r')
        data = np.genfromtxt(f, delimiter=',')
        #delete(data,0,0) # Erases the first row (i.e. the header)
        #plot(data[:,0],data[:,1],'o')
        f.close()

        dlpl = np.flipud(data[:, 0])
        Tmod = np.flipud(data[:, 1])

        Tpha = np.zeros(len(data[:, 0]))
        lambda_0 = 1239.8 / E_ev * 1e-9
        k = 2 * pi / (lambda_0 + lambda_0 * dlpl)
        dk_f = k[0] - k[1]
        k = np.concatenate(([k[0] + dk_f], k, [k[-1] - dk_f]))
        Tmod = np.concatenate(([0], Tmod, [0]))
        Tpha = np.concatenate(([0], Tpha, [0]))
        # Tmod=np.insert(Tmod,slice(0),0)
        # Tmod=np.insert(Tmod,slice(-1),0)
        # Tpha=np.insert(Tmod,slice(0),0)
        # Tpha=np.insert(Tmod,slice(-1),0)
        # Tmod=np.insert(Tmod,slice(0,-1),[0,0])
        # Tpha=np.insert(Tpha,slice(0,-1),[0,0])#padding with zeros on edges, so that interpolation was done with zeros as well
        print np.column_stack((k, Tmod))
        #f = open(res_dir+'s2.Tmod.dat', 'w')
        #    writepath_Tmod='d:\Work\!PROJECTS\ocelot_test\s2.Tmod.dat'
        #    writepath_Tpha='d:\Work\!PROJECTS\ocelot_test\s2.Tpha.dat'
        np.savetxt(output_files[1], np.column_stack((k, Tmod)))
        np.savetxt(output_files[2], np.column_stack((k, Tpha)))

        klpos, krpos, cwidth = FWHM(k, Tmod)
        cwidth = abs(cwidth)
        print 'CWIDTH=', cwidth
        dk = cwidth / 10.0
        mult = np.int(dkold / dk)

        #if int(mult/2) - mult/2 ==0: mult = mult-1 %probably it needs to be even

        print 'MULT = ', mult
        dk = dkold / mult  #Important! Otherwise the np.int in the line changes the k scale substantially

        # bring to common format !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        dr = 0

        # phases = unfold_angles(np.angle(np.conj(filt.tr)))

    if paral == True:
        ARGS = ''.join([
            input_file + '.dfl' + ' ', output_files[0] + ' ',
            output_files[1] + ' ', output_files[2] + ' ',
            output_files[3] + ' ', output_files[4] + ' ',
            output_files[5] + ' ', output_files[6] + ' ',
            output_files[7] + ' ', output_files[8] + ' ',
            str(xlamds) + ' ',
            str(ncar) + ' ',
            str(mult) + ' ',
            str(ds) + ' ',
            str(dk) + ' ',
            str(SHF) + ' ',
            str(nslice) + ' ',
            str(dr)
        ])
        runpar = '`which mpirun` -x PATH -x MPI_PYTHON_SITEARCH -x PYTHONPATH'
        prog = ' ' + 'python /data/netapp/xfel/gianluca/products/ocelot/utils/seed.py ' + ARGS + ''
        #prog   = ' '+'python /data/netapp/xfel/svitozar/CODE/ocelot/utils/seed.py '+ARGS+''

        #print 'NEWARGS'
        #print ARGS
        #exit()
        cmd = runpar + prog
        os.system(cmd)

    if paral == False:
        import seed0 as sd
        sd.filterfield(
            input_file + '.dfl',
            output_files[0],
            output_files[1],
            output_files[2],
            output_files[3],
            output_files[4],
            output_files[5],
            output_files[6],
            output_files[7],
            output_files[8],
            #output_files[9],
            #output_files[10],
            #output_files[11],
            #output_files[12],
            #output_files[13],
            #output_files[14],
            #output_files[15],
            #output_files[16],
            xlamds,
            ncar,
            mult,
            ds,
            dk,
            SHF,
            nslice,
            dr)

    print 'reading filtered file (hxrss_common, lile 728) ', output_files[5]

    ssc, Pout = readres(output_files[5])
    lsc, Sout = readres(output_files[7])

    return ssc, Pout, lsc, Sout
예제 #2
0
파일: ex2.py 프로젝트: slaclab/ocelot
    #geo = Geometry([m2])

    return geo


geo = init_geometry()
scene = init_plots(['geometry:x','geometry:y'], geo)

rays = []

a = geo.find("m2").a


for i in range(40):
    
    r = Ray(r0=[0.01,a[1],-sqrt(a[0]**2 - a[1]**2)], k=[0,-a[1]/a[0] * (1+ np.random.randn()*0.1) ,1])
    #test 1 -0.0359695
    #r = Ray(r0=[0,geo.find("m2").a[1],-sqrt(a[0]**2 - a[1]**2)], k=[0,-0.0359695 ,1])
    
    trace_ray(r, geo)
    rays.append(r)

'''
f = sqrt(a[0]**2 - a[1]**2)
r = Ray(r0=[0,a[1],-f], k=[0,-a[1]/a[0] ,1])
trace_ray(r, geo)
rays.append(r)
scene.ax[0].plot( [-f,f],[a[1],a[1]],color='red', lw=1)
'''

plot_rays(scene.ax[0], rays, proj='x')
예제 #3
0
def sseed(input_file,
          E_ev,
          chicane,
          run_dir,
          delay=None,
          debug=True,
          output_file=None,
          wake=None,
          xt_couple=False,
          n_peak=1,
          npad=6,
          threaded=True):

    h = 4.135667516e-15
    c = 299792458.0

    t1 = time.time()
    g = readGenesisOutput(input_file)
    print 'read sliced field ', g('ncar'), g.nSlices
    ncar = int(g('ncar'))
    dgrid = float(g('dgrid'))

    idx_max = np.argmax(g.I)
    g.idx_max = idx_max
    print 'ss: idx_max:', g.idx_max

    slices = readRadiationFile(fileName=input_file + '.dfl', npoints=g('ncar'))

    print 'field readout :', time.time() - t1, ' sec'
    t1 = time.time()

    s3d = Signal3D()
    s3d.slices = slices
    s3d.mesh_size = (int(g('ncar')), int(g('ncar')))
    s3d.g = g
    pulse3d, bunch = s3d, None

    pulse3d.slices = np.reshape(pulse3d.slices, (1, -1))  # 1d array
    pulse3d_part = Signal3D()
    pulse3d_part.nx = int(pulse3d.g('ncar'))
    pulse3d_part.ny = int(pulse3d.g('ncar'))
    pulse3d_part.tmax = pulse3d.g.nSlices * pulse3d.g('zsep') * pulse3d.g(
        'xlamds') / 2.99792458e8 * 1.e15
    pulse3d_part.slices = pulse3d.slices[0]
    pulse3d_part.E_ref = 1. / pulse3d.g(
        'xlamds') * 4.135667516e-15 * 2.99792458e8

    g.npad = npad
    pulses_1d = pulses_from_field(pulse3d_part, npad=npad, threaded=threaded)
    g.nslice = pulses_1d.nslice
    print '*** created', pulses_1d.n_pulses, ' pulses *** '

    if debug:
        pulse_idx = int(pulse3d_part.nx * pulse3d_part.ny / 2.)
        print 'plotting slice', pulse_idx
        fig = plt.figure()
        ax = fig.add_subplot(221)
        ax.grid(True)
        ax.plot(pulses_1d.t,
                np.abs(pulses_1d.f[pulse_idx]) + 1,
                '#000000',
                alpha=0.5)
        ax.set_title('Stage 1 FEL pulse')

    pulse_idx = int(pulse3d_part.nx * pulse3d_part.ny / 2.)

    n_fel_start = 0
    for i in range(len(pulses_1d.f[pulse_idx])):
        if np.abs(pulses_1d.f[pulse_idx][i]) > 1.0:
            n_fel_start = i
            break

    n_points = len(pulses_1d.f[pulse_idx]) / (2 * npad + 1)
    g.power_ref = np.abs(pulses_1d.f[pulse_idx])[n_points * npad:n_points *
                                                 (npad + 1)]

    r = Ray()
    r.lamb = 2 * pi * hbar * c / E_ev
    print 'wavelength', r.lamb, '(', E_ev, 'eV), filetring...'

    filt = get_crystal_filter(chicane.cryst,
                              r,
                              ref_idx=chicane.cryst.ref_idx,
                              k=pulses_1d.freq_k)
    print pulses_1d.freq_k
    chicane.cryst.filter = filt

    f_av = np.zeros(len(pulses_1d.t))

    print 'field/filter preparation: ', time.time() - t1, ' sec'
    t1 = time.time()
    if threaded:
        print 'filtering (threaded) ... '
        #ncores = multiprocessing.cpu_count()/8
        pool = multiprocessing.Pool()
        tasks = [
            pool.apply_async(filter_1d,
                             (pulses_1d, chicane.cryst.filter.tr, i))
            for i in range(pulses_1d.n_pulses)
        ]
        for t in tasks:
            t.wait()
        pool.close()
        pool.join()
    else:
        print 'filtering (not threaded) ... '
        for i in range(pulses_1d.n_pulses):
            #print 'filtering:', i, '/', len(pulses_1d.f[i,:])
            filter_1d(pulses_1d, chicane.cryst.filter.tr, i)

    for i in xrange(pulses_1d.n_pulses):
        f_av += np.abs(pulses_1d.f[i, :])

    print 'filtering time: ', time.time() - t1, ' sec'
    t1 = time.time()

    if wake != None:
        f_av = wake

    n_marg = 20 / (pulses_1d.t[1] - pulses_1d.t[0]
                   )  # number of margin slices prior to FEL pulse
    f_wake = get_wake(f_av, n_fel_start - n_marg, smooth_param=2)

    if debug:
        ax2 = fig.add_subplot(222)
        ax2.set_title('Wake')
        ax2.grid(True)
        ax2.set_yscale('log')
        ax2.plot(f_wake, 'r--')
        ax2.plot(f_av, 'g--')

    x, y = peaks(pulses_1d.t, f_wake, n=4)
    print 'peaks', x, y

    if delay == None:
        delay = pulses_1d.t[pulses_1d.nslice * npad +
                            g.idx_max] - x[n_peak]  # based on current maximum

    n_delay = int(delay / (pulses_1d.t[1] - pulses_1d.t[0]))
    n_start = pulses_1d.npad * pulses_1d.nslice - n_delay

    print 'delay', delay, ' fs ', delay * 1.e-15 * 3.e8 / 1.e-6, 'mu m ', n_delay, ' slices', ' nslice=', pulses_1d.nslice, ' n_start=', n_start
    print 'max current slice: ', pulses_1d.nslice * npad + g.idx_max

    i1 = 0
    i2 = pulses_1d.n_pulses

    t = pulses_1d.t[n_start:n_start + pulses_1d.nslice]
    pulse3d.slices = np.reshape(
        pulse3d.slices, (pulses_1d.nslice, pulse3d_part.nx, pulse3d_part.nx))
    field_from_pulses(t, pulses_1d.f[i1:i2,
                                     n_start:n_start + pulses_1d.nslice],
                      pulse3d.mesh_size, pulse3d.slices)

    g.spec = np.fft.fft(pulse3d.slices[:, ncar / 2, ncar / 2])
    g.max_power = np.max(np.abs(pulse3d.slices[:, ncar / 2, ncar / 2]))
    g.power = np.abs(pulse3d.slices[:, ncar / 2, ncar / 2])
    g.freq_ev = h * fftfreq(len(g.spec), d=(t[1] - t[0]) * 1.e-15)

    g.delay = delay

    g.seed_axis = np.abs(pulse3d.slices[:, ncar / 2, ncar / 2])
    g.wake = f_av
    nslice = len(pulse3d.slices[:, 0, 0])

    if xt_couple:  # spatial-temporal coupling
        dct = (pulses_1d.t[1] - pulses_1d.t[0]) * 1.e-15 * c

        for i_slice in xrange(len(pulse3d.slices[:, 0, 0])):
            #print 'shifting slice', i_slice
            shift_x = (nslice - i_slice) * dct * cos(
                chicane.cryst.thetaB) / sin(chicane.cryst.thetaB)
            #print 'shift_x' , shift_x
            #print dgrid, ncar
            n_shift = int(shift_x / (dgrid / ncar))
            #print 'n_shift', n_shift
            pulse3d.slices[i_slice, :, :] = np.roll(
                pulse3d.slices[i_slice, :, :], n_shift, 0)

    if debug:
        ax.set_yscale('log')
        ax.plot(t + 0, np.abs(pulse3d.slices[:, ncar / 2, ncar / 2]), 'r--')
        ax.plot(t + 0, np.abs(pulse3d.slices[:, ncar / 2, ncar / 2 + 5]),
                'r--')
        ax.plot(t + delay, np.abs(pulse3d.slices[:, ncar / 2, ncar / 2]), 'g-')
        ax.plot(pulses_1d.t[pulses_1d.nslice * npad + g.idx_max],
                f_wake[pulses_1d.nslice * npad + g.idx_max], 'bs')
        print 'seed t', pulses_1d.t[pulses_1d.nslice * npad +
                                    g.idx_max], f_wake[pulses_1d.nslice * npad
                                                       + g.idx_max]

        ax3 = fig.add_subplot(223)
        #ax3.plot(t + delay, np.imag(pulse3d.slices[:,ncar/2,ncar/2]), 'b-', lw=1)
        print 'debug: max slice', g.idx_max,
        ax3.plot(np.abs(pulse3d.slices[100, :, ncar / 2]), 'r--')
        ax3.plot(np.abs(pulse3d.slices[200, :, ncar / 2]), 'g--')
        ax3.plot(np.abs(pulse3d.slices[300, :, ncar / 2]), 'b--')
        ax3.plot(np.abs(pulse3d.slices[g.idx_max, :, ncar / 2]), 'b-')

        ax4 = fig.add_subplot(224)
        ax4.plot(g.freq_ev, np.abs(g.spec), 'b-')
        #plt.title('Spectrum (middle pulse after seed)')

        fig = plt.figure()
        ax5 = fig.add_subplot(111)
        ax5.set_yscale('log')
        ax5.plot(np.abs(pulse3d.slices[:, ncar / 2, ncar / 2]), 'r-')
        ax5.plot(g.wake[n_start:n_start + pulses_1d.nslice], 'b-')
        ax5.plot(g.I, 'g-')

        plt.show()

    print 'creating final field: ', time.time() - t1, ' sec'
    t1 = time.time()

    if output_file != None:
        writeRadiationFile(output_file + '.dfl', pulse3d.slices)
        print 'written radiation file, slices', len(pulse3d.slices[:, ncar / 2,
                                                                   ncar / 2])

    print 'writing final field: ', time.time() - t1, ' sec'

    return g
예제 #4
0
파일: ex1.py 프로젝트: slaclab/ocelot
                id="m2")
    m3 = Mirror(r=[0, -50 * cm, 20 * cm],
                size=[10 * cm, 10 * cm, 1 * mm],
                pitch_ang=pi / 4.,
                id="m3")
    m4 = Mirror(r=[0, 0, 20 * cm],
                size=[10 * cm, 8 * cm, 10 * mm],
                pitch_ang=-3 * pi / 4.,
                id="m4")

    geo = Geometry([m1, m2, m3, m4])

    return geo


geo = init_geometry()
scene = init_plots(['geometry:y'], geo)

rays = []

sigma_y = 0.1e-1  # rad

for i in range(100):
    r = Ray(r0=[0, 0, -0.3], k=[0, np.random.randn() * sigma_y, 1])
    trace_ray(r, geo)
    rays.append(r)

plot_rays(scene.ax[0], rays, proj='y')

plt.show()
                  no=[0.0, 0, 1],
                  d=[10 * mum, 10 * mum],
                  id="a1")
    geo = Geometry([m1, a1])

    return geo


geo = init_geometry()
scene = init_plots(['geometry:x', 'geometry:y'], geo)

rays = []

a = geo.find("m1").a

r = Ray(r0=[a[1], 0.0, -sqrt(a[0]**2 - a[1]**2)],
        k=[-a[1] / a[0] * (1 + 0.0), 0.0, 1])
trace_ray(r, geo)
rays.append(r)
'''
r = Ray(r0=[a[1],0.0, -sqrt(a[0]**2 - a[1]**2)], k=[-a[1]/a[0] * (1 - 0.05) ,0.0, 1])
trace_ray(r, geo)
rays.append(r)

r = Ray(r0=[a[1],0.0, -sqrt(a[0]**2 - a[1]**2)], k=[-a[1]/a[0] * (1 + 0.05) ,0.0, 1])
trace_ray(r, geo)
rays.append(r)
'''

plot_rays(scene.ax[0], rays, proj='x', alpha=1.0)
plot_rays(scene.ax[1], rays, proj='y', alpha=1.0)
예제 #6
0
파일: ex5.py 프로젝트: slaclab/ocelot
geo = init_geometry()
scene = init_plots(['geometry', 'detectors:d1', 'detectors:d2'], geo)
#scene = init_plots(['geometry'], geo)

rays = []

sigma_x = 30.e-2 * mum
sigma_xp = 10.e-16  # rad
sigma_y = 30.e-2 * mum  # m
sigma_yp = 10.e-16  # rad

for i in range(1):
    r = Ray(r0=[
        np.random.randn() * sigma_x,
        np.random.randn() * sigma_y, -145 * m
    ],
            k=[np.random.randn() * sigma_xp,
               np.random.randn() * sigma_yp, 1])
    print('tracing ray...')
    trace_ray(r, geo)
    rays.append(r)

plot_rays(scene.ax[0], rays)

#plot_detectors(scene, geo)

try:
    m1 = geo.find("d1").matrix.transpose()
    scene.profile_im["d1"].imshow(m1,
                                  cmap='gist_heat',
                                  interpolation='none',
예제 #7
0
                pitch_ang=3 * pi / 4.,
                id="m1")
    geo = Geometry([m1])
    return geo


geo = init_geometry()

print 'pitch', geo.find("m1").pitch_ang
print 'no', geo.find("m1").no

scene = init_plots(['geometry:y'], geo)

rays = []

r = Ray(r0=[0, 0, -0.6], k=[0, 0, 1])
trace_ray(r, geo)
rays.append(r)

r = Ray(r0=[0, 0, -0.6], k=[0, 0.1, 1])
trace_ray(r, geo)
rays.append(r)

r = Ray(r0=[0, 0, -0.6], k=[0, -0.1, 1])
trace_ray(r, geo)
rays.append(r)

plot_rays(scene.ax[0], rays, proj='y')

plt.show()
예제 #8
0
                  size=[0.02 * m, 0.02 * m, 0.20 * m],
                  d=[10 * mum, 10 * mum],
                  id="a1")
    geo = Geometry([m1, a1])

    return geo


geo = init_geometry()
scene = init_plots(['geometry:x', 'geometry:y'], geo)

rays = []

a = geo.find("m1").a

r = Ray(r0=[0.0, a[1], -sqrt(a[0]**2 - a[1]**2)],
        k=[0.0, -a[1] / a[0] * (1 + 0.0), 1])
trace_ray(r, geo)
rays.append(r)

r = Ray(r0=[0.0, a[1], -sqrt(a[0]**2 - a[1]**2)],
        k=[0.0, -a[1] / a[0] * (1 - 0.05), 1])
trace_ray(r, geo)
rays.append(r)

r = Ray(r0=[0.0, a[1], -sqrt(a[0]**2 - a[1]**2)],
        k=[0.0, -a[1] / a[0] * (1 + 0.05), 1])
trace_ray(r, geo)
rays.append(r)

plot_rays(scene.ax[0], rays, proj='x', alpha=1.0)
plot_rays(scene.ax[1], rays, proj='y', alpha=1.0)