Exemplo n.º 1
0
    def _prepareGenesisRun(self):
        """ """
        """ Private method to setup the genesis run. """

        # Setup empty distribution.
        edist = genesis.GenesisElectronDist()

        # Fill in the data. Reverse time axis.
        edist.x = numpy.flipud(self.__input_data[:, 0])
        edist.xp = numpy.flipud(self.__input_data[:, 1])
        edist.y = numpy.flipud(self.__input_data[:, 2])
        edist.yp = numpy.flipud(self.__input_data[:, 3])
        edist.t = numpy.flipud(self.__input_data[:, 4])
        edist.g = numpy.flipud(self.__input_data[:, 5])
        edist.part_charge = self.__charge / edist.len()

        # Produce a genesis beam
        self.__genesis_beam = genesis.edist2beam(
            edist, step=self.parameters['time_averaging_window'])

        # Generate genesis input with defaults and guesses from beam peak parameters.
        genesis_input = genesis.generate_input(
            undulator=self.parameters['undulator_parameters'],
            beam=genesis.get_beam_peak(self.__genesis_beam),
            itdp=self.parameters['is_time_dependent'])

        # Merge guessed and external input.
        if hasattr(self, '_GenesisPhotonSource__genesis_input'
                   ) and self.__genesis_input is not None:
            for key, value in list(self.__genesis_input.__dict__.items()):
                if value != 0.0:
                    setattr(genesis_input, key, value)

        genesis_input.exp_dir = genesis_input.run_dir = self.output_path
        # Store merged genesis input.
        self.__genesis_input = genesis_input

        # Set beam to actual beam, not the peak parameters.
        self.__genesis_input.beam = self.__genesis_beam

        # Call "run_genesis" to setup run directories, which also issues the launcher.launch() command, which, naturall, fails here.
        try:
            genesis.run_genesis(self.__genesis_input, launcher=None, debug=0)
        except AttributeError:
            pass
        except:
            raise
    def GEN_simul_preproc(self, A_input, i_aft=0, dirno=1, startcharge=250):
        self.startcharge = startcharge
        if not self.file_pout.endswith('/'):
            self.file_pout=self.file_pout+'/'
        #print('\n\n\nis it working?\n\n')
        inp_arr = []
        A_bbeam = ['rxbeam','rybeam','emitx','emity','alphax','alphay','xbeam','ybeam','pxbeam','pybeam']
        A_simul = ['alignradf','npart','ncar','zsep','delz','dmpfld','fbess0','dgrid','rmax0','xkx','xky','iwityp',
                   'nptr','lbc','zrayl','zstop','zwaist','delgam','xlamd','nscr','nscz','curpeak',
                   'iphsty','nharm','curlen','nbins','gamma0','isravg','isrsig','eloss','version',
                   'multconv','imagl','convharm','idril','ffspec','ndcut','ibfield','nslice','ntail',
                   'ippart','ispart','ipradi','isradi']
        A_td = ['itdp','prad0','shotnoise']
        A_und = ['quadd', 'quadf','fl','dl','drl','nsec','nwig','aw0', 'awd']

        # print('++++ Output Path {0} ++++++'.format(self.file_pout))

        # Setting the number of noise realisations and scan (over quads or different parameters)

        if (self.i_scan ==0):
            s_scan = range(1)
            num = self.stat_run
            run_ids = range(0,num)
            # print('++++++++ No scan ++++++++++')
        elif (self.i_scan !=0):
            if (self.parameter in A_und):
                run_ids= range(1)
                if self.parameter !='aw0':
                    s_scan = range(int(self.init),int(self.end),int(np.ceil((self.end-self.init)/(self.n_scan))))
                else:
                    s_scan = np.linspace(self.init,self.end,self.n_scan)
                # print('++++ Quad scan, parameter  {0} ++++++'.format(self.parameter))
            elif (self.parameter=='xlamds'):
                run_ids= range(1)
                s_scan = np.linspace(self.init,self.end,self.n_scan)
                # print('++++ Quad scan, parameter  {0} ++++++'.format(self.parameter))
            else:
                s_scan = np.linspace(self.init,self.end,self.n_scan)
                num = self.stat_run
                run_ids = range(0,num)
                # print('++++ Number of noise realisations {0} ++++++'.format(num))

            # setting the undulator design( Magnetic Lattice)
        A_undulator = self.undulator_design(A_input)

            # Fill in the beam object
        A_beam = self.BeamDefinition(A_input)
        if (getattr(A_input,'itdp')==0):
            # print('++++ Steady State run +++++')
            i_tdp = False
        elif (getattr(A_input,'itdp')==1):
            i_tdp = True

            # Generate input object
        inp = generate_input(A_undulator['Undulator Parameters'],A_beam,itdp=i_tdp)

        # Overwrite the simulation attributes of the input object with the ones defined in the input file
        for key in A_input.__dict__:
            if (key in A_simul) or (key in A_und) or (key in A_td) or (key =='xlamds') or (key == 'f1st') or (key == 'nslice') or (key == 'ntail'):
                setattr(inp,key, getattr(A_input,key))
        for key in ['edist','beam','dfl']:
            if getattr(A_input,key)!=None:
                setattr(inp,key,getattr(A_input,key))

        # Set up some input parameters
        if getattr(inp,'itdp')==0:
            setattr(inp,'type','steady')
        else:
            setattr(inp,'type','tdp')
        setattr(inp, 'awd', float(getattr(inp, 'aw0')))

        # idump attribute
        if (getattr(self,'idump')) == 1:
            setattr(inp,'idump',1)
            setattr(inp,'idmpfld',1)

        # Existent dist or beam file (if exists)
        if (getattr(self,'i_edist') == 1) and (hasattr(self,'file_edist')):
            inp=self.GEN_existent_beam_dist_dpa_rad(inp,'edist')
        elif (getattr(self,'i_beam') == 1) and (hasattr(self,'file_beam')):
            #print inp.__dict__.keys()
            inp=self.GEN_existent_beam_dist_dpa_rad(inp,'beam')
            #print inp.__dict__.keys()
        elif  (getattr(self,'i_rad') == 1) and (hasattr(self,'file_rad')):
            inp=self.GEN_existent_beam_dist_dpa_rad(inp,'rad')
        elif  (getattr(self,'i_dpa') == 1) and (hasattr(self,'file_dpa')):
            inp=self.GEN_existent_beam_dist_dpa_rad(inp,'dpa')
        elif  (getattr(self,'i_dfl') == 1) and (hasattr(self,'file_dfl')):
            inp=self.GEN_existent_beam_dist_dpa_rad(inp,'dfl')
        else:
            pass
            # print('++++ No edist or beam or dpa or rad file available ++++++')
        # print inp.beam

        # Read HDF5 file.
        if hasattr(self,'i_HDF5') and getattr(self,'i_HDF5')==1 and hasattr(self,'HDF5_file'):
            inp, beam = self.convert_HDF5_edist(inp, getattr(self,'HDF5_file'))
            setattr(inp,'beam',None)
            gamma = np.median(inp.edist.g)
            # setattr(inp,'xlamds',float(inp.xlamd*(1.0+np.square(inp.aw0))/(2.0*np.square(gamma))))
            # setattr(inp,'xlamds', float(0.022058051560136/(gamma**2))) ## DJD 15/02/2019
            setattr(inp,'xlamds', float(0.01685042566473/(gamma**2))) ## JKJ 04/06/2019
            print( 'aw0 = ', inp.aw0)
            print( 'awd = ', inp.awd)
            print( 'xlamds = ', inp.xlamds)

        elif  (hasattr(self,'i_HDF5') and getattr(self,'i_HDF5')==1) and not (hasattr(self,'HDF5_file')):
            # print('Path of  the HDF5 file not provided')
            return
        else:
            pass
            # print('No need to HDF5 ASTRA file')

        # if (getattr(self,'i_edist')==1) or (getattr(inp,'edist')!=None) or  (getattr(inp,'beam')!=None) :
        #     setattr(inp,'ntail',0)
        # else:
        #     if (getattr(self,'i_edist')==0) and getattr(A_input,'ntail')!=0 :
        #         setattr(inp,'ntail',int(getattr(A_input,'ntail')))
        #     else:
        #         setattr(inp,'ntail',-int(np.floor(getattr(inp,'nslice')/2)))
        # Overwrite the simulation attributes if the user has new values for them defined in the input data structure
        if (hasattr(self, 'i_rewrite')) and (hasattr(self, 'par_rew')) and (getattr(self, 'i_rewrite') == 1):
            inp = self.GEN_rewrite_par(inp)
        else:
            pass

        # Running over noise realisations and/or scan parameters
        for n_par in s_scan:
            for run_id in run_ids:
                inp.runid = run_id
                inp.lout =  [1,1,1,1,1,0,1,1,1,1,1,1,1,1,0,0,0,0,0]
                inp.run_dir = getattr(self,'file_pout')

                try:
                    os.makedirs(inp.run_dir)
                except:
                    pass
                if self.i_scan==1 and inp.f1st==1:
                    inp= self.GEN_scan(n_par ,A_input,A_undulator,inp)
                elif self.i_scan==0 and inp.f1st==1:
                    inp.lat = A_undulator['Magnetic Lattice']
                    setattr(inp,'magin',1)
                else:
                    inp.lat =None
                    setattr(inp,'magin',0)
                # DJD 16/10/18 temporary hack to randomise seed
                ipseed = 56#np.random.randint(9999)
                setattr(inp,'ipseed', ipseed)

                inp_arr.append(inp)
                launcher=get_genesis_launcher(self.gen_launch)
                g = run_genesis(inp,launcher,i_aft=i_aft)
                setattr(g,'filePath',str(inp.run_dir))
                # g.Lsat = g.z[np.argmax(g.bunching[np.argmax(g.p_int[:,-1])])]
                g.bunch_length = self.bunch_length
                g.Lsat = g.z[np.argmax(g.bunching[np.argmax(g.I)])]
        g.momentum = inp.edist.cp
        # print( 'g.momentum = ', g.momentum)
        return g
    def GEN_simul_preproc(self, A_input, i_aft=0):
        if not self.file_pout.endswith('/'):
            self.file_pout = self.file_pout + '/'
        #print('\n\n\nis it working?\n\n')
        inp_arr = []
        A_bbeam = [
            'rxbeam', 'rybeam', 'emitx', 'emity', 'alphax', 'alphay', 'xbeam',
            'ybeam', 'pxbeam', 'pybeam'
        ]
        A_simul = [
            'alignradf', 'npart', 'ncar', 'zsep', 'delz', 'dmpfld', 'fbess0',
            'dgrid', 'rmax0', 'xkx', 'xky', 'iwityp', 'nptr', 'lbc', 'zrayl',
            'zstop', 'zwaist', 'delgam', 'xlamd', 'nscr', 'nscz', 'curpeak',
            'iphsty', 'nharm', 'curlen', 'nbins', 'gamma0', 'isravg', 'isrsig',
            'eloss', 'version', 'multconv', 'imagl', 'convharm', 'idril',
            'ffspec', 'ndcut', 'ibfield', 'nslice', 'ntail', 'ippart',
            'ispart', 'ipradi', 'isradi'
        ]
        A_td = ['itdp', 'prad0', 'shotnoise']
        A_und = [
            'quadd', 'quadf', 'fl', 'dl', 'drl', 'nsec', 'nwig', 'aw0', 'awd'
        ]

        print('++++ Output Path {0} ++++++'.format(self.file_pout))

        # Setting the number of noise realisations and scan (over quads or different parameters)

        if (self.i_scan == 0):
            s_scan = range(1)
            num = self.stat_run
            run_ids = xrange(0, num)
            print('++++++++ No scan ++++++++++')
        elif (self.i_scan != 0):
            if (self.parameter in A_und):
                run_ids = range(1)
                if self.parameter != 'aw0':
                    s_scan = range(
                        int(self.init), int(self.end),
                        int(np.ceil((self.end - self.init) / (self.n_scan))))
                else:
                    s_scan = np.linspace(self.init, self.end, self.n_scan)
                print('++++ Quad scan, parameter  {0} ++++++'.format(
                    self.parameter))
            elif (self.parameter == 'xlamds'):
                run_ids = range(1)
                s_scan = np.linspace(self.init, self.end, self.n_scan)
                print('++++ Quad scan, parameter  {0} ++++++'.format(
                    self.parameter))
            else:
                s_scan = np.linspace(self.init, self.end, self.n_scan)
                num = self.stat_run
                run_ids = xrange(0, num)
                print(
                    '++++ Number of noise realisations {0} ++++++'.format(num))

            # setting the undulator design( Magnetic Lattice)
        A_undulator = self.undulator_design(A_input)

        # Fill in the beam object
        A_beam = self.BeamDefinition(A_input)
        if (getattr(A_input, 'itdp') == 0):
            print('++++ Steady State run +++++')
            i_tdp = False
        elif (getattr(A_input, 'itdp') == 1):
            i_tdp = True

            # Generate input object
        inp = generate_input(A_undulator['Undulator Parameters'],
                             A_beam,
                             itdp=i_tdp)

        # Overwrite the simulation attributes of the input object with the ones defined in the input file
        for key in A_input.__dict__:
            if (key in A_simul) or (key in A_und) or (key in A_td) or (
                    key == 'xlamds') or (key == 'f1st') or (
                        key == 'nslice') or (key == 'ntail'):
                setattr(inp, key, getattr(A_input, key))
        for key in ['edist', 'beam', 'dfl']:
            if getattr(A_input, key) != None:
                setattr(inp, key, getattr(A_input, key))

        # Set up some input parameters
        if getattr(inp, 'itdp') == 0:
            setattr(inp, 'type', 'steady')
        else:
            setattr(inp, 'type', 'tdp')
        setattr(inp, 'awd', float(getattr(inp, 'aw0')))

        # idump attribute
        if (getattr(self, 'idump')) == 1:
            setattr(inp, 'idump', 1)
            setattr(inp, 'idmpfld', 1)

        # Existent dist or beam file (if exists)
        if (getattr(self, 'i_edist') == 1) and (hasattr(self, 'file_edist')):
            inp = self.GEN_existent_beam_dist_dpa_rad(inp, 'edist')
        elif (getattr(self, 'i_beam') == 1) and (hasattr(self, 'file_beam')):
            #print inp.__dict__.keys()
            inp = self.GEN_existent_beam_dist_dpa_rad(inp, 'beam')
            #print inp.__dict__.keys()
        elif (getattr(self, 'i_rad') == 1) and (hasattr(self, 'file_rad')):
            inp = self.GEN_existent_beam_dist_dpa_rad(inp, 'rad')
        elif (getattr(self, 'i_dpa') == 1) and (hasattr(self, 'file_dpa')):
            inp = self.GEN_existent_beam_dist_dpa_rad(inp, 'dpa')
        elif (getattr(self, 'i_dfl') == 1) and (hasattr(self, 'file_dfl')):
            inp = self.GEN_existent_beam_dist_dpa_rad(inp, 'dfl')
        else:
            print('++++ No edist or beam or dpa or rad file available ++++++')
        print inp.beam

        # Read ASTRA file.
        if hasattr(self, 'i_astra') and getattr(
                self, 'i_astra') == 1 and hasattr(self, 'astra_file'):
            inp = self.convert_ASTRA_edist(inp)
            setattr(inp, 'beam', None)
        elif (hasattr(self, 'i_astra') and getattr(self, 'i_astra')
              == 1) and not (hasattr(self, 'astra_file')):
            print('Path of  the ASTRA file not provided')
            return
        else:
            print('No need to read ASTRA file')

        # Rematch beam (if the flag has been set within the data dictionary)
        if (getattr(inp, 'edist') != None) and hasattr(
                self, 'i_match') and (getattr(self, 'i_match') == 1):
            inp = self.rematch_edist(inp)

        # Setting up the time window of the distribution
        #if getattr(self,'i_beam')==0:
        #    setattr(inp,'nslice',getattr(A_input,'nslice'))
        #else:
        #    beamf = getattr(inp,'beam')
        #    if hasattr(beamf,'I'):
        #        setattr(inp,'curlen', getattr(beamf,tpulse) * speed_of_light / 1e15)
        #        setattr(inp,'nslice',8 * int(inp.curlen / inp.zsep / inp.xlamds))
        #    else:
        #        setattr(inp,'nslice',getattr(A_input,'nslice'))

        if (getattr(self, 'i_edist') == 1) or (getattr(
                inp, 'edist') != None) or (getattr(inp, 'beam') != None):
            setattr(inp, 'ntail', 0)
        else:
            if (getattr(self, 'i_edist')
                    == 0) and getattr(A_input, 'ntail') != 0:
                setattr(inp, 'ntail', int(getattr(A_input, 'ntail')))
            else:
                setattr(inp, 'ntail',
                        -int(np.floor(getattr(inp, 'nslice') / 2)))
        # Overwrite the simulation attributes if the user has new values for them defined in the input data structure
        if (hasattr(self, 'i_rewrite')) and (hasattr(
                self, 'par_rew')) and (getattr(self, 'i_rewrite') == 1):
            inp = self.GEN_rewrite_par(inp)
        else:
            pass

        # Running over noise realisations and/or scan parameters
        for n_par in s_scan:
            for run_id in run_ids:
                inp.runid = run_id
                inp.lout = [
                    1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0
                ]
                if ((self.stat_run == 1) or (self.i_scan == 1)):
                    setattr(inp, 'ipseed', -1)
                else:
                    ipseed = np.random.randint(9999)
                    setattr(inp, 'ipseed', ipseed)
                inp.run_dir = getattr(self, 'file_pout') + 'scan_' + str(
                    n_par) + '/ip_seed_' + str(inp.ipseed) + '/'

                try:
                    os.makedirs(inp.run_dir)
                    if self.stat_run > 1:
                        while ipseed in [
                                int(files[8:]) for files in os.listdir(
                                    getattr(self, 'file_pout') + 'scan_' +
                                    str(n_par)) if os.path.isdir(
                                        getattr(self, 'file_pout') + 'scan_' +
                                        str(n_par) + '/' + files)
                        ]:
                            ipseed = np.random.randint(9999)
                            shutil.rmtree(inp.run_dir)
                        else:
                            setattr(inp, 'ipseed', ipseed)
                            inp.run_dir = getattr(
                                self, 'file_pout') + 'scan_' + str(
                                    n_par) + '/ip_seed_' + str(
                                        inp.ipseed) + '/'
                            os.makedirs(inp.run_dir)
                except OSError as exc:
                    if (exc.errno == errno.EEXIST) and os.path.isdir(
                            self.file_pout + 'scan' + str(n_par) + '/run_' +
                            str(run_id)):
                        pass
                    else:
                        raise
                if self.i_scan == 1 and inp.f1st == 1:
                    inp = self.GEN_scan(n_par, A_input, A_undulator, inp)
                elif self.i_scan == 0 and inp.f1st == 1:
                    inp.lat = A_undulator['Magnetic Lattice']
                    setattr(inp, 'magin', 1)
                else:
                    inp.lat = None
                    setattr(inp, 'magin', 0)
                # DJD 16/10/18 temporary hack to randomise seed
                ipseed = np.random.randint(9999)
                setattr(inp, 'ipseed', ipseed)

                inp_arr.append(inp)
                launcher = get_genesis_launcher(self.gen_launch)
                print('+++++ Starting simulation of noise realisation {0}'.
                      format(run_id))
                g = run_genesis(inp, launcher, i_aft=i_aft)
                setattr(g, 'filePath', str(inp.run_dir))
                #if (inp.itdp==1):
                #    plot_gen_out_all(handle=g, savefig=True, showfig=False, choice=(1, 1, 1, 1, 3.05, 0, 0, 0, 0, 0, 0, 0, 0), vartype_dfl=complex128, debug=1)
                inp.latticefile = None
                inp.outputfile = None
                inp.edistfile = None
                inp.beamfile = None
                inp.fieldfile = None
                inp.radfile = None
                #print g.__dict__.keys()

        #print('++++ postprocessing (results saved in {0}results++++'.format(self.file_pout))
        #self.post_processing(inp,s_scan)
        #plt.close("all")
        #print inp.out
        #return out
        return g
 def run_genesis(self, inp, launcher, *args, **kwargs):
     g = run_genesis(inp, launcher, i_aft=i_aft)
     return g
def main():
    import os, sys
    import numpy as np
    from ocelot.common import globals
    from ocelot.adaptors.genesis import generate_input, generate_lattice, get_genesis_launcher, run_genesis, filename_from_path
    from ocelot.gui.genesis_plot import plot_gen_out_all, plot_gen_stat

    # Reading the input file

    A_input = read_input_file(os.getcwd() + '/')
    A_bbeam = [
        'gamma0', 'curlen', 'curpeak', 'delgam', 'rxbeam', 'rybeam', 'emitx',
        'emity', 'alphax', 'alphay', 'xbeam', 'ybeam', 'pxbeam', 'pybeam'
    ]
    A_simul = [
        'npart', 'ncar', 'zsep', 'delz', 'dmpfld', 'fbess0', 'dgrid', 'rmax0',
        'xkx', 'xky', 'iwityp'
    ]
    A_td = ['itdp', 'prad0', 'shotnoise']
    A_und = ['quadd', 'quadf', 'fl', 'dl', 'drl', 'nsec', 'nwig', 'aw0', 'awd']

    #set simulation parameters by calling the read_input_file function
    exp_dir = A_input['exp_dir'][1:-1] + '/'
    print('++++ Output Path {} ++++++'.format(exp_dir))

    # Setting the number of noise realisations and scan (over quads or different parameters)
    A_input['parameter'] = str(A_input['parameter'][:-1])
    if (A_input['i_scan'] == 0):
        s_scan = range(1)
        num = A_input['stat_run']
        run_ids = xrange(0, num)
        print('++++++++ No scan ++++++++++')
    elif (A_input['i_scan'] != 0):
        if (A_input['parameter'] in A_und):
            run_ids = range(1)
            if A_input['parameter'] != 'aw0':
                s_scan = range(
                    int(A_input['init']), int(A_input['end']),
                    int(
                        np.ceil((A_input['end'] - A_input['init']) /
                                (A_input['n_scan'] - 1))))
            else:
                s_scan = np.linspace(A_input['init'], A_input['end'],
                                     A_input['n_scan'])
            print('++++ Quad scan, parameter  {} ++++++'.format(
                A_input['parameter']))
        elif (A_input['parameter'] == 'xlamds'):
            run_ids = range(1)
            s_scan = np.linspace(A_input['init'], A_input['end'],
                                 A_input['n_scan'])
            print('++++ Quad scan, parameter  {} ++++++'.format(
                A_input['parameter']))
        else:
            s_scan = np.linspace(A_input['init'], A_input['end'],
                                 A_input['n_scan'])
            num = A_input['stat_run']
            run_ids = xrange(0, num)
            print('++++ Number of noise realisations {} ++++++'.format(num))

        # setting the undulator design( Magnetic Lattice)
    A_undulator = undulator_design(A_input)

    # Fill in the beam object
    A_beam = BeamDefinition(A_input)
    if (A_input['itdp'] == 0):
        print('++++ Steady State run +++++')
        i_tdp = False
    elif (A_input['itdp'] == 1):
        i_tdp = True

        # Generate input object
    inp = generate_input(A_undulator['Undulator Parameters'],
                         A_beam,
                         itdp=i_tdp)

    # Overwrite the simulation attributes of the input object with the ones defined in the input file
    for in_put in A_input:
        if (in_put in A_simul) or (in_put in A_und) or (in_put in A_td) or (
                in_put == 'xlamds'):
            setattr(inp, in_put, A_input[in_put])
        else:
            continue
    # Set up some input parameters
    setattr(inp, 'f1st', int(getattr(inp, 'fl') / 2))
    setattr(inp, 'awd', float(getattr(inp, 'aw0')))
    if A_input['in_gen'] == 1:
        setattr(inp, 'zstop', 0)
        setattr(inp, 'nbins', A_input['nbins'])
        # Set the object for a flat-top or Gaussian Current distribution
    if int(A_input['i_profile']) == 1:
        setattr(inp, 'nslice', 8 * int(inp.curlen / inp.zsep / inp.xlamds))
        setattr(inp, 'ntail', -getattr(inp, 'nslice') / 2)
    elif int(A_input['i_profile']) == 0:
        setattr(inp, 'nslice', int(inp.curlen / inp.zsep / inp.xlamds))
        setattr(inp, 'curlen', -getattr(inp, 'curlen'))
        setattr(inp, 'ntail', 0)
    else:
        print(
            '++++ Profile not set to be square (i_profile = 0) or Gaussian (i_profile=1) +++++++++++'
        )
        return

    # Running over noise realisations and/or scan parameters
    for n_par in s_scan:
        for run_id in run_ids:
            inp.runid = run_id
            #inp.ipseed = 17111*(int(inp.runid)+1)
            if ((A_input['stat_run'] == 1) or (A_input['i_scan'] == 1)):
                setattr(inp, 'ipseed', -1)
            else:
                setattr(inp, 'ipseed', np.random.randint(9999))
            inp.run_dir = exp_dir + 'scan_' + str(n_par) + '/ip_seed_' + str(
                inp.ipseed) + '/'
            inp_path = inp.run_dir + 'run.' + str(inp.runid) + '.inp'
            inp_file = filename_from_path(inp_path)
            try:
                os.makedirs(inp.run_dir)
            except OSError as exc:
                if (exc.errno == errno.EEXIST) and os.path.isdir(
                        exp_dir + 'scan' + str(n_par) + '/run_' + str(run_id)):
                    pass
                else:
                    raise

            if A_input['i_scan'] == 1:
                if (A_input['parameter'] in A_simul):
                    setattr(inp, A_input['parameter'][1:-1], n_par)
                    inp.lat = A_undulator['Magnetic Lattice']
                    print(' ++++++++++ Scan {} of the parameter {}'.format(
                        n_par, A_input['parameter']))
                elif ((A_input['parameter'] in A_und)
                      or (A_input['parameter'] == 'xlamds')):
                    print(
                        ' ++++++++++ Steady State Scan {} of the parameter {} Quad optimisation'
                        .format(n_par, A_input['parameter']))
                    setattr(inp, 'type', 'steady')
                    setattr(inp, 'itdp', 0)
                    setattr(inp, 'shotnoise', 0)
                    setattr(inp, 'prad0', 10)
                    setattr(inp, 'betamatch', True)
                    if (A_input['parameter'] in A_und):
                        if A_input['parameter'] == 'aw0':
                            A_input[str(A_input['parameter'])] = n_par
                            A_input[str(A_input['awd'])] = n_par
                        else:
                            n_par = int(n_par)
                            if A_input['parameter'] in A_und[0:2]:
                                for j_quad in A_und[0:2]:
                                    if j_quad == 'quadd':
                                        n_par = -n_par
                                    else:
                                        n_par = n_par
                                    A_input[str(j_quad)] = n_par
                            else:
                                A_input[str(A_input['parameter'])] = n_par
                    else:
                        n_par = float(n_par)
                        A_input[str(A_input['parameter'])] = n_par
                    A_undulator = undulator_design(A_input)
                    inp.lat = A_undulator['Magnetic Lattice']
                    inp.latticefile = inp_file + '.lat'
                    inp = beta_matching(inp, inp.run_dir)
                    inp.latticefile = None
                else:
                    n_par = float(n_par)
                    A_input[str(A_input['parameter'])] = n_par
                    setattr(inp, str(A_input['parameter']), n_par)
                    inp.lat = A_undulator['Magnetic Lattice']
            else:
                inp.lat = A_undulator['Magnetic Lattice']

            launcher = get_genesis_launcher(A_input['genesis_launcher'][1:-1])
            print('+++++ Starting simulation of noise realisation {}'.format(
                run_id))
            g = run_genesis(inp, launcher)
            setattr(g, 'filePath', str(inp.run_dir))
            if (inp.itdp == 1):
                fig = plot_gen_out_all(handle=g,
                                       savefig=True,
                                       showfig=False,
                                       choice=(1, 1, 1, 1, 6.05, 0, 0, 0, 0, 0,
                                               0, 0, 0),
                                       vartype_dfl=complex128,
                                       debug=1)
            inp.latticefile = None
            inp.outputfile = None

#Post- processing
# Setting off LaTeX in order to avoid the error when a plot is generated.
    print('+++++ Post-processing +++++++++++++++++++')
    plt.rcParams['text.usetex'] = False
    plt.rcParams['text.latex.unicode'] = False
    if (A_input['i_scan'] == 0):
        if (A_input['stat_run'] > 1):
            print(
                '++++++++Statistical runs (results saved in {}results) ++++++'.
                format(exp_dir))
            fig2 = plot_gen_stat(exp_dir,
                                 run_inp=s_scan,
                                 stage_inp=xrange(1),
                                 param_inp=[],
                                 s_param_inp=[
                                     'p_int', 'energy', 'xrms', 'yrms',
                                     'bunching', 'r_size_weighted', 'spec',
                                     'error'
                                 ],
                                 z_param_inp=[
                                     'p_int', 'phi_mid_disp', 'xrms', '#yrms',
                                     'spec', 'bunching', 'wigner'
                                 ],
                                 dfl_param_inp=[],
                                 run_param_inp=[],
                                 s_inp=['max', 'mean'],
                                 z_inp=[0, 'end'],
                                 run_s_inp=[],
                                 run_z_inp=[],
                                 savefig=True,
                                 saveval=False,
                                 debug=0)
        elif (A_input['stat_run'] == 1):
            print('++++++++ Single run (results saved in {}results) ++++++'.
                  format(exp_dir))
            if (A_input['itdp'] == 0):
                i_tdp = False
            else:
                i_tdp = True
            fig = gen_outplot_single(exp_dir,
                                     run_inp=s_scan,
                                     itdp=i_tdp,
                                     savefig=True)
    else:
        print(
            '++++++++scan (results saved in {}results) ++++++'.format(exp_dir))
        fig = gen_outplot_single(exp_dir,
                                 run_inp=s_scan,
                                 itdp=False,
                                 savefig=True)