def optimise_Lattice(phase=None, q=70, do_optimisation=False): global dir, lattice, scaling, bestdelta bestdelta = 1e10 dir = './SETUP/TOMP_SETUP' lattice = Framework(dir, clean=False, verbose=False) lattice.loadSettings('CLA10-FE.def') lattice.modifyElement('CLA-L01-CAV-SOL-01', 'field_amplitude', 0.07) lattice.modifyElement('CLA-L01-CAV-SOL-02', 'field_amplitude', -0.05) scaling = 6 if not os.name == 'nt': lattice.defineASTRACommand(scaling=(scaling)) lattice.defineCSRTrackCommand(scaling=(scaling)) lattice.define_gpt_command(scaling=(scaling)) # lattice['L01'].file_block['input']['prefix'] = '../../CLARA_BA1_Gaussian/basefiles_'+str(scaling)+'_'+str(q)+'/' quads = [ lattice.getElement('CLA-S02-MAG-QUAD-01', 'k1l'), lattice.getElement('CLA-S02-MAG-QUAD-02', 'k1l'), lattice.getElement('CLA-S02-MAG-QUAD-03', 'k1l'), lattice.getElement('CLA-S02-MAG-QUAD-04', 'k1l'), lattice.getElement('CLA-S02-MAG-QUAD-05', 'k1l'), ] quads = np.array([ 2.018036284043403, -1.6775106326141502, 2.0713066380968943, -1.4092617257511626, 0.07875236608471231 ]) lattice['S02'].sample_interval = 8 if do_optimisation: if phase is not None: lattice['S02'].file_block['input'][ 'prefix'] = '../TOMP_SETUP_' + str(phase) + '_' + str(q) + '/' quads = setVELA(quads) optFuncVELA(quads) print('VELA = ', quads) lattice['S02'].sample_interval = 1 #2**(3*2)
def create_base_files(scaling, charge=70): framework = Framework('basefiles_' + str(scaling) + '_' + str(charge), overwrite=True, clean=True) framework.loadSettings('CLA10-BA1_TOMP_ASTRA.def') if not os.name == 'nt': framework.defineASTRACommand(scaling=(scaling)) framework.defineCSRTrackCommand(scaling=(scaling)) framework.generator.number_of_particles = 2**(3 * scaling) framework.modifyElement('CLA-LRG1-GUN-CAV', 'phase', -5) framework['generator'].charge = charge * 1e-12 # before_tracking() framework.track(files=['generator', 'injector10'])
def create_base_files(scaling): framework = Framework('basefiles_' + str(scaling), overwrite=True, clean=True) framework.loadSettings('CLA10-BA1_TOMP.def') if not os.name == 'nt': framework.defineASTRACommand( ['mpiexec', '-np', str(3 * scaling), '/opt/ASTRA/astra_MPICH2.sh']) framework.defineGeneratorCommand(['/opt/ASTRA/generator.sh']) framework.defineCSRTrackCommand([ '/opt/OpenMPI-1.4.3/bin/mpiexec', '-n', str(3 * scaling), '/opt/CSRTrack/csrtrack_openmpi.sh' ]) framework.generator.number_of_particles = 2**(3 * scaling) framework.modifyElement('CLA-LRG1-GUN-CAV', 'phase', -5) framework.track(files=['generator', 'injector10'])
def optimise_Lattice(): global dir, lattice dir = './TOMP_SETUP_DBURT' lattice = Framework(dir, clean=False, verbose=False) lattice.loadSettings('CLA10-BA1_TOMP.def') scaling = 5 if not os.name == 'nt': lattice.defineASTRACommand( ['mpiexec', '-np', str(3 * scaling), '/opt/ASTRA/astra_MPICH2.sh']) # lattice.defineASTRACommand(['/opt/ASTRA/astra.sh']) lattice.defineGeneratorCommand(['/opt/ASTRA/generator.sh']) lattice.defineCSRTrackCommand([ '/opt/OpenMPI-1.4.3/bin/mpiexec', '-n', str(3 * scaling), '/opt/CSRTrack/csrtrack_openmpi.sh' ]) lattice.defineElegantCommand(['elegant']) # lattice.defineElegantCommand(['mpiexec','-np','6','Pelegant']) scaling = 5 lattice['L01'].file_block['input']['prefix'] = '../basefiles_' + str( scaling) + '/' client = unitsC.zmqClient() namesK = client.getNamesK(DBURT='CLARA_2_BA1_BA2_2018-11-20-1951.dburt') for name, param, k in namesK: if param is not None: if str(name) in lattice.elementObjects.keys(): print name, param, k lattice.modifyElement(str(name), str(param), float(k)) # exit() # quads = [ 21.11058462, -11.36377551, 24.69336696, -22.63264054, 56.07039682, -51.58739658] quads = [-13.84327193, -2.92364597, 18.55449508, -18.53314705] quads = setChicane(quads) optFuncChicane(quads) print 'Chicane = ', quads # lattice.modifyElement('EBT-BA1-MAG-QUAD-01', 'k1', -1.22) # lattice.modifyElement('EBT-BA1-MAG-QUAD-02', 'k1', 2.18) # lattice.modifyElement('EBT-BA1-MAG-QUAD-03', 'k1', -1.22) lattice['S02'].file_block['output']['end_element'] = 'EBT-BA1-COFFIN-FOC'
framework.defineASTRACommand( ['mpiexec', '-np', str(ncpu), '/opt/ASTRA/astra_MPICH2.sh']) framework.defineCSRTrackCommand([ '/opt/OpenMPI-1.4.3/bin/mpiexec', '-n', str(ncpu), '/opt/CSRTrack/csrtrack_openmpi.sh' ]) framework.defineElegantCommand(['elegant']) framework.loadSettings('Lattices/CLA10-BA1.def') framework.change_Lattice_Code('All', 'elegant') framework['S02'].prefix = '../../basefiles_4/' etax = [] etax2 = [] kValues = np.arange(0, 3, 0.1) for k in kValues: #np.arange(0,1,0.1): print('setting k = ', k) framework.modifyElement('EBT-BA1-MAG-QUAD-07', 'k1l', k) framework.track(startfile='S02', endfile='BA1_dipole') twiss.reset_dicts() twiss.read_sdds_file(basedir + '/BA1_dipole.mat') etax.append(twiss.elegant['R16'][-1]) etax2.append(twiss.elegant['T166'][-1]) print(k, twiss.elegant['R16'][-1], twiss.elegant['T166'][-1], twiss.elegant['R16'][-1] / twiss.elegant['T166'][-1]) data = zip(kValues, etax, etax2, np.array(etax) / np.array(etax2)) with open('dispersion.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(data)
class fitnessFunc(): def __init__(self, args, tempdir, scaling=4, overwrite=True, verbose=False, summary=False, post_injector=True): self.cons = constraintsClass() self.beam = rbf.beam() self.twiss = rtf.twiss() self.scaling = scaling self.tmpdir = tempdir self.verbose = verbose self.summary = summary self.overwrite = overwrite self.post_injector = post_injector # print 'self.post_injector = ', self.post_injector ''' if only post-injector optimisation''' if self.post_injector: linac2field, linac2phase, linac3field, linac3phase, fhcfield, fhcphase, linac4field, linac4phase, bcangle = args self.parameters = dict( zip([ 'linac2field', 'linac2phase', 'linac3field', 'linac3phase', 'fhcfield', 'fhcphase', 'linac4field', 'linac4phase', 'bcangle' ], args)) else: ''' including injector parameters ''' gunphase, gunsol, linac1field, linac1phase, linac1sol1, linac1sol2, linac2field, linac2phase, linac3field, linac3phase, fhcfield, fhcphase, linac4field, linac4phase, bcangle = args self.parameters = dict( zip([ 'gunphase', 'gunsol', 'linac1field', 'linac1phase', 'linac1sol1', 'linac1sol2', 'linac2field', 'linac2phase', 'linac3field', 'linac3phase', 'fhcfield', 'fhcphase', 'linac4field', 'linac4phase', 'bcangle' ], args)) self.npart = 2**(3 * scaling) ncpu = scaling * 3 if self.post_injector: self.sbandlinacfields = np.array( [linac2field, linac3field, linac4field]) else: self.sbandlinacfields = np.array( [linac1field, linac2field, linac3field, linac4field]) self.dirname = os.path.basename(self.tmpdir) self.framework = Framework(self.dirname, overwrite=overwrite, verbose=verbose) if not os.name == 'nt': self.framework.defineGeneratorCommand(['/opt/ASTRA/generator']) self.framework.defineASTRACommand( ['mpiexec', '-np', str(ncpu), '/opt/ASTRA/astra_MPICH2.sh']) self.framework.defineCSRTrackCommand([ '/opt/OpenMPI-1.4.3/bin/mpiexec', '-n', str(ncpu), '/opt/CSRTrack/csrtrack_openmpi.sh' ]) self.framework.defineElegantCommand(['elegant']) self.framework.loadSettings('Lattices/clara400_v12_v3.def') if not self.post_injector: self.framework.generator.particles = self.npart self.framework.modifyElement('CLA-HRG1-GUN-CAV', 'phase', gunphase) self.framework.modifyElement('CLA-HRG1-GUN-SOL', 'field_amplitude', gunsol) self.framework.modifyElement('CLA-L01-CAV', 'field_amplitude', abs(linac1field)) self.framework.modifyElement('CLA-L01-CAV', 'phase', linac1phase) self.framework.modifyElement('CLA-L01-CAV-SOL-01', 'field_amplitude', linac1sol1) self.framework.modifyElement('CLA-L01-CAV-SOL-02', 'field_amplitude', linac1sol2) self.framework.modifyElement('CLA-L02-CAV', 'field_amplitude', abs(linac2field)) self.framework.modifyElement('CLA-L02-CAV', 'phase', linac2phase) self.framework.modifyElement('CLA-L03-CAV', 'field_amplitude', abs(linac3field)) self.framework.modifyElement('CLA-L03-CAV', 'phase', linac3phase) self.framework.modifyElement('CLA-L4H-CAV', 'field_amplitude', abs(fhcfield)) self.framework.modifyElement('CLA-L4H-CAV', 'phase', fhcphase) self.framework.modifyElement('CLA-L04-CAV', 'field_amplitude', abs(linac4field)) self.framework.modifyElement('CLA-L04-CAV', 'phase', linac4phase) self.framework['bunch_compressor'].set_angle(abs(bcangle)) def between(self, value, minvalue, maxvalue, absolute=True): if absolute: result = max([minvalue, min([maxvalue, abs(value)])]) else: result = np.sign(value) * max( [minvalue, min([maxvalue, abs(value)])]) return result def calculateBeamParameters(self): bcangle = self.framework['bunch_compressor'].angle # print 'bcangle = ', bcangle try: # if abs(bcangle) < 0.01 or abs(bcangle) > 0.175: # raise ValueError if self.overwrite: startS = self.framework['S02'].startObject['position_start'][2] if self.post_injector: self.framework['S02'].file_block['input'][ 'prefix'] = '../basefiles_' + str(self.scaling) + '/' self.framework.track(startfile='S02', endfile='S07') #startfile='FMS') else: self.framework.track(endfile='S07') # self.beam.read_astra_beam_file(self.dirname+'/S07.4928.001') self.beam.read_HDF5_beam_file(self.dirname + '/CLA-S07-MARK-03.hdf5') self.beam.slices = 10 self.beam.bin_time() sigmat = 1e12 * np.std(self.beam.t) sigmap = np.std(self.beam.p) meanp = np.mean(self.beam.p) emitx = 1e6 * self.beam.normalized_mve_horizontal_emittance emity = 1e6 * self.beam.normalized_mve_horizontal_emittance density = self.beam.density fitp = 100 * sigmap / meanp fhcfield = self.parameters['fhcfield'] peakI, peakIMomentumSpread, peakIEmittanceX, peakIEmittanceY, peakIMomentum, peakIDensity = self.beam.mvesliceAnalysis( ) chirp = self.beam.chirp constraintsList = { 'peakI_min': { 'type': 'greaterthan', 'value': abs(peakI), 'limit': 600, 'weight': 60 }, 'peakI_max': { 'type': 'lessthan', 'value': abs(peakI), 'limit': 750, 'weight': 10 }, # 'peakIMomentumSpread': {'type': 'lessthan', 'value': peakIMomentumSpread, 'limit': 0.1, 'weight': 2}, # 'peakIEmittanceX': {'type': 'lessthan', 'value': 1e6*peakIEmittanceX, 'limit': 0.75, 'weight': 5}, # 'peakIEmittanceY': {'type': 'lessthan', 'value': 1e6*peakIEmittanceY, 'limit': 0.75, 'weight': 5}, 'peakIMomentum': { 'type': 'equalto', 'value': 1e-6 * peakIMomentum, 'limit': 220, 'weight': 20 }, 'sband_linac fields': { 'type': 'lessthan', 'value': 1e-6 * self.sbandlinacfields, 'limit': 32, 'weight': 200 }, # 'xband_linac fields': {'type': 'lessthan', 'value': 1e-6*self.xbandlinacfields, 'limit': 100, 'weight': 100}, '4hc field': { 'type': 'lessthan', 'value': 1e-6 * fhcfield, 'limit': 35, 'weight': 100 }, # 'horizontal emittance': {'type': 'lessthan', 'value': emitx, 'limit': 2, 'weight': 0}, # 'vertical emittance': {'type': 'lessthan', 'value': emity, 'limit': 2, 'weight': 0}, # 'momentum_spread': {'type': 'lessthan', 'value': fitp, 'limit': 0.1, 'weight': 2}, 'chirp': { 'type': 'equalto', 'value': abs(chirp), 'limit': 0.75, 'weight': 5 }, 'correct_chirp': { 'type': 'lessthan', 'value': chirp, 'limit': 0, 'weight': 100 }, 'peakI_volume': { 'type': 'greaterthan', 'value': peakIDensity, 'limit': 1e32, 'weight': 5 }, 'volume': { 'type': 'greaterthan', 'value': density, 'limit': 1e30, 'weight': 5 }, } # self.twiss.read_astra_emit_files(self.dirname+'/S07.Zemit.001') # constraintsList5 = { # 'last_exn_5': {'type': 'lessthan', 'value': 1e6*self.twiss['enx'], 'limit': 0.75, 'weight': 1}, # 'last_eyn_5': {'type': 'lessthan', 'value': 1e6*self.twiss['eny'], 'limit': 0.75, 'weight': 1}, # } # constraintsList = merge_two_dicts(constraintsList, constraintsList5) fitness = self.cons.constraints(constraintsList) if self.verbose: print self.cons.constraintsList(constraintsList) if self.summary: np.save('summary_constraints.txt', self.cons.constraintsList(constraintsList)) # self.astra.createHDF5Summary(reference='Longitudinal_GA') print fitness, 1e-6 * peakIMomentum, abs( peakI ), 1e6 * peakIEmittanceX, 1e6 * peakIEmittanceY, chirp, peakIDensity, density return fitness except Exception as e: print(e) return 1e6
class fitnessFunc(): def __init__(self, args, tempdir, scaling=5, overwrite=True, verbose=False, summary=False, post_injector=True): self.cons = constraintsClass() self.beam = rbf.beam() self.scaling = scaling self.tmpdir = tempdir self.verbose = verbose self.summary = summary self.overwrite = overwrite self.post_injector = post_injector ''' if only post-injector optimisation''' if self.post_injector: linac2field, linac2phase, linac3field, linac3phase, fhcfield, fhcphase, linac4field, linac4phase, bcangle = args self.parameters = dict( zip([ 'linac2field', 'linac2phase', 'linac3field', 'linac3phase', 'fhcfield', 'fhcphase', 'linac4field', 'linac4phase', 'bcangle' ], args)) else: ''' including injector parameters ''' gunphase, gunsol, linac1field, linac1phase, linac1sol1, linac1sol2, linac2field, linac2phase, linac3field, linac3phase, fhcfield, fhcphase, linac4field, linac4phase, bcangle = args self.parameters = dict( zip([ 'gunphase', 'gunsol', 'linac1field', 'linac1phase', 'linac1sol1', 'linac1sol2', 'linac2field', 'linac2phase', 'linac3field', 'linac3phase', 'fhcfield', 'fhcphase', 'linac4field', 'linac4phase', 'bcangle' ], args)) self.npart = 2**(3 * scaling) ncpu = scaling * 3 if self.post_injector: self.sbandlinacfields = np.array( [linac2field, linac3field, linac4field]) else: self.sbandlinacfields = np.array( [linac1field, linac2field, linac3field, linac4field]) self.dirname = os.path.basename(self.tmpdir) self.framework = Framework(self.dirname, overwrite=overwrite, verbose=verbose) if not os.name == 'nt': self.framework.defineGeneratorCommand(['/opt/ASTRA/generator']) self.framework.defineASTRACommand( ['mpiexec', '-np', str(ncpu), '/opt/ASTRA/astra_MPICH2.sh']) self.framework.defineCSRTrackCommand([ '/opt/OpenMPI-1.4.3/bin/mpiexec', '-n', str(ncpu), '/opt/CSRTrack/csrtrack_openmpi.sh' ]) self.framework.defineElegantCommand(['elegant']) self.framework.loadSettings('Lattices/clara400_v12_v3_elegant.def') if not self.post_injector: self.framework.generator.particles = self.npart self.framework.modifyElement('CLA-HRG1-GUN-CAV', 'phase', gunphase) self.framework.modifyElement('CLA-HRG1-GUN-SOL', 'field_amplitude', gunsol) self.framework.modifyElement('CLA-L01-CAV', 'field_amplitude', abs(linac1field)) self.framework.modifyElement('CLA-L01-CAV', 'phase', linac1phase) self.framework.modifyElement('CLA-L01-CAV-SOL-01', 'field_amplitude', linac1sol1) self.framework.modifyElement('CLA-L01-CAV-SOL-02', 'field_amplitude', linac1sol2) self.framework.modifyElement('CLA-L02-CAV', 'field_amplitude', abs(linac2field)) self.framework.modifyElement('CLA-L02-CAV', 'phase', linac2phase) self.framework.modifyElement('CLA-L03-CAV', 'field_amplitude', abs(linac3field)) self.framework.modifyElement('CLA-L03-CAV', 'phase', linac3phase) self.framework.modifyElement('CLA-L4H-CAV', 'field_amplitude', abs(fhcfield)) self.framework.modifyElement('CLA-L4H-CAV', 'phase', fhcphase) self.framework.modifyElement('CLA-L04-CAV', 'field_amplitude', abs(linac4field)) self.framework.modifyElement('CLA-L04-CAV', 'phase', linac4phase) self.framework['bunch_compressor'].set_angle(abs(bcangle)) def calculateBeamParameters(self): try: if self.post_injector: self.framework['POSTINJ'].file_block['input'][ 'prefix'] = '../basefiles_' + str(self.scaling) + '/' self.framework.track(startfile='POSTINJ') else: self.framework.track() #startfile='FMS') self.beam.read_HDF5_beam_file(self.dirname + '/CLA-FMS-APER-01.hdf5') ## CONVERT THIS TO A DIST FILE!!! except Exception as e: print(e) return 1e6