From abf31369757aa671d8029d1a8f15ec387e4fe57d Mon Sep 17 00:00:00 2001 From: giadarol Date: Mon, 29 Jul 2019 15:16:24 +0200 Subject: [PATCH 01/12] Load from file function --- gen_multibunch_beam.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/gen_multibunch_beam.py b/gen_multibunch_beam.py index d7451d4..6c5a1b3 100644 --- a/gen_multibunch_beam.py +++ b/gen_multibunch_beam.py @@ -55,3 +55,17 @@ def gen_matched_multibunch_beam(machine, n_macroparticles_per_bunch, filling_pat bb.slice_info['i_turn'] = 0 return list_bunches + +def load_multibunch_beam(dirname): + import PyPARIS.myfilemanager as mfm + print('Loading the beam from %s'%dirname) + bzero = ch.buffer_2_beam(mfm.dict_of_arrays_and_scalar_from_h5( + dirname+'/bunch0.h5')['bunchbuffer']) + N_bunches_tot_beam = bzero.slice_info['N_bunches_tot_beam'] + list_bunches = [bzero] + for ibun in xrange(1, N_bunches_tot_beam): + list_bunches.append(ch.buffer_2_beam( + mfm.dict_of_arrays_and_scalar_from_h5( + dirname+'/bunch%d.h5'%ibun)['bunchbuffer'])) + list_bunches = list_bunches[::-1] # We want the last bunch to be in pos 0 + return list_bunches From 82c8e520ca479b893148c13146126ce7ee6b0a03 Mon Sep 17 00:00:00 2001 From: giadarol Date: Tue, 30 Jul 2019 11:13:49 +0200 Subject: [PATCH 02/12] Dump and load beam from/to folder --- gen_multibunch_beam.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/gen_multibunch_beam.py b/gen_multibunch_beam.py index 6c5a1b3..4843466 100644 --- a/gen_multibunch_beam.py +++ b/gen_multibunch_beam.py @@ -1,3 +1,5 @@ +import os + from scipy.constants import c as clight, e as qe import numpy as np @@ -56,9 +58,13 @@ def gen_matched_multibunch_beam(machine, n_macroparticles_per_bunch, filling_pat return list_bunches -def load_multibunch_beam(dirname): + +def load_multibunch_beam(dirname, reset_i_turns=True): import PyPARIS.myfilemanager as mfm + import PyPARIS.communication_helpers as ch + print('Loading the beam from %s'%dirname) + bzero = ch.buffer_2_beam(mfm.dict_of_arrays_and_scalar_from_h5( dirname+'/bunch0.h5')['bunchbuffer']) N_bunches_tot_beam = bzero.slice_info['N_bunches_tot_beam'] @@ -67,5 +73,24 @@ def load_multibunch_beam(dirname): list_bunches.append(ch.buffer_2_beam( mfm.dict_of_arrays_and_scalar_from_h5( dirname+'/bunch%d.h5'%ibun)['bunchbuffer'])) + list_bunches = list_bunches[::-1] # We want the last bunch to be in pos 0 + if reset_i_turns: + for bb in list_bunches: + bb.slice_info['i_turn'] = 0 + return list_bunches + + +def save_bunch_to_folder(bunch, dirname): + import PyPARIS.myfilemanager as mfm + import PyPARIS.communication_helpers as ch + if not os.path.exists(dirname): + os.makedirs(dirname) + buf = ch.beam_2_buffer(bunch) + bpath = dirname+'/bunch%d.h5'%bunch.slice_info['i_bunch'] + print('Saving: ' + bpath) + mfm.dict_to_h5(dict_save={'bunchbuffer':buf}, + filename=bpath) + + From 5b8c441f716d2ed7035019092a108892ea4e0cd5 Mon Sep 17 00:00:00 2001 From: lmether Date: Tue, 30 Jul 2019 13:06:29 +0200 Subject: [PATCH 03/12] Updated myfilemanager --- myfilemanager.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/myfilemanager.py b/myfilemanager.py index a1dee4b..524d459 100644 --- a/myfilemanager.py +++ b/myfilemanager.py @@ -59,31 +59,36 @@ def monitorh5_to_dict(filename, key= 'Bunch'): def monitorh5_to_obj(filename, key= 'Bunch'): return obj_from_dict(monitorh5_to_dict(filename, key)) -def monitorh5list_to_dict(filename_list, key='Bunch', permissive=False): +def monitorh5list_to_dict(filename_list, key='Bunch', flag_transpose=False, permissive=False): monitor_dict = monitorh5_to_dict(filename_list[0], key=key) - for i_file in xrange(1,len(filename_list)): + for i_file in xrange(1, len(filename_list)): print('Loading '+filename_list[i_file]) try: - monitor_dict_curr = monitorh5_to_dict(filename_list[i_file]) - for kk in monitor_dict.keys(): - monitor_dict[kk] = np.array(list(monitor_dict[kk])+list(monitor_dict_curr[kk])) + monitor_dict_curr = monitorh5_to_dict(filename_list[i_file], key=key) + if flag_transpose: + for kk in monitor_dict.keys(): + monitor_dict[kk] = np.array(list(monitor_dict[kk].T)+list(monitor_dict_curr[kk].T)).T + else: + for kk in monitor_dict.keys(): + monitor_dict[kk] = np.array(list(monitor_dict[kk])+list(monitor_dict_curr[kk])) except IOError as err: print('Got:') print(err) if not permissive: raise err - return monitor_dict + return monitor_dict -def monitorh5list_to_obj(filename_list, key= 'Bunch', permissive=False): - return obj_from_dict(monitorh5list_to_dict(filename_list, key, permissive)) +def monitorh5list_to_obj(filename_list, key= 'Bunch', flag_transpose=False, permissive=False): + return obj_from_dict(monitorh5list_to_dict(filename_list, key, flag_transpose, permissive)) -def dict_to_h5(dict_save, filename): +def dict_to_h5(dict_save, filename, compression=None, compression_opts=None): import h5py with h5py.File(filename, 'w') as fid: for kk in dict_save.keys(): - fid[kk] = dict_save[kk] + fid.create_dataset(kk, data=dict_save[kk], + compression=compression, compression_opts=compression_opts) From 66a79ce0a545286e176590796f9561064402915e Mon Sep 17 00:00:00 2001 From: lmether Date: Tue, 6 Aug 2019 12:46:06 +0200 Subject: [PATCH 04/12] pre_init_master untested!!! --- ring_of_CPUs_multiturn.py | 55 ++++++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/ring_of_CPUs_multiturn.py b/ring_of_CPUs_multiturn.py index 9bcc177..61098a7 100644 --- a/ring_of_CPUs_multiturn.py +++ b/ring_of_CPUs_multiturn.py @@ -145,7 +145,15 @@ def __init__(self, sim_content, N_pieces_per_transfer=1, force_serial = False, c self.comm.Barrier() self.verbose_mpi_out('After barrier 2 (cpu %d)'%self.comm.Get_rank()) - self.sim_content.init_all() + if hasattr(self.sim_content, 'pre_init_master'): + if self.I_am_the_master: + from_master = self.sim_content.pre_init_master() + else: + from_master = None + from_master = self._broadcast_from_master(from_master) + self.sim_content.init_all(from_master) + else: + self.sim_content.init_all() if self.enable_barriers: self.verbose_mpi_out('At barrier 3 (cpu %d)'%self.comm.Get_rank()) @@ -324,26 +332,7 @@ def run(self): if self.enable_orders_from_master: - if self.I_am_the_master: - # send orders - buforders = ch.list_of_strings_2_buffer(orders_from_master) - if len(buforders) > self.N_buffer_int_size: - raise ValueError('Int buffer is too small!') - self.buf_int = 0*self.buf_int - self.buf_int[:len(buforders)]=buforders - - self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) - self.comm.Bcast(self.buf_int, self.master_id) - self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) - - else: - # receive orders from the master - self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) - self.comm.Bcast(self.buf_int, self.master_id) - self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) - - orders_from_master = ch.buffer_2_list_of_strings(self.buf_int) - + self._broadcast_from_master(orders_from_master) # check if simulation has to be ended if 'stop' in orders_from_master: break @@ -373,3 +362,27 @@ def _print_some_info_on_comm(self, thisslice, iteration, t_start, t_end): print2logandstdo('Iter start on %s, iter%05d - I am %02d.%02d and I treated None, lasts %ds'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(t_start)), iteration, self.myring, self.myid_in_ring, t_end-t_start)) + + + def _broadcast_from_master(self, list_of_strings): + if self.I_am_the_master: + # send orders + buforders = ch.list_of_strings_2_buffer(list_of_strings) + if len(buforders) > self.N_buffer_int_size: + raise ValueError('Int buffer is too small!') + self.buf_int = 0*self.buf_int + self.buf_int[:len(buforders)] = buforders + + self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.comm.Bcast(self.buf_int, self.master_id) + self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + + else: + # receive orders from the master + self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.comm.Bcast(self.buf_int, self.master_id) + self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + + list_of_strings = ch.buffer_2_list_of_strings(self.buf_int) + + return list_of_strings From 83281aef8503085c39b122b3693c0019c968c9f3 Mon Sep 17 00:00:00 2001 From: lmether Date: Tue, 6 Aug 2019 13:55:59 +0200 Subject: [PATCH 05/12] Status --- communication_helpers.py | 4 ++-- ring_of_CPUs_multiturn.py | 31 ++++++++++++++++--------------- 2 files changed, 18 insertions(+), 17 deletions(-) diff --git a/communication_helpers.py b/communication_helpers.py index 6e3d640..e6930f9 100644 --- a/communication_helpers.py +++ b/communication_helpers.py @@ -31,13 +31,13 @@ def split_float_buffers(megabuffer): def list_of_strings_2_buffer(strlist): - data = ''.join(map(lambda s:s+';', strlist))+'\n' + data = ''.join(map(lambda s:s+';', strlist))+'\nendbuf\n' buf_to_send = np.atleast_1d(np.int_(np.array(map(ord, list(data))))) return buf_to_send def buffer_2_list_of_strings(buf): str_received = ''.join(map(unichr, list(buf))) - strlist = list(map(str, str_received.split('\n')[0].split(';')))[:-1] + strlist = list(map(str, str_received.split('\nendbuf\n')[0].split(';')))[:-1] return strlist diff --git a/ring_of_CPUs_multiturn.py b/ring_of_CPUs_multiturn.py index 61098a7..fb7f5d7 100644 --- a/ring_of_CPUs_multiturn.py +++ b/ring_of_CPUs_multiturn.py @@ -30,8 +30,9 @@ def __init__(self, sim_content, N_pieces_per_transfer=1, force_serial = False, c N_buffer_float_size = 1000000, N_buffer_int_size = 100, verbose = False, mpi_verbose = False, enable_barriers = False, enable_orders_from_master = True): - + + self.iteration = -1 self.sim_content = sim_content self.N_turns = sim_content.N_turns @@ -203,7 +204,7 @@ def __init__(self, sim_content, N_pieces_per_transfer=1, force_serial = False, c def run(self): - iteration = 0 + self.iteration = 0 list_received_buffers = [self.sim_content.piece_to_buffer(None)] while True: @@ -227,7 +228,7 @@ def run(self): if self.myring==0 and self.myid_in_ring == 0: t_now = time.mktime(time.localtime()) print2logandstdo('%s, iter%03d - cpu %d.%d startin bunch %d/%d turn=%d'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(t_now)), - iteration, self.myring, self.myid_in_ring, + self.iteration, self.myring, self.myid_in_ring, next_bunch.slice_info['i_bunch'], next_bunch.slice_info['N_bunches_tot_beam'], next_bunch.slice_info['i_turn'])) @@ -263,7 +264,7 @@ def run(self): if thisslice is not None: self.sim_content.treat_piece(thisslice) t_end = time.mktime(time.localtime()) - self._print_some_info_on_comm(thisslice, iteration, t_start, t_end) + self._print_some_info_on_comm(thisslice, t_start, t_end) ######################### @@ -309,10 +310,10 @@ def run(self): self.comm.Barrier() self.verbose_mpi_out('After barrier L1 (cpu %d)'%self.comm.Get_rank()) - self.verbose_mpi_out('At Sendrecv, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.verbose_mpi_out('At Sendrecv, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, self.iteration)) self.comm.Sendrecv(sendbuf, dest=self.right, sendtag=self.right, recvbuf=self.buf_float, source=self.left, recvtag=self.myid) - self.verbose_mpi_out('After Sendrecv, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.verbose_mpi_out('After Sendrecv, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, self.iteration)) if self.enable_barriers: self.verbose_mpi_out('At barrier L2 (cpu %d)'%self.comm.Get_rank()) @@ -342,24 +343,24 @@ def run(self): self.comm.Barrier() self.verbose_mpi_out('After barrier L4 (cpu %d)'%self.comm.Get_rank()) - iteration+=1 + self.iteration+=1 # (TEMPORARY!) To stop - # if iteration==10000: + # if self.iteration==10000: # break # (TEMPORARY!) - def _print_some_info_on_comm(self, thisslice, iteration, t_start, t_end): + def _print_some_info_on_comm(self, thisslice, t_start, t_end): if self.verbose: if thisslice is not None: - print2logandstdo('Iter start on %s, iter%05d - I am %02d.%02d and I treated slice %d/%d of bunch %d/%d, lasts %ds'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(t_start)), iteration, + print2logandstdo('Iter start on %s, iter%05d - I am %02d.%02d and I treated slice %d/%d of bunch %d/%d, lasts %ds'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(t_start)), self.iteration, self.myring, self.myid_in_ring, thisslice.slice_info['i_slice'], thisslice.slice_info['N_slices_tot_bunch'], thisslice.slice_info['info_parent_bunch']['i_bunch'], thisslice.slice_info['info_parent_bunch']['N_bunches_tot_beam'], t_end-t_start)) else: - print2logandstdo('Iter start on %s, iter%05d - I am %02d.%02d and I treated None, lasts %ds'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(t_start)), iteration, + print2logandstdo('Iter start on %s, iter%05d - I am %02d.%02d and I treated None, lasts %ds'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(t_start)), self.iteration, self.myring, self.myid_in_ring, t_end-t_start)) @@ -373,15 +374,15 @@ def _broadcast_from_master(self, list_of_strings): self.buf_int = 0*self.buf_int self.buf_int[:len(buforders)] = buforders - self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, self.iteration)) self.comm.Bcast(self.buf_int, self.master_id) - self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, self.iteration)) else: # receive orders from the master - self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.verbose_mpi_out('At Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, self.iteration)) self.comm.Bcast(self.buf_int, self.master_id) - self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, iteration)) + self.verbose_mpi_out('After Bcast, cpu %d/%d, iter %d'%(self.myid, self.N_nodes, self.iteration)) list_of_strings = ch.buffer_2_list_of_strings(self.buf_int) From accdefb1506aceea2cf19171531635cf32b35690 Mon Sep 17 00:00:00 2001 From: giadarol Date: Tue, 6 Aug 2019 15:53:14 +0200 Subject: [PATCH 06/12] Removed test (moved to PyECLOUD) --- test_kicks/000_run_sim_with_eclouds.sh | 10 - test_kicks/001_check_output.py | 103 --------- test_kicks/Simulation_with_eclouds.py | 216 ------------------ ...01_compare_kick_against_headtail_serial.py | 203 ---------------- test_kicks/cleanall | 6 - test_kicks/machines_for_testing.py | 126 ---------- test_kicks/mystyle.py | 27 --- test_kicks/pyecloud_config/LHC_chm_ver.mat | Bin 1200 -> 0 bytes .../pyecloud_config/machine_parameters.input | 10 - .../secondary_emission_parameters.input | 18 -- .../simulation_parameters.input | 63 ----- test_kicks/run_bologna_000 | 43 ---- 12 files changed, 825 deletions(-) delete mode 100644 test_kicks/000_run_sim_with_eclouds.sh delete mode 100644 test_kicks/001_check_output.py delete mode 100644 test_kicks/Simulation_with_eclouds.py delete mode 100644 test_kicks/a001_compare_kick_against_headtail_serial.py delete mode 100755 test_kicks/cleanall delete mode 100644 test_kicks/machines_for_testing.py delete mode 100644 test_kicks/mystyle.py delete mode 100755 test_kicks/pyecloud_config/LHC_chm_ver.mat delete mode 100755 test_kicks/pyecloud_config/machine_parameters.input delete mode 100755 test_kicks/pyecloud_config/secondary_emission_parameters.input delete mode 100755 test_kicks/pyecloud_config/simulation_parameters.input delete mode 100755 test_kicks/run_bologna_000 diff --git a/test_kicks/000_run_sim_with_eclouds.sh b/test_kicks/000_run_sim_with_eclouds.sh deleted file mode 100644 index d976785..0000000 --- a/test_kicks/000_run_sim_with_eclouds.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/bash - -# Run Parallel without MPI -# ../multiprocexec.py -n 3 sim_class=Simulation_with_eclouds.Simulation - -# Run Serial -#../serialexec.py sim_class=Simulation_with_eclouds.Simulation - -# Run MPI -mpiexec -n 4 ../withmpi.py sim_class=Simulation_with_eclouds.Simulation diff --git a/test_kicks/001_check_output.py b/test_kicks/001_check_output.py deleted file mode 100644 index af7b4cf..0000000 --- a/test_kicks/001_check_output.py +++ /dev/null @@ -1,103 +0,0 @@ -import sys -sys.path.append('../../') - -import numpy as np -import pylab as pl - -import PyPARIS.myfilemanager as mfm -import mystyle as ms - -import time - -n_segments = 3 -n_part_per_turn = 5000 -N_turns = 8 - -filename = '../../PyECLOUD/testing/tests_PyEC4PyHT/headtail_for_test/test_protons/SPS_Q20_proton_check_dipole_3kicks_20150212_prb.dat' -appo = np.loadtxt(filename) - -parid = np.reshape(appo[:,0], (-1, n_part_per_turn))[::n_segments,:] -x = np.reshape(appo[:,1], (-1, n_part_per_turn))[::n_segments,:] -xp = np.reshape(appo[:,2], (-1, n_part_per_turn))[::n_segments,:] -y = np.reshape(appo[:,3], (-1, n_part_per_turn))[::n_segments,:] -yp =np.reshape(appo[:,4], (-1, n_part_per_turn))[::n_segments,:] -z = np.reshape(appo[:,5], (-1, n_part_per_turn))[::n_segments,:] -zp = np.reshape(appo[:,6], (-1, n_part_per_turn))[::n_segments,:] - -rms_err_x_list = [] -rms_err_y_list = [] -for i_turn in xrange(N_turns-1): - - ob = mfm.object_with_arrays_and_scalar_from_h5('particles_at_turn_%d.h5'%i_turn) - - # sort id and momenta after track - - id_after = ob.id_after - xp_after = ob.xp_after - yp_after = ob.yp_after - z_after = ob.z_after - id_before = ob.id_before - xp_before = ob.xp_before - yp_before = ob.yp_before - - fig = pl.figure(100, figsize=(18,10)) - pl.clf() - sp1 = pl.subplot(2,3,1) - pl.plot(z_after, (100*np.abs((xp_after-xp_before)-(xp[i_turn+1, :]-xp[0, :]))/np.std(xp[i_turn+1, :]-xp[0, :])), '.r', markersize = 2) - pl.grid('on') - pl.ylabel('''error($\Delta$x')/$\Delta$x' [%]''') - pl.subplot(2,3,4, sharex=sp1) - pl.plot(z_after, (xp[i_turn+1, :]-xp[0, :]), '.r', label='HT', markersize = 2) - pl.plot(z_after, (xp_after-xp_before), '.b', label='PyHT', markersize = 2) - ms.sciy() - pl.grid('on') - pl.ylabel("$\Delta$x'") - pl.xlabel('z[m]') - pl.legend(prop = {'size':14}) - pl.subplot(2,3,3) - pl.hist((100*np.abs((xp_after-xp_before)-(xp[i_turn+1, :]-xp[0, :]))/np.std(xp[i_turn+1, :]-xp[0, :])), bins=100, range=(0,100)) - pl.xlabel('Error_x [%]') - pl.ylabel('Occurrences') - pl.xlim(0,100) - rms_err_x = np.std(100*np.abs((xp_after-xp_before)-(xp[i_turn+1, :]-xp[0, :]))/np.std(xp[i_turn+1, :]-xp[0, :])) - - sp1 = pl.subplot(2,3,2) - pl.plot(z_after, (100*np.abs((yp_after-yp_before)-(yp[i_turn+1, :]-yp[0, :]))/np.std(yp[i_turn+1, :]-yp[0, :])), '.r', markersize = 2) - pl.grid('on') - pl.ylabel('''error($\Delta$y')/$\Delta$y' [%]''') - pl.subplot(2,3,5, sharex=sp1) - pl.plot(z_after, (yp[i_turn+1, :]-yp[0, :]), '.r', label='HT', markersize = 2) - pl.plot(z_after, (yp_after-yp_before), '.b', label='PyHT', markersize = 2) - ms.sciy() - pl.grid('on') - pl.ylabel("$\Delta$y'") - pl.xlabel('z[m]') - pl.legend(prop = {'size':14}) - pl.subplot(2,3,6) - pl.hist((100*np.abs((yp_after-yp_before)-(yp[i_turn+1, :]-yp[0, :]))/np.std(yp[i_turn+1, :]-yp[0, :])), bins=100, range=(0,100)) - pl.xlim(0,100) - pl.xlabel('Error_y [%]') - pl.ylabel('Occurrences') - rms_err_y = np.std(100*np.abs((yp_after-yp_before)-(yp[i_turn+1, :]-yp[0, :]))/np.std(yp[i_turn+1, :]-yp[0, :])) - - - pl.suptitle('Turn %d rms_err_x = %e rms_err_y = %e'%(i_turn, rms_err_x, rms_err_y)) - - pl.savefig(filename.split('_prb.dat')[0]+'_%02d.png'%i_turn, dpi=150) - - rms_err_x_list.append(rms_err_x) - rms_err_y_list.append(rms_err_y) - - pl.ion() - pl.draw() - time.sleep(1.) - -pl.figure(1000) -pl.plot(rms_err_x_list, '.-', markersize = 10, linewidth=2, label='x') -pl.plot(rms_err_y_list, '.-', markersize = 10, linewidth=2, label='y') -pl.grid('on') -pl.ylabel('''Relative r.m.s. error [%]''') -pl.xlabel('Turn') -pl.legend() -pl.savefig(filename.split('_prb.dat')[0]+'_errors.png', dpi=200) -pl.show() diff --git a/test_kicks/Simulation_with_eclouds.py b/test_kicks/Simulation_with_eclouds.py deleted file mode 100644 index d51cab4..0000000 --- a/test_kicks/Simulation_with_eclouds.py +++ /dev/null @@ -1,216 +0,0 @@ -import sys, os -BIN = os.path.expanduser("../../") -sys.path.append(BIN) - -import numpy as np -from scipy.constants import c, e - -import PyPARIS.share_segments as shs -import PyPARIS.communication_helpers as ch - -# compute sigma x and y -epsn_x = 2.5e-6 -epsn_y = 2.5e-6 -B_multip = [0.5] -n_slices = 64 -n_segments = 3 - -filename = '../../PyECLOUD/testing/tests_PyEC4PyHT/headtail_for_test/test_protons/SPS_Q20_proton_check_dipole_3kicks_20150212_prb.dat' -B_multip = [0.5] -N_turns_to_simulate = 8 - - -class Simulation(object): - def __init__(self): - self.N_turns = N_turns_to_simulate - self.N_pieces_per_transfer=10 - - def init_all(self): - - - self.n_slices = n_slices - self.n_segments = n_segments - - from machines_for_testing import SPS - self.machine = SPS(n_segments = n_segments, - machine_configuration = 'Q20-injection', accQ_x=20., accQ_y=20., - RF_at='end_of_transverse') - - - # We suppose that all the object that cannot be slice parallelized are at the end of the ring - i_end_parallel = len(self.machine.one_turn_map)-1 #only RF is not parallelizable - - # split the machine - sharing = shs.ShareSegments(i_end_parallel, self.ring_of_CPUs.N_nodes) - myid = self.ring_of_CPUs.myid - i_start_part, i_end_part = sharing.my_part(myid) - self.mypart = self.machine.one_turn_map[i_start_part:i_end_part] - if self.ring_of_CPUs.I_am_a_worker: - print 'I am id=%d (worker) and my part is %d long'%(myid, len(self.mypart)) - elif self.ring_of_CPUs.I_am_the_master: - self.non_parallel_part = self.machine.one_turn_map[i_end_parallel:] - print 'I am id=%d (master) and my part is %d long'%(myid, len(self.mypart)) - - - # config e-cloud - init_unif_edens_flag=1 - init_unif_edens=2e11 - N_MP_ele_init = 100000 - N_mp_max = N_MP_ele_init*4. - - # define apertures and Dh_sc to simulate headtail - inj_optics = self.machine.transverse_map.get_injection_optics() - sigma_x = np.sqrt(inj_optics['beta_x']*epsn_x/self.machine.betagamma) - sigma_y = np.sqrt(inj_optics['beta_y']*epsn_y/self.machine.betagamma) - x_aper = 20*sigma_x - y_aper = 20*sigma_y - Dh_sc = 2*x_aper/128/2 - - # initial MP size - nel_mp_ref_0 = init_unif_edens*4*x_aper*y_aper/N_MP_ele_init - - import PyECLOUD.PyEC4PyHT as PyEC4PyHT - ecloud = PyEC4PyHT.Ecloud(slice_by_slice_mode=True, - L_ecloud=self.machine.circumference/n_segments, - slicer=None, - Dt_ref=25e-12, - pyecl_input_folder='../../PyECLOUD/testing/tests_PyEC4PyHT/drift_sim/', - x_aper=x_aper, y_aper=y_aper, Dh_sc=Dh_sc, - init_unif_edens_flag=init_unif_edens_flag, - init_unif_edens=init_unif_edens, - N_mp_max=N_mp_max, - nel_mp_ref_0=nel_mp_ref_0, - B_multip=B_multip) - - - my_new_part = [] - self.my_list_eclouds = [] - for ele in self.mypart: - my_new_part.append(ele) - if ele in self.machine.transverse_map: - ecloud_new = ecloud.generate_twin_ecloud_with_shared_space_charge() - my_new_part.append(ecloud_new) - self.my_list_eclouds.append(ecloud_new) - self.mypart = my_new_part - - def init_master(self): - - # beam parameters - sigma_z = 0.2 - intensity = 1.15e11 - macroparticlenumber_track = 300000 - - # initialization bunch - bunch = self.machine.generate_6D_Gaussian_bunch( - macroparticlenumber_track, intensity, epsn_x, epsn_y, sigma_z=sigma_z) - print 'Bunch initialized.' - - #replace particles with HDTL ones - self.n_part_per_turn = 5000 - appo = np.loadtxt(filename) - - parid = np.reshape(appo[:,0], (-1, self.n_part_per_turn))[::self.n_segments,:] - x = np.reshape(appo[:,1], (-1, self.n_part_per_turn))[::self.n_segments,:] - xp = np.reshape(appo[:,2], (-1, self.n_part_per_turn))[::self.n_segments,:] - y = np.reshape(appo[:,3], (-1, self.n_part_per_turn))[::self.n_segments,:] - yp =np.reshape(appo[:,4], (-1, self.n_part_per_turn))[::self.n_segments,:] - z = np.reshape(appo[:,5], (-1, self.n_part_per_turn))[::self.n_segments,:] - zp = np.reshape(appo[:,6], (-1, self.n_part_per_turn))[::self.n_segments,:] - - # replace first particles with HEADTAIL ones - bunch.x[:self.n_part_per_turn] = x[0,:] - bunch.xp[:self.n_part_per_turn] = xp[0,:] - bunch.y[:self.n_part_per_turn] = y[0,:] - bunch.yp[:self.n_part_per_turn] = yp[0,:] - bunch.z[:self.n_part_per_turn] = z[0,:] - bunch.dp[:self.n_part_per_turn] =zp[0,:] - - # save id and momenta before track - self.id_before = bunch.id[bunch.id<=self.n_part_per_turn] - self.xp_before = bunch.xp[bunch.id<=self.n_part_per_turn] - self.yp_before = bunch.yp[bunch.id<=self.n_part_per_turn] - - # initial slicing - from PyHEADTAIL.particles.slicing import UniformBinSlicer - self.slicer = UniformBinSlicer(n_slices = self.n_slices, n_sigma_z = 3.) - - self.rms_err_x_list = [] - self.rms_err_y_list = [] - - #slice for the first turn - slice_obj_list = bunch.extract_slices(self.slicer) - - pieces_to_be_treated = slice_obj_list - - print 'N_turns', self.N_turns - - return pieces_to_be_treated - - def init_worker(self): - pass - - def treat_piece(self, piece): - for ele in self.mypart: - ele.track(piece) - - def finalize_turn_on_master(self, pieces_treated): - - # re-merge bunch - bunch = sum(pieces_treated) - - #finalize present turn (with non parallel part, e.g. synchrotron motion) - for ele in self.non_parallel_part: - ele.track(bunch) - - # id and momenta after track - id_after = bunch.id[bunch.id<=self.n_part_per_turn] - xp_after = bunch.xp[bunch.id<=self.n_part_per_turn] - z_after = bunch.z[bunch.id<=self.n_part_per_turn] - yp_after = bunch.yp[bunch.id<=self.n_part_per_turn] - - # sort id and momenta after track - indsort = np.argsort(id_after) - id_after = np.take(id_after, indsort) - xp_after = np.take(xp_after, indsort) - yp_after = np.take(yp_after, indsort) - z_after = np.take(z_after, indsort) - - # save results - import PyPARIS.myfilemanager as mfm - mfm.dict_to_h5({\ - 'id_after': id_after, - 'xp_after': xp_after, - 'yp_after': yp_after, - 'z_after': z_after, - 'id_before':self.id_before, - 'xp_before':self.xp_before, - 'yp_before':self.yp_before}, - 'particles_at_turn_%d.h5'%self.ring_of_CPUs.i_turn) - - - # prepare next turn (re-slice) - new_pieces_to_be_treated = bunch.extract_slices(self.slicer) - orders_to_pass = ['reset_clouds'] - - return orders_to_pass, new_pieces_to_be_treated - - - def execute_orders_from_master(self, orders_from_master): - if 'reset_clouds' in orders_from_master: - for ec in self.my_list_eclouds: ec.finalize_and_reinitialize() - - - - def finalize_simulation(self): - pass - def piece_to_buffer(self, piece): - buf = ch.beam_2_buffer(piece) - return buf - - def buffer_to_piece(self, buf): - piece = ch.buffer_2_beam(buf) - return piece - - - - diff --git a/test_kicks/a001_compare_kick_against_headtail_serial.py b/test_kicks/a001_compare_kick_against_headtail_serial.py deleted file mode 100644 index 0cc30d7..0000000 --- a/test_kicks/a001_compare_kick_against_headtail_serial.py +++ /dev/null @@ -1,203 +0,0 @@ -import sys, os -BIN=os.path.expanduser('../../') -sys.path.append(BIN) - - -import numpy as np -import pylab as pl -import mystyle as ms -import time - -show_movie = False - - -filename = '../../PyECLOUD/testing/tests_PyEC4PyHT/headtail_for_test/test_protons/SPS_Q20_proton_check_dipole_3kicks_20150212_prb.dat' -B_multip = [0.5] -N_kicks = 3 - -n_part_per_turn = 5000 - -appo = np.loadtxt(filename) - -parid = np.reshape(appo[:,0], (-1, n_part_per_turn))[::N_kicks,:] -x = np.reshape(appo[:,1], (-1, n_part_per_turn))[::N_kicks,:] -xp = np.reshape(appo[:,2], (-1, n_part_per_turn))[::N_kicks,:] -y = np.reshape(appo[:,3], (-1, n_part_per_turn))[::N_kicks,:] -yp =np.reshape(appo[:,4], (-1, n_part_per_turn))[::N_kicks,:] -z = np.reshape(appo[:,5], (-1, n_part_per_turn))[::N_kicks,:] -zp = np.reshape(appo[:,6], (-1, n_part_per_turn))[::N_kicks,:] -N_turns = len(x[:,0]) - -pl.close('all') -ms.mystyle(fontsz=14) - - -# define machine for PyHEADTAIL -from PyHEADTAIL.particles.slicing import UniformBinSlicer -from machines_for_testing import SPS -machine = SPS(n_segments = N_kicks, machine_configuration = 'Q20-injection', accQ_x=20., accQ_y=20.) -#machine.one_turn_map.remove(machine.longitudinal_map) - - -# compute sigma x and y -epsn_x = 2.5e-6 -epsn_y = 2.5e-6 - -inj_optics = machine.transverse_map.get_injection_optics() -sigma_x = np.sqrt(inj_optics['beta_x']*epsn_x/machine.betagamma) -sigma_y = np.sqrt(inj_optics['beta_y']*epsn_y/machine.betagamma) - -# define apertures and Dh_sc to simulate headtail conditions -x_aper = 20*sigma_x -y_aper = 20*sigma_y -Dh_sc = 2*x_aper/128/2 -if show_movie: Dh_sc*=2 - -# ecloud -import PyECLOUD.PyEC4PyHT as PyEC4PyHT -from PyHEADTAIL.particles.slicing import UniformBinSlicer -slicer = UniformBinSlicer(n_slices = 64, n_sigma_z = 3.) - -init_unif_edens_flag=1 -init_unif_edens=2e11 -N_MP_ele_init = 100000 -N_mp_max = N_MP_ele_init*4. - -nel_mp_ref_0 = init_unif_edens*4*x_aper*y_aper/N_MP_ele_init - - -ecloud = PyEC4PyHT.Ecloud(L_ecloud=machine.circumference/N_kicks, slicer=slicer, - Dt_ref=25e-12, pyecl_input_folder='../../PyECLOUD/testing/tests_PyEC4PyHT/drift_sim/', - x_aper=x_aper, y_aper=y_aper, Dh_sc=Dh_sc, - init_unif_edens_flag=init_unif_edens_flag, - init_unif_edens=init_unif_edens, - N_mp_max=N_mp_max, - nel_mp_ref_0=nel_mp_ref_0, - B_multip=B_multip) -machine.install_after_each_transverse_segment(ecloud) - -if show_movie: - ecloud.save_ele_distributions_last_track = True - ecloud.save_ele_potential_and_field = True - -# generate a bunch -bunch = machine.generate_6D_Gaussian_bunch(n_macroparticles=300000, intensity=1.15e11, epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=0.2) - - -# replace first particles with HEADTAIL ones -bunch.x[:n_part_per_turn] = x[0,:] -bunch.xp[:n_part_per_turn] = xp[0,:] -bunch.y[:n_part_per_turn] = y[0,:] -bunch.yp[:n_part_per_turn] = yp[0,:] -bunch.z[:n_part_per_turn] = z[0,:] -bunch.dp[:n_part_per_turn] =zp[0,:] - -# save id and momenta before track -id_before = bunch.id[bunch.id<=n_part_per_turn] -xp_before = bunch.xp[bunch.id<=n_part_per_turn] -yp_before = bunch.yp[bunch.id<=n_part_per_turn] - -rms_err_x_list = [] -rms_err_y_list = [] -for ii in xrange(N_turns-1): - # track - machine.track(bunch)#, verbose = True) - print 'Turn', ii - - # id and momenta after track - id_after = bunch.id[bunch.id<=n_part_per_turn] - xp_after = bunch.xp[bunch.id<=n_part_per_turn] - z_after = bunch.z[bunch.id<=n_part_per_turn] - yp_after = bunch.yp[bunch.id<=n_part_per_turn] - - # sort id and momenta after track - indsort = np.argsort(id_after) - id_after = np.take(id_after, indsort) - xp_after = np.take(xp_after, indsort) - yp_after = np.take(yp_after, indsort) - z_after = np.take(z_after, indsort) - - fig = pl.figure(100, figsize=(18,10)) - pl.clf() - sp1 = pl.subplot(2,3,1) - pl.plot(z_after, (100*np.abs((xp_after-xp_before)-(xp[ii+1, :]-xp[0, :]))/np.std(xp[ii+1, :]-xp[0, :])), '.r', markersize = 2) - pl.grid('on') - pl.ylabel('''error($\Delta$x')/$\Delta$x' [%]''') - pl.subplot(2,3,4, sharex=sp1) - pl.plot(z_after, (xp[ii+1, :]-xp[0, :]), '.r', label='HT', markersize = 2) - pl.plot(z_after, (xp_after-xp_before), '.b', label='PyHT', markersize = 2) - ms.sciy() - pl.grid('on') - pl.ylabel("$\Delta$x'") - pl.xlabel('z[m]') - pl.legend(prop = {'size':14}) - pl.subplot(2,3,3) - pl.hist((100*np.abs((xp_after-xp_before)-(xp[ii+1, :]-xp[0, :]))/np.std(xp[ii+1, :]-xp[0, :])), bins=100, range=(0,100)) - pl.xlabel('Error_x [%]') - pl.ylabel('Occurrences') - pl.xlim(0,100) - rms_err_x = np.std(100*np.abs((xp_after-xp_before)-(xp[ii+1, :]-xp[0, :]))/np.std(xp[ii+1, :]-xp[0, :])) - - sp1 = pl.subplot(2,3,2) - pl.plot(z_after, (100*np.abs((yp_after-yp_before)-(yp[ii+1, :]-yp[0, :]))/np.std(yp[ii+1, :]-yp[0, :])), '.r', markersize = 2) - pl.grid('on') - pl.ylabel('''error($\Delta$y')/$\Delta$y' [%]''') - pl.subplot(2,3,5, sharex=sp1) - pl.plot(z_after, (yp[ii+1, :]-yp[0, :]), '.r', label='HT', markersize = 2) - pl.plot(z_after, (yp_after-yp_before), '.b', label='PyHT', markersize = 2) - ms.sciy() - pl.grid('on') - pl.ylabel("$\Delta$y'") - pl.xlabel('z[m]') - pl.legend(prop = {'size':14}) - pl.subplot(2,3,6) - pl.hist((100*np.abs((yp_after-yp_before)-(yp[ii+1, :]-yp[0, :]))/np.std(yp[ii+1, :]-yp[0, :])), bins=100, range=(0,100)) - pl.xlim(0,100) - pl.xlabel('Error_y [%]') - pl.ylabel('Occurrences') - rms_err_y = np.std(100*np.abs((yp_after-yp_before)-(yp[ii+1, :]-yp[0, :]))/np.std(yp[ii+1, :]-yp[0, :])) - - - pl.suptitle('Turn %d rms_err_x = %e rms_err_y = %e'%(ii, rms_err_x, rms_err_y)) - - pl.savefig(filename.split('_prb.dat')[0]+'_%02d.png'%ii, dpi=150) - - rms_err_x_list.append(rms_err_x) - rms_err_y_list.append(rms_err_y) - - pl.ion() - pl.draw() - time.sleep(1.) - -pl.figure(1000) -pl.plot(rms_err_x_list, '.-', markersize = 10, linewidth=2, label='x') -pl.plot(rms_err_y_list, '.-', markersize = 10, linewidth=2, label='y') -pl.grid('on') -pl.ylabel('''Relative r.m.s. error [%]''') -pl.xlabel('Turn') -pl.legend() -pl.savefig(filename.split('_prb.dat')[0]+'_errors.png', dpi=200) -pl.show() - -slices = bunch.get_slices(ecloud.slicer) -if show_movie: - n_frames = ecloud.rho_ele_last_track.shape[0] - pl.close(1) - pl.figure(1, figsize=(8,8)) - vmax = np.max(ecloud.rho_ele_last_track[:]) - vmin = np.min(ecloud.rho_ele_last_track[:]) - for ii in xrange(n_frames-1, 0, -1): - pl.subplot2grid((10,1),(0,0), rowspan=3) - pl.plot(slices.z_centers, np.float_(slices.n_macroparticles_per_slice)/np.max(slices.n_macroparticles_per_slice)) - pl.xlabel('z [m]');pl.ylabel('Long. profile') - pl.axvline(x = slices.z_centers[ii], color='r') - pl.subplot2grid((10,1),(4,0), rowspan=6) - pl.pcolormesh(ecloud.spacech_ele.xg*1e3, ecloud.spacech_ele.yg*1e3, ecloud.rho_ele_last_track[ii,:,:].T, vmax=vmax, vmin=vmin) - pl.xlabel('x [mm]');pl.ylabel('y [mm]') - pl.axis('equal') - pl.subplots_adjust(hspace=.5) - pl.draw() - time.sleep(.2) - pl.show() - - diff --git a/test_kicks/cleanall b/test_kicks/cleanall deleted file mode 100755 index 9363e65..0000000 --- a/test_kicks/cleanall +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -rm *.txt -rm *.err -rm *.out -rm *.cmd diff --git a/test_kicks/machines_for_testing.py b/test_kicks/machines_for_testing.py deleted file mode 100644 index 60a517a..0000000 --- a/test_kicks/machines_for_testing.py +++ /dev/null @@ -1,126 +0,0 @@ -from PyHEADTAIL.machines.synchrotron import BasicSynchrotron -import numpy as np -from scipy.constants import c, e, m_p - -class EmptyObject(object): - pass - -class SPS(BasicSynchrotron): - - def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): - - pp = EmptyObject() - - pp.machine_configuration = machine_configuration - pp.optics_mode = optics_mode - - pp.longitudinal_mode = 'linear' - pp.h_RF = 4620 - pp.mass = m_p - pp.charge = e - - pp.RF_at = 'end_of_transverse' - - if pp.machine_configuration=='Q26-injection': - pp.p0 = 26e9 * e /c - pp.p_increment = 0. - pp.accQ_x = 26.13 - pp.accQ_y = 26.18 - pp.V_RF = 2e6 - pp.dphi_RF = 0. - pp.alpha = 0.00192 - pp.beta_x = 42. - pp.D_x = 0 - pp.beta_y = 42. - pp.D_y = 0 - elif pp.machine_configuration=='Q20-injection': - pp.p0 = 26e9 * e /c - pp.p_increment = 0. - pp.accQ_x = 20.13 - pp.accQ_y = 20.18 - pp.V_RF = 5.75e6 - pp.dphi_RF = 0. - pp.alpha = 0.00308642 - pp.beta_x = 54.6 - pp.D_x = 0 - pp.beta_y = 54.6 - pp.D_y = 0 - else: - raise ValueError('machine_configuration not recognized!') - - - - if pp.optics_mode=='smooth': - if 's' in kwargs.keys(): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') - - pp.n_segments = kwargs['n_segments'] - pp.circumference = 1100*2*np.pi - - pp.name = None - - pp.alpha_x = None - pp.alpha_y = None - - pp.s = None - - elif pp.optics_mode=='non-smooth': - if 'n_segments' in kwargs.keys(): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') - pp.n_segments = None - pp.circumference = None - - pp.name = kwargs['name'] - - pp.beta_x = kwargs['beta_x'] - pp.beta_y = kwargs['beta_y'] - - try: - pp.D_x = kwargs['D_x'] - except KeyError: - pp.D_x = 0*np.array(kwargs['s']) - try: - pp.D_y = kwargs['D_y'] - except KeyError: - pp.D_y = 0*np.array(kwargs['s']) - - pp.alpha_x = kwargs['alpha_x'] - pp.alpha_y = kwargs['alpha_y'] - - pp.s = kwargs['s'] - - else: - raise ValueError('optics_mode not recognized!') - - - # detunings - pp.Qp_x = 0 - pp.Qp_y = 0 - - pp.app_x = 0 - pp.app_y = 0 - pp.app_xy = 0 - - - - for attr in kwargs.keys(): - if kwargs[attr] is not None: - if type(kwargs[attr]) is list or type(kwargs[attr]) is np.ndarray: - str2print = '[%s ...]'%repr(kwargs[attr][0]) - else: - str2print = repr(kwargs[attr]) - self.prints('Synchrotron init. From kwargs: %s = %s' - % (attr, str2print)) - - if not hasattr(pp, attr): - raise NameError("I don't understand %s"%attr) - - setattr(pp, attr, kwargs[attr]) - - - super(SPS, self).__init__(optics_mode=pp.optics_mode, circumference=pp.circumference, n_segments=pp.n_segments, s=pp.s, name=pp.name, - alpha_x=pp.alpha_x, beta_x=pp.beta_x, D_x=pp.D_x, alpha_y=pp.alpha_y, beta_y=pp.beta_y, D_y=pp.D_y, - accQ_x=pp.accQ_x, accQ_y=pp.accQ_y, Qp_x=pp.Qp_x, Qp_y=pp.Qp_y, app_x=pp.app_x, app_y=pp.app_y, app_xy=pp.app_xy, - alpha_mom_compaction=pp.alpha, longitudinal_mode=pp.longitudinal_mode, - h_RF=np.atleast_1d(pp.h_RF), V_RF=np.atleast_1d(pp.V_RF), dphi_RF=np.atleast_1d(pp.dphi_RF), p0=pp.p0, p_increment=pp.p_increment, - charge=pp.charge, mass=pp.mass, RF_at=pp.RF_at) - - diff --git a/test_kicks/mystyle.py b/test_kicks/mystyle.py deleted file mode 100644 index de2249c..0000000 --- a/test_kicks/mystyle.py +++ /dev/null @@ -1,27 +0,0 @@ -from matplotlib import rc, rcdefaults -import pylab as pl - - - -def mystyle(fontsz=10): - - font = {#'family' : 'normal', - #'weight' : 'bold', - 'size' : fontsz} - print fontsz - rcdefaults() - rc('font', **font) - -def mystyle_arial(fontsz=10, dist_tick_lab=7): - - rcdefaults() - rc('font',**{'family':'sans-serif','sans-serif':['arial'], 'size':fontsz}) - rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=dist_tick_lab) - - - -def sciy(): - pl.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - -def scix(): - pl.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='x') diff --git a/test_kicks/pyecloud_config/LHC_chm_ver.mat b/test_kicks/pyecloud_config/LHC_chm_ver.mat deleted file mode 100755 index 2a41ac7be48cdfbae810a7a7997288ddffba6cce..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1200 zcmeZu4DoSvQZUssQ1EpO(M`+DNmU5QNi0drFUqx2D9A6)tk6+#E=o--Nlj76&$CkS z&CgTtO{`QfvQRLzurf5XGBi>!GB7k^AOkRZ`tkv_9bjZ&U<1+|Kn$WmfE9>Ae4rEq z$ZSRiCWf#I1_n+bdje2!mnRRCcKbB@Eus#F8zZOL2Ssv6{JuEV{+GzX7~M}(?3ooW zojbR8vi*@m50~w+oMf+ew0enX&IJ2N%|t`z9X<9>lQ%MDsC3vrIvsjlM8Da7c6r|P zIX9~9bysyqE`C&Cuk!5Xfu9S*?DZh@ep86}{&^5}`yWH}?SBa|XMYsL-2M6xd-flO z*t;Lw=fmWo{@Bk1@yGr{Q1hVv*dGqH?-A7gJ5cw)+-CrF zuN2h%eo+6|Lj5-l>R*`uUqHhn78*VV(C|724L?|TLj3^`Z&>(~6pxjNcmzf#7<`rD zdek*7&Hk0F3dg66GJBcxKO2OmHP|O;rWI`6(rSM$XKl{5>Mr~Dz6y6vU+=SjowG!Z=vpX-S+wKm4Jjj-y!_{A0YDk z6(H*OCqne^zW_0BKhz)l-$MMcALuA3=E%gav@OGQK!9H$F8dC$k_vGp{%qls`fF_VNAn7z=?(_N1Cufy2C?X|ts- I3s18L0Di5=zW@LL diff --git a/test_kicks/pyecloud_config/machine_parameters.input b/test_kicks/pyecloud_config/machine_parameters.input deleted file mode 100755 index 8637b80..0000000 --- a/test_kicks/pyecloud_config/machine_parameters.input +++ /dev/null @@ -1,10 +0,0 @@ -# MACHINE PARAMETERS - -chamb_type = None #redefine in the script - - -track_method= 'BorisMultipole' -N_sub_steps = 5 -B_multip = [0.] - - diff --git a/test_kicks/pyecloud_config/secondary_emission_parameters.input b/test_kicks/pyecloud_config/secondary_emission_parameters.input deleted file mode 100755 index 618b83e..0000000 --- a/test_kicks/pyecloud_config/secondary_emission_parameters.input +++ /dev/null @@ -1,18 +0,0 @@ -# secondary emission model -Emax=332.; -del_max = 0. -R0 = 0. -switch_model=0 - -# hilleret model for sec. emission -E_th=35.; -sigmafit =1.0828; -mufit = 1.6636; - -switch_no_increase_energy=0 -thresh_low_energy=-1 - -scrub_en_th=20.#eV - -secondary_angle_distribution = 'cosine_3D' - diff --git a/test_kicks/pyecloud_config/simulation_parameters.input b/test_kicks/pyecloud_config/simulation_parameters.input deleted file mode 100755 index 11b8269..0000000 --- a/test_kicks/pyecloud_config/simulation_parameters.input +++ /dev/null @@ -1,63 +0,0 @@ -# SIMULATION PARAMETERS - -machine_param_file='machine_parameters.input' -secondary_emission_parameters_file='secondary_emission_parameters.input' -beam_parameters_file='beam.beam' - -logfile_path = 'logfile.txt' -progress_path = 'progress' -stopfile = 'stop' - -Dt = None -t_end = None #s (no effect if log. profile is imported from file) - -#import numpy as np -#dec_fact_out = int(np.round(5 * 25e-12/Dt)) - -lam_th = None #e-/m -Dx_hist = 1e-3 #m -r_center = 1e-3 #m - - -Dt_En_hist = 25e-9 #s -Nbin_En_hist= 2000 -En_hist_max= 2e3 #eV - -t_ion=100.; #s - -N_mp_max=250000; #size of allocated vectors - -#Regen parameters - -N_mp_regen=250000; -N_mp_regen_low=5000; -N_mp_after_regen=10000; -t_ON_regen_low=10. -fact_split=1.5; -fact_clean=1e-6; -regen_hist_cut = 1.e-4 - -N_mp_soft_regen = 75000 -N_mp_after_soft_regen = 25000 - -nel_mp_ref_0 = None #redefine in the script - -# Number of bins -Nx_regen=51;#it must be odd! -Ny_regen=51;#it must be odd! -Nvx_regen=51;#it must be odd! -Nvy_regen=101;#it must be odd! -Nvz_regen=51;#it must be odd! - - -#Sp_ch params -Dt_sc = None -Dh_sc = None -t_sc_ON=0e-9; #s -#PyPICmode = 'FFT_OpenBoundary' -sparse_solver = 'klu' - -flag_movie = 0 #1/0 -flag_sc_movie = 0 #1/0 - -save_mp_state_time_file = -1 diff --git a/test_kicks/run_bologna_000 b/test_kicks/run_bologna_000 deleted file mode 100755 index f89d182..0000000 --- a/test_kicks/run_bologna_000 +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash - - -NUMBER_OF_REQUESTED_CORES=3 -MAX_NUMBER_OF_CORE_PER_NODE=32 - -PATH_TO_EXECUTABLE="python /home/HPC/giadarol/test_PyECPyHT/PyParaSlice/test_physics/000_test_with_ecloud.py" -SIMULATION_NAME='first' -QUEUE=hpc_inf -#QUEUE=hpc_short - -stderr_file=epic.txt -stdout_file=opic.txt - - - -############################################ -## DO NOT TOUCH FROM HERE -############################################ - -job=job_${NUMBER_OF_REQUESTED_CORES}.cmd - -rm -f $job -touch $job -chmod 755 $job -touch ${stderr_file} -touch ${stdout_file} -echo "#BSUB -J ${SIMULATION_NAME}" > $job # Job name -echo "#BSUB -o %J.out" >> $job # Job standard output -echo "#BSUB -e %J.err" >> $job # Job standard error -echo "#BSUB -N" >> $job # Job report -echo "#BSUB -B" >> $job # Send mail -echo "#BSUB -q $QUEUE" >> $job -echo "#BSUB -a openmpi" >> $job -echo "#BSUB -n ${NUMBER_OF_REQUESTED_CORES}" >> $job -echo "#BSUB -R span[ptile=${MAX_NUMBER_OF_CORE_PER_NODE}]" >> $job -echo "/usr/share/lsf/9.1/linux2.6-glibc2.3-x86_64/bin/mpirun.lsf env PSM_SHAREDCONTEXTS_MAX=8 ${PATH_TO_EXECUTABLE} >> ${stdout_file} 2>> ${stderr_file}" >> $job - - -echo "Submit your job to the queue system with this command: " -echo "bsub < $job" - - From 4dbfa21cad0ed3823ad52ed55eaabc6d6d0ec0aa Mon Sep 17 00:00:00 2001 From: giadarol Date: Tue, 6 Aug 2019 16:15:57 +0200 Subject: [PATCH 07/12] Removed test, it is tested in the PyPARIS_sim_class --- .../000_run_sim_with_eclouds.sh | 10 - .../001_run_sim_with_dummy_eclouds.sh | 10 - .../002_fully_serial_sim.py | 117 ---------- .../003_plot_results.py | 38 ---- ...with_python_multiprocess_nolounchscript.py | 97 --------- .../LHC_chm_ver.mat | Bin 1200 -> 0 bytes .../000_instability_simulation/LHC_custom.py | 61 ------ .../Simulation_with_dummy_eclouds.py | 206 ------------------ .../Simulation_with_eclouds.py | 198 ----------------- .../000_instability_simulation/cleanall | 6 - .../000_instability_simulation/mystyle.py | 31 --- .../pyecloud_config/machine_parameters.input | 10 - .../secondary_emission_parameters.input | 17 -- .../simulation_parameters.input | 63 ------ 14 files changed, 864 deletions(-) delete mode 100644 test_instability/000_instability_simulation/000_run_sim_with_eclouds.sh delete mode 100644 test_instability/000_instability_simulation/001_run_sim_with_dummy_eclouds.sh delete mode 100644 test_instability/000_instability_simulation/002_fully_serial_sim.py delete mode 100644 test_instability/000_instability_simulation/003_plot_results.py delete mode 100644 test_instability/000_instability_simulation/004_run_with_python_multiprocess_nolounchscript.py delete mode 100644 test_instability/000_instability_simulation/LHC_chm_ver.mat delete mode 100644 test_instability/000_instability_simulation/LHC_custom.py delete mode 100644 test_instability/000_instability_simulation/Simulation_with_dummy_eclouds.py delete mode 100644 test_instability/000_instability_simulation/Simulation_with_eclouds.py delete mode 100755 test_instability/000_instability_simulation/cleanall delete mode 100644 test_instability/000_instability_simulation/mystyle.py delete mode 100644 test_instability/000_instability_simulation/pyecloud_config/machine_parameters.input delete mode 100644 test_instability/000_instability_simulation/pyecloud_config/secondary_emission_parameters.input delete mode 100644 test_instability/000_instability_simulation/pyecloud_config/simulation_parameters.input diff --git a/test_instability/000_instability_simulation/000_run_sim_with_eclouds.sh b/test_instability/000_instability_simulation/000_run_sim_with_eclouds.sh deleted file mode 100644 index 2722259..0000000 --- a/test_instability/000_instability_simulation/000_run_sim_with_eclouds.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/bash - -# Run Parallel without MPI -# ../../multiprocexec.py -n 3 sim_class=Simulation_with_eclouds.Simulation - -# Run Serial -# ../../serialexec.py sim_class=Simulation_with_eclouds.Simulation - -# Run MPI -mpiexec -n 4 ../../withmpi.py sim_class=Simulation_with_eclouds.Simulation diff --git a/test_instability/000_instability_simulation/001_run_sim_with_dummy_eclouds.sh b/test_instability/000_instability_simulation/001_run_sim_with_dummy_eclouds.sh deleted file mode 100644 index 8f8cc20..0000000 --- a/test_instability/000_instability_simulation/001_run_sim_with_dummy_eclouds.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/bash - -# Run Parallel without MPI -# ../../multiprocexec.py -n 3 sim_class=Simulation_with_dummy_eclouds.Simulation - -# Run Serial -# ../../serialexec.py sim_class=Simulation_with_dummy_eclouds.Simulation - -# Run MPI -mpiexec -n 4 ../../withmpi.py sim_class=Simulation_with_dummy_eclouds.Simulation diff --git a/test_instability/000_instability_simulation/002_fully_serial_sim.py b/test_instability/000_instability_simulation/002_fully_serial_sim.py deleted file mode 100644 index 050fc1e..0000000 --- a/test_instability/000_instability_simulation/002_fully_serial_sim.py +++ /dev/null @@ -1,117 +0,0 @@ -import sys, os -BIN=os.path.expanduser('../../../') -sys.path.append(BIN) - - -import numpy as np -from scipy.constants import c, e - - -jobid = 'LH0136' -queue = '1nw' - -n_segments = 79 -N_turns = 512 - - -intensity = 1.300000e+11 -epsn_x = 2.5e-6 -epsn_y = 2.5e-6 - -machine_configuration = 'HLLHC-injection' - -init_unif_edens_flag = 1 -init_unif_edens = 1.000000e+12 -N_MP_ele_init = 100000 -N_mp_max = N_MP_ele_init*4. - -x_kick_in_sigmas = 0.1 -y_kick_in_sigmas = 0.1 - - -chamb_type = 'polyg' -x_aper = 2.300000e-02 -y_aper = 1.800000e-02 -filename_chm = 'LHC_chm_ver.mat' - - - -B_multip_per_eV = [1.190000e-12] -B_multip_per_eV = np.array(B_multip_per_eV) - - -# define the machine -from LHC_custom import LHC -machine = LHC(n_segments = n_segments, machine_configuration = machine_configuration) - -# compute sigma x and y -inj_opt = machine.transverse_map.get_injection_optics() -sigma_x = np.sqrt(inj_opt['beta_x']*epsn_x/machine.betagamma) -sigma_y = np.sqrt(inj_opt['beta_y']*epsn_y/machine.betagamma) - -x_kick = x_kick_in_sigmas*sigma_x -y_kick = y_kick_in_sigmas*sigma_y - -# define PIC grid size -Dh_sc = .2e-3 - -# define MP size -nel_mp_ref_0 = init_unif_edens*4*x_aper*y_aper/N_MP_ele_init - - - -# define an electron cloud -import PyECLOUD.PyEC4PyHT as PyEC4PyHT -from PyHEADTAIL.particles.slicing import UniformBinSlicer -slicer = UniformBinSlicer(n_slices = 64, n_sigma_z = 2.) -ecloud = PyEC4PyHT.Ecloud(L_ecloud=machine.circumference/n_segments, slicer=slicer , - Dt_ref=10e-12, pyecl_input_folder='./pyecloud_config', - chamb_type = chamb_type, - x_aper=x_aper, y_aper=y_aper, - filename_chm=filename_chm, Dh_sc=Dh_sc, - init_unif_edens_flag=init_unif_edens_flag, - init_unif_edens=init_unif_edens, - N_mp_max=N_mp_max, - nel_mp_ref_0=nel_mp_ref_0, - B_multip=B_multip_per_eV*machine.p0/e*c) - -# install ecloud in the machine -machine.install_after_each_transverse_segment(ecloud) - -# setup transverse losses (to "protect" the ecloud) -import PyHEADTAIL.aperture.aperture as aperture -apt_xy = aperture.EllipticalApertureXY(x_aper=ecloud.cloudsim.cloud_list[0].impact_man.chamb.x_aper, - y_aper=ecloud.cloudsim.cloud_list[0].impact_man.chamb.y_aper) -machine.one_turn_map.append(apt_xy) - -# generate a bunch -bunch = machine.generate_6D_Gaussian_bunch_matched(n_macroparticles=300000, intensity=intensity, - epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=1.35e-9/4*c) - -# apply initial displacement -bunch.x += x_kick -bunch.y += y_kick - -# define a bunch monitor -from PyHEADTAIL.monitors.monitors import BunchMonitor -bunch_monitor = BunchMonitor('bunch_evolution.h5', N_turns, {'Comment':'PyHDTL simulation'}, - write_buffer_every = 8) - -# simulate -import time -for i_turn in xrange(N_turns): - print '%s Turn %d'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime()), i_turn) - machine.track(bunch, verbose = False) - bunch_monitor.dump(bunch) - - - - - - - - - - - - diff --git a/test_instability/000_instability_simulation/003_plot_results.py b/test_instability/000_instability_simulation/003_plot_results.py deleted file mode 100644 index 3892b60..0000000 --- a/test_instability/000_instability_simulation/003_plot_results.py +++ /dev/null @@ -1,38 +0,0 @@ -import sys -sys.path.append('../../../') - -import numpy as np -import mystyle as ms -import pylab as pl -from scipy.constants import c as ccc - -import PyPARIS.myfilemanager as mfm - -pl.close('all') -ob = mfm.monitorh5_to_obj('bunch_evolution.h5') - -pl.figure(1) -pl.subplot(2,3,1) -pl.plot(ob.mean_x) -ms.sciy() -pl.subplot(2,3,4) -spectrum_x = np.abs(np.fft.rfft(ob.mean_x)) -pl.semilogy(np.linspace(0, .5, len(spectrum_x)), spectrum_x) - - -pl.subplot(2,3,2) -pl.plot(ob.mean_y) -ms.sciy() -pl.subplot(2,3,5) -spectrum_y = np.abs(np.fft.rfft(ob.mean_y)) -pl.semilogy(np.linspace(0, .5, len(spectrum_y)), spectrum_y) - -pl.subplot(2,3,3) -pl.plot(ob.epsn_x) -ms.sciy() -pl.gca().ticklabel_format(useOffset=False) -pl.subplot(2,3,6) -pl.plot(ob.epsn_y) -ms.sciy() -pl.gca().ticklabel_format(useOffset=False) -pl.show() diff --git a/test_instability/000_instability_simulation/004_run_with_python_multiprocess_nolounchscript.py b/test_instability/000_instability_simulation/004_run_with_python_multiprocess_nolounchscript.py deleted file mode 100644 index 00ec073..0000000 --- a/test_instability/000_instability_simulation/004_run_with_python_multiprocess_nolounchscript.py +++ /dev/null @@ -1,97 +0,0 @@ -import sys, os -BIN = os.path.expanduser("../../../") -sys.path.append(BIN) - -import multiprocessing as mp -import numpy as np - -class mpComm(object): - def __init__(self, pid, N_proc, queue_list, - mutex, barriex, turnstile, turnstile2, cnt): - self._pid = pid - self._N_proc = N_proc - self._queue_list = queue_list - self.mutex = mutex - self.turnstile = turnstile - self.turnstile2 = turnstile2 - self.cnt = cnt - - def Get_size(self): - return self._N_proc - - def Get_rank(self): - return self._pid - - def Barrier(self): - self.mutex.acquire() - self.cnt.value += 1 - if self.cnt.value == self._N_proc: - self.turnstile2.acquire() - self.turnstile.release() - self.mutex.release() - self.turnstile.acquire() - self.turnstile.release() - #criticalpoint - self.mutex.acquire() - self.cnt.value -= 1 - if self.cnt.value == 0: - self.turnstile.acquire() - self.turnstile2.release() - self.mutex.release() - self.turnstile2.acquire() - self.turnstile2.release() - - - - def Sendrecv(self, sendbuf, dest, sendtag, recvbuf, source, recvtag): - self._queue_list[dest].put(sendbuf) - temp = self._queue_list[self._pid].get() - recvbuf[:len(temp)]=temp - - def Bcast(self, buf, root): - self.Barrier() - if self._pid==root: - for ii, q in enumerate(self._queue_list): - if ii!=root: - q.put(buf) - else: - temp = self._queue_list[self._pid].get() - buf[:len(temp)]=temp - self.Barrier() - -def todo(pid, N_proc, queue_list, - mutex, barriex, turnstile, turnstile2, cnt): - - comm = mpComm(pid, N_proc, queue_list, - mutex, barriex, turnstile, turnstile2, cnt) - - from PyPARIS.ring_of_CPUs import RingOfCPUs - from Simulation_with_eclouds import Simulation - simulation_content = Simulation() - - myCPUring = RingOfCPUs(simulation_content, N_pieces_per_transfer=1, comm=comm) - - myCPUring.run() - - -if __name__=='__main__': - N_proc = 2 - - queue_list = [mp.Queue() for _ in xrange(N_proc)] - - mutex = mp.Semaphore(1) - barrier = mp.Semaphore(0) - turnstile = mp.Semaphore(0) - turnstile2 = mp.Semaphore(1) - cnt = mp.Value('i', 0) - - proc_list = [] - for pid in xrange(N_proc): - proc_list.append(mp.Process(target=todo, - args=(pid, N_proc, queue_list, - mutex, barrier, turnstile, turnstile2, cnt))) - for p in proc_list: - p.start() - for p in proc_list: - p.join() - diff --git a/test_instability/000_instability_simulation/LHC_chm_ver.mat b/test_instability/000_instability_simulation/LHC_chm_ver.mat deleted file mode 100644 index 2a41ac7be48cdfbae810a7a7997288ddffba6cce..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1200 zcmeZu4DoSvQZUssQ1EpO(M`+DNmU5QNi0drFUqx2D9A6)tk6+#E=o--Nlj76&$CkS z&CgTtO{`QfvQRLzurf5XGBi>!GB7k^AOkRZ`tkv_9bjZ&U<1+|Kn$WmfE9>Ae4rEq z$ZSRiCWf#I1_n+bdje2!mnRRCcKbB@Eus#F8zZOL2Ssv6{JuEV{+GzX7~M}(?3ooW zojbR8vi*@m50~w+oMf+ew0enX&IJ2N%|t`z9X<9>lQ%MDsC3vrIvsjlM8Da7c6r|P zIX9~9bysyqE`C&Cuk!5Xfu9S*?DZh@ep86}{&^5}`yWH}?SBa|XMYsL-2M6xd-flO z*t;Lw=fmWo{@Bk1@yGr{Q1hVv*dGqH?-A7gJ5cw)+-CrF zuN2h%eo+6|Lj5-l>R*`uUqHhn78*VV(C|724L?|TLj3^`Z&>(~6pxjNcmzf#7<`rD zdek*7&Hk0F3dg66GJBcxKO2OmHP|O;rWI`6(rSM$XKl{5>Mr~Dz6y6vU+=SjowG!Z=vpX-S+wKm4Jjj-y!_{A0YDk z6(H*OCqne^zW_0BKhz)l-$MMcALuA3=E%gav@OGQK!9H$F8dC$k_vGp{%qls`fF_VNAn7z=?(_N1Cufy2C?X|ts- I3s18L0Di5=zW@LL diff --git a/test_instability/000_instability_simulation/LHC_custom.py b/test_instability/000_instability_simulation/LHC_custom.py deleted file mode 100644 index b962786..0000000 --- a/test_instability/000_instability_simulation/LHC_custom.py +++ /dev/null @@ -1,61 +0,0 @@ -from PyHEADTAIL.machines.synchrotron import BasicSynchrotron -import numpy as np -from scipy.constants import c, e, m_p - -class EmptyObject(object): - pass - -class LHC(BasicSynchrotron): - - def __init__(self, n_segments, machine_configuration): - - pp = EmptyObject() - pp.n_segments = n_segments - pp.machine_configuration =machine_configuration - - pp.circumference = 26658.8832 - - if pp.machine_configuration =='HLLHC-injection': - pp.charge = e - pp.mass = m_p - - pp.alpha_x = 0. - pp.beta_x = 92.7 - pp.D_x = 0. - pp.alpha_y = 0. - pp.beta_y = 93.2 - pp.D_y = 0. - - pp.accQ_x = 62.28 - pp.accQ_y = 60.31 - - pp.Qp_x = 0 - pp.Qp_y = 0 - - pp.app_x = 0.0000e-9 - pp.app_y = 0.0000e-9 - pp.app_xy = 0 - - pp.alpha = 3.4561e-04 - - pp.h_RF = 35640 - pp.V_RF = 8e6 - pp.dphi_RF = 0. - - - pp.longitudinal_mode = 'non-linear' - - pp.p0 = 450.e9 * e /c - - pp.p_increment = 0. - - else: - raise ValueError('ERROR: unknown machine configuration', machine_configuration) - - - super(LHC, self).__init__(optics_mode='smooth', circumference=pp.circumference, n_segments=pp.n_segments, - alpha_x=pp.alpha_x, beta_x=pp.beta_x, D_x=pp.D_x, alpha_y=pp.alpha_y, beta_y=pp.beta_y, D_y=pp.D_y, - accQ_x=pp.accQ_x, accQ_y=pp.accQ_y, Qp_x=pp.Qp_x, Qp_y=pp.Qp_y, app_x=pp.app_x, app_y=pp.app_y, app_xy=pp.app_xy, - alpha_mom_compaction=pp.alpha, longitudinal_mode=pp.longitudinal_mode, - h_RF=np.atleast_1d(pp.h_RF), V_RF=np.atleast_1d(pp.V_RF), dphi_RF=np.atleast_1d(pp.dphi_RF), p0=pp.p0, p_increment=pp.p_increment, - charge=pp.charge, mass=pp.mass, RF_at='end_of_transverse') diff --git a/test_instability/000_instability_simulation/Simulation_with_dummy_eclouds.py b/test_instability/000_instability_simulation/Simulation_with_dummy_eclouds.py deleted file mode 100644 index 7d360ed..0000000 --- a/test_instability/000_instability_simulation/Simulation_with_dummy_eclouds.py +++ /dev/null @@ -1,206 +0,0 @@ -import sys, os -BIN = os.path.expanduser("../../../") -sys.path.append(BIN) -BIN = os.path.expanduser("../../") -sys.path.append(BIN) - -import communication_helpers as ch -import numpy as np -from scipy.constants import c, e -import share_segments as shs -import time - -n_segments = 15#79 -N_turns = 512 - -Dh_sc = .2e-3 - - -intensity = 1.300000e+11 -epsn_x = 2.5e-6 -epsn_y = 2.5e-6 - -machine_configuration = 'HLLHC-injection' - -init_unif_edens_flag = 1 -init_unif_edens = 1.5e+12 -N_MP_ele_init = 100000 -N_mp_max = N_MP_ele_init*4. - -x_kick_in_sigmas = 0.1 -y_kick_in_sigmas = 0.1 - - -chamb_type = 'polyg' -x_aper = 2.300000e-02 -y_aper = 1.800000e-02 -filename_chm = 'LHC_chm_ver.mat' - -B_multip_per_eV = [1.190000e-12] -B_multip_per_eV = np.array(B_multip_per_eV) - -Dt_ref=10e-12 -pyecl_input_folder='./pyecloud_config' - -n_macroparticles=300000 -sigma_z=1.35e-9/4*c - -n_slices = 64 -n_sigma_z = 2. - -class Simulation(object): - def __init__(self): - self.N_turns = N_turns - - def init_all(self): - - - self.n_slices = n_slices - self.n_segments = n_segments - - # define the machine - from LHC_custom import LHC - self.machine = LHC(n_segments = n_segments, machine_configuration = machine_configuration) - - # define MP size - nel_mp_ref_0 = init_unif_edens*4*x_aper*y_aper/N_MP_ele_init - - # prepare e-cloud - import PyECLOUD.PyEC4PyHT as PyEC4PyHT - ecloud = PyEC4PyHT.Ecloud(slice_by_slice_mode=True, - L_ecloud=self.machine.circumference/n_segments, slicer=None , - Dt_ref=Dt_ref, pyecl_input_folder=pyecl_input_folder, - chamb_type = chamb_type, - x_aper=x_aper, y_aper=y_aper, - filename_chm=filename_chm, Dh_sc=Dh_sc, - init_unif_edens_flag=init_unif_edens_flag, - init_unif_edens=init_unif_edens, - N_mp_max=N_mp_max, - nel_mp_ref_0=nel_mp_ref_0, - B_multip=B_multip_per_eV*self.machine.p0/e*c) - - # setup transverse losses (to "protect" the ecloud) - import PyHEADTAIL.aperture.aperture as aperture - apt_xy = aperture.EllipticalApertureXY(x_aper=ecloud.cloudsim.cloud_list[0].impact_man.chamb.x_aper, - y_aper=ecloud.cloudsim.cloud_list[0].impact_man.chamb.y_aper) - self.machine.one_turn_map.append(apt_xy) - - n_non_parallelizable = 2 #rf and aperture - - # We suppose that all the object that cannot be slice parallelized are at the end of the ring - i_end_parallel = len(self.machine.one_turn_map)-n_non_parallelizable - - # split the machine - sharing = shs.ShareSegments(i_end_parallel, self.ring_of_CPUs.N_nodes) - myid = self.ring_of_CPUs.myid - i_start_part, i_end_part = sharing.my_part(myid) - self.mypart = self.machine.one_turn_map[i_start_part:i_end_part] - if self.ring_of_CPUs.I_am_a_worker: - print 'I am id=%d/%d (worker) and my part is %d long'%(myid, self.ring_of_CPUs.N_nodes, len(self.mypart)) - elif self.ring_of_CPUs.I_am_the_master: - self.non_parallel_part = self.machine.one_turn_map[i_end_parallel:] - print 'I am id=%d/%d (master) and my part is %d long'%(myid, self.ring_of_CPUs.N_nodes, len(self.mypart)) - - #install eclouds in my part - my_new_part = [] - self.my_list_eclouds = [] - for ele in self.mypart: - my_new_part.append(ele) - if ele in self.machine.transverse_map: - #ecloud_new = ecloud.generate_twin_ecloud_with_shared_space_charge() - ecloud_new = DummyEcloud() - my_new_part.append(ecloud_new) - self.my_list_eclouds.append(ecloud_new) - self.mypart = my_new_part - - def init_master(self): - - # generate a bunch - bunch = self.machine.generate_6D_Gaussian_bunch_matched( - n_macroparticles=n_macroparticles, intensity=intensity, - epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=sigma_z) - print 'Bunch initialized.' - - # initial slicing - from PyHEADTAIL.particles.slicing import UniformBinSlicer - self.slicer = UniformBinSlicer(n_slices = n_slices, n_sigma_z = n_sigma_z) - - # compute initial displacements - inj_opt = self.machine.transverse_map.get_injection_optics() - sigma_x = np.sqrt(inj_opt['beta_x']*epsn_x/self.machine.betagamma) - sigma_y = np.sqrt(inj_opt['beta_y']*epsn_y/self.machine.betagamma) - x_kick = x_kick_in_sigmas*sigma_x - y_kick = y_kick_in_sigmas*sigma_y - - # apply initial displacement - bunch.x += x_kick - bunch.y += y_kick - - # define a bunch monitor - from PyHEADTAIL.monitors.monitors import BunchMonitor - self.bunch_monitor = BunchMonitor('bunch_evolution', N_turns, {'Comment':'PyHDTL simulation'}, - write_buffer_every = 8) - - - #slice for the first turn - slice_obj_list = bunch.extract_slices(self.slicer) - - pieces_to_be_treated = slice_obj_list - - print 'N_turns', self.N_turns - - return pieces_to_be_treated - - def init_worker(self): - pass - - def treat_piece(self, piece): - for ele in self.mypart: - ele.track(piece) - - def finalize_turn_on_master(self, pieces_treated): - - # re-merge bunch - bunch = sum(pieces_treated) - - #finalize present turn (with non parallel part, e.g. synchrotron motion) - for ele in self.non_parallel_part: - ele.track(bunch) - - # save results - #print '%s Turn %d'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime()), i_turn) - self.bunch_monitor.dump(bunch) - - # prepare next turn (re-slice) - new_pieces_to_be_treated = bunch.extract_slices(self.slicer) - orders_to_pass = ['reset_clouds'] - - return orders_to_pass, new_pieces_to_be_treated - - - def execute_orders_from_master(self, orders_from_master): - if 'reset_clouds' in orders_from_master: - for ec in self.my_list_eclouds: ec.finalize_and_reinitialize() - - - - def finalize_simulation(self): - pass - - def piece_to_buffer(self, piece): - buf = ch.beam_2_buffer(piece) - return buf - - def buffer_to_piece(self, buf): - piece = ch.buffer_2_beam(buf) - return piece - -class DummyEcloud(object): - def __init__(self): - pass - def track(self, bunch): - pass - def finalize_and_reinitialize(self): - pass - - diff --git a/test_instability/000_instability_simulation/Simulation_with_eclouds.py b/test_instability/000_instability_simulation/Simulation_with_eclouds.py deleted file mode 100644 index c449955..0000000 --- a/test_instability/000_instability_simulation/Simulation_with_eclouds.py +++ /dev/null @@ -1,198 +0,0 @@ -import sys, os -BIN = os.path.expanduser("../../../") -sys.path.append(BIN) -BIN = os.path.expanduser("../../") -sys.path.append(BIN) - -import communication_helpers as ch -import numpy as np -from scipy.constants import c, e -import share_segments as shs -import time - -n_segments = 79 -N_turns = 2#512 - -Dh_sc = .2e-3 - - -intensity = 1.300000e+11 -epsn_x = 2.5e-6 -epsn_y = 2.5e-6 - -machine_configuration = 'HLLHC-injection' - -init_unif_edens_flag = 1 -init_unif_edens = 1.5e+12 -N_MP_ele_init = 100000 -N_mp_max = N_MP_ele_init*4. - -x_kick_in_sigmas = 0.1 -y_kick_in_sigmas = 0.1 - - -chamb_type = 'polyg' -x_aper = 2.300000e-02 -y_aper = 1.800000e-02 -filename_chm = 'LHC_chm_ver.mat' - -B_multip_per_eV = [1.190000e-12] -B_multip_per_eV = np.array(B_multip_per_eV) - -Dt_ref=10e-12 -pyecl_input_folder='./pyecloud_config' - -n_macroparticles=300000 -sigma_z=1.35e-9/4*c - -n_slices = 64 -n_sigma_z = 2. - -class Simulation(object): - def __init__(self): - self.N_turns = N_turns - - def init_all(self): - - - self.n_slices = n_slices - self.n_segments = n_segments - - # define the machine - from LHC_custom import LHC - self.machine = LHC(n_segments = n_segments, machine_configuration = machine_configuration) - - # define MP size - nel_mp_ref_0 = init_unif_edens*4*x_aper*y_aper/N_MP_ele_init - - # prepare e-cloud - import PyECLOUD.PyEC4PyHT as PyEC4PyHT - ecloud = PyEC4PyHT.Ecloud(slice_by_slice_mode=True, - L_ecloud=self.machine.circumference/n_segments, slicer=None , - Dt_ref=Dt_ref, pyecl_input_folder=pyecl_input_folder, - chamb_type = chamb_type, - x_aper=x_aper, y_aper=y_aper, - filename_chm=filename_chm, Dh_sc=Dh_sc, - init_unif_edens_flag=init_unif_edens_flag, - init_unif_edens=init_unif_edens, - N_mp_max=N_mp_max, - nel_mp_ref_0=nel_mp_ref_0, - B_multip=B_multip_per_eV*self.machine.p0/e*c) - - # setup transverse losses (to "protect" the ecloud) - import PyHEADTAIL.aperture.aperture as aperture - apt_xy = aperture.EllipticalApertureXY(x_aper=x_aper, y_aper=y_aper) - self.machine.one_turn_map.append(apt_xy) - - n_non_parallelizable = 2 #rf and aperture - - # We suppose that all the object that cannot be slice parallelized are at the end of the ring - i_end_parallel = len(self.machine.one_turn_map)-n_non_parallelizable - - # split the machine - sharing = shs.ShareSegments(i_end_parallel, self.ring_of_CPUs.N_nodes) - myid = self.ring_of_CPUs.myid - i_start_part, i_end_part = sharing.my_part(myid) - self.mypart = self.machine.one_turn_map[i_start_part:i_end_part] - if self.ring_of_CPUs.I_am_a_worker: - print 'I am id=%d/%d (worker) and my part is %d long'%(myid, self.ring_of_CPUs.N_nodes, len(self.mypart)) - elif self.ring_of_CPUs.I_am_the_master: - self.non_parallel_part = self.machine.one_turn_map[i_end_parallel:] - print 'I am id=%d/%d (master) and my part is %d long'%(myid, self.ring_of_CPUs.N_nodes, len(self.mypart)) - - #install eclouds in my part - my_new_part = [] - self.my_list_eclouds = [] - for ele in self.mypart: - my_new_part.append(ele) - if ele in self.machine.transverse_map: - ecloud_new = ecloud.generate_twin_ecloud_with_shared_space_charge() - my_new_part.append(ecloud_new) - self.my_list_eclouds.append(ecloud_new) - self.mypart = my_new_part - - def init_master(self): - - # generate a bunch - bunch = self.machine.generate_6D_Gaussian_bunch_matched( - n_macroparticles=n_macroparticles, intensity=intensity, - epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=sigma_z) - print 'Bunch initialized.' - - # initial slicing - from PyHEADTAIL.particles.slicing import UniformBinSlicer - self.slicer = UniformBinSlicer(n_slices = n_slices, n_sigma_z = n_sigma_z) - - # compute initial displacements - inj_opt = self.machine.transverse_map.get_injection_optics() - sigma_x = np.sqrt(inj_opt['beta_x']*epsn_x/self.machine.betagamma) - sigma_y = np.sqrt(inj_opt['beta_y']*epsn_y/self.machine.betagamma) - x_kick = x_kick_in_sigmas*sigma_x - y_kick = y_kick_in_sigmas*sigma_y - - # apply initial displacement - bunch.x += x_kick - bunch.y += y_kick - - # define a bunch monitor - from PyHEADTAIL.monitors.monitors import BunchMonitor - self.bunch_monitor = BunchMonitor('bunch_evolution', N_turns, {'Comment':'PyHDTL simulation'}, - write_buffer_every = 8) - - - #slice for the first turn - slice_obj_list = bunch.extract_slices(self.slicer) - - pieces_to_be_treated = slice_obj_list - - print 'N_turns', self.N_turns - - return pieces_to_be_treated - - def init_worker(self): - pass - - def treat_piece(self, piece): - for ele in self.mypart: - ele.track(piece) - - def finalize_turn_on_master(self, pieces_treated): - - # re-merge bunch - bunch = sum(pieces_treated) - - #finalize present turn (with non parallel part, e.g. synchrotron motion) - for ele in self.non_parallel_part: - ele.track(bunch) - - # save results - #print '%s Turn %d'%(time.strftime("%d/%m/%Y %H:%M:%S", time.localtime()), i_turn) - self.bunch_monitor.dump(bunch) - - # prepare next turn (re-slice) - new_pieces_to_be_treated = bunch.extract_slices(self.slicer) - orders_to_pass = ['reset_clouds'] - - return orders_to_pass, new_pieces_to_be_treated - - - def execute_orders_from_master(self, orders_from_master): - if 'reset_clouds' in orders_from_master: - for ec in self.my_list_eclouds: ec.finalize_and_reinitialize() - - - - def finalize_simulation(self): - pass - - def piece_to_buffer(self, piece): - buf = ch.beam_2_buffer(piece) - return buf - - def buffer_to_piece(self, buf): - piece = ch.buffer_2_beam(buf) - return piece - - - - diff --git a/test_instability/000_instability_simulation/cleanall b/test_instability/000_instability_simulation/cleanall deleted file mode 100755 index 9363e65..0000000 --- a/test_instability/000_instability_simulation/cleanall +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -rm *.txt -rm *.err -rm *.out -rm *.cmd diff --git a/test_instability/000_instability_simulation/mystyle.py b/test_instability/000_instability_simulation/mystyle.py deleted file mode 100644 index 50ced22..0000000 --- a/test_instability/000_instability_simulation/mystyle.py +++ /dev/null @@ -1,31 +0,0 @@ -from matplotlib import rc, rcdefaults -import pylab as pl -from colorsys import hsv_to_rgb - - -def mystyle(fontsz=16): - - font = {#'family' : 'normal', - #'weight' : 'bold', - 'size' : fontsz} - print fontsz - rcdefaults() - rc('font', **font) - -def mystyle_arial(fontsz=16, dist_tick_lab=10): - - rcdefaults() - rc('font',**{'family':'sans-serif','sans-serif':['arial'], 'size':fontsz}) - rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=dist_tick_lab) - - - -def sciy(): - pl.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - -def scix(): - pl.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='x') - - -def colorprog(i_prog, Nplots, v1 = .9, v2 = 1.): - return hsv_to_rgb(float(i_prog)/float(Nplots), v1, v2) diff --git a/test_instability/000_instability_simulation/pyecloud_config/machine_parameters.input b/test_instability/000_instability_simulation/pyecloud_config/machine_parameters.input deleted file mode 100644 index 8637b80..0000000 --- a/test_instability/000_instability_simulation/pyecloud_config/machine_parameters.input +++ /dev/null @@ -1,10 +0,0 @@ -# MACHINE PARAMETERS - -chamb_type = None #redefine in the script - - -track_method= 'BorisMultipole' -N_sub_steps = 5 -B_multip = [0.] - - diff --git a/test_instability/000_instability_simulation/pyecloud_config/secondary_emission_parameters.input b/test_instability/000_instability_simulation/pyecloud_config/secondary_emission_parameters.input deleted file mode 100644 index ef0930c..0000000 --- a/test_instability/000_instability_simulation/pyecloud_config/secondary_emission_parameters.input +++ /dev/null @@ -1,17 +0,0 @@ -# secondary emission model -Emax=332.; -del_max = 0. -R0 = 0. -switch_model=0 - -# hilleret model for sec. emission -E_th=35.; -sigmafit =1.0828; -mufit = 1.6636; - -switch_no_increase_energy=0 -thresh_low_energy=-1 - -scrub_en_th=20.#eV - -secondary_angle_distribution = 'cosine_3D' diff --git a/test_instability/000_instability_simulation/pyecloud_config/simulation_parameters.input b/test_instability/000_instability_simulation/pyecloud_config/simulation_parameters.input deleted file mode 100644 index 11b8269..0000000 --- a/test_instability/000_instability_simulation/pyecloud_config/simulation_parameters.input +++ /dev/null @@ -1,63 +0,0 @@ -# SIMULATION PARAMETERS - -machine_param_file='machine_parameters.input' -secondary_emission_parameters_file='secondary_emission_parameters.input' -beam_parameters_file='beam.beam' - -logfile_path = 'logfile.txt' -progress_path = 'progress' -stopfile = 'stop' - -Dt = None -t_end = None #s (no effect if log. profile is imported from file) - -#import numpy as np -#dec_fact_out = int(np.round(5 * 25e-12/Dt)) - -lam_th = None #e-/m -Dx_hist = 1e-3 #m -r_center = 1e-3 #m - - -Dt_En_hist = 25e-9 #s -Nbin_En_hist= 2000 -En_hist_max= 2e3 #eV - -t_ion=100.; #s - -N_mp_max=250000; #size of allocated vectors - -#Regen parameters - -N_mp_regen=250000; -N_mp_regen_low=5000; -N_mp_after_regen=10000; -t_ON_regen_low=10. -fact_split=1.5; -fact_clean=1e-6; -regen_hist_cut = 1.e-4 - -N_mp_soft_regen = 75000 -N_mp_after_soft_regen = 25000 - -nel_mp_ref_0 = None #redefine in the script - -# Number of bins -Nx_regen=51;#it must be odd! -Ny_regen=51;#it must be odd! -Nvx_regen=51;#it must be odd! -Nvy_regen=101;#it must be odd! -Nvz_regen=51;#it must be odd! - - -#Sp_ch params -Dt_sc = None -Dh_sc = None -t_sc_ON=0e-9; #s -#PyPICmode = 'FFT_OpenBoundary' -sparse_solver = 'klu' - -flag_movie = 0 #1/0 -flag_sc_movie = 0 #1/0 - -save_mp_state_time_file = -1 From a688423e66c0ba8ed10c94966ca59950c7b0261d Mon Sep 17 00:00:00 2001 From: giadarol Date: Tue, 6 Aug 2019 16:18:50 +0200 Subject: [PATCH 08/12] Removed test (covered in PyPARIS_sim_class) --- .../000_run_sim_without_ecloud.sh | 10 - .../001_run_sim_with_ecloud.sh | 10 - .../002_plot_results_from_last_sim.py | 69 ----- test_ring_with_objects/LHC.py | 123 --------- test_ring_with_objects/Simulation.py | 200 --------------- .../Simulation_with_eclouds.py | 242 ------------------ test_ring_with_objects/cleanall | 6 - .../pyecloud_config/LHC_chm_ver.mat | Bin 1200 -> 0 bytes .../pyecloud_config/machine_parameters.input | 10 - .../secondary_emission_parameters.input | 18 -- .../simulation_parameters.input | 63 ----- 11 files changed, 751 deletions(-) delete mode 100644 test_ring_with_objects/000_run_sim_without_ecloud.sh delete mode 100644 test_ring_with_objects/001_run_sim_with_ecloud.sh delete mode 100644 test_ring_with_objects/002_plot_results_from_last_sim.py delete mode 100644 test_ring_with_objects/LHC.py delete mode 100644 test_ring_with_objects/Simulation.py delete mode 100644 test_ring_with_objects/Simulation_with_eclouds.py delete mode 100755 test_ring_with_objects/cleanall delete mode 100755 test_ring_with_objects/pyecloud_config/LHC_chm_ver.mat delete mode 100755 test_ring_with_objects/pyecloud_config/machine_parameters.input delete mode 100755 test_ring_with_objects/pyecloud_config/secondary_emission_parameters.input delete mode 100755 test_ring_with_objects/pyecloud_config/simulation_parameters.input diff --git a/test_ring_with_objects/000_run_sim_without_ecloud.sh b/test_ring_with_objects/000_run_sim_without_ecloud.sh deleted file mode 100644 index 33bb5a8..0000000 --- a/test_ring_with_objects/000_run_sim_without_ecloud.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/bash - -# Run Parallel without MPI -../multiprocexec.py -n 3 sim_class=Simulation.Simulation - -# Run Serial -# ../serialexec.py sim_class=Simulation.Simulation - -# Run MPI -# mpiexec -n 4 ../withmpi.py sim_class=Simulation.Simulation diff --git a/test_ring_with_objects/001_run_sim_with_ecloud.sh b/test_ring_with_objects/001_run_sim_with_ecloud.sh deleted file mode 100644 index f017a27..0000000 --- a/test_ring_with_objects/001_run_sim_with_ecloud.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/bash - -# Run Parallel without MPI -../multiprocexec.py -n 3 sim_class=Simulation_with_eclouds.Simulation - -# Run Serial -# ../serialexec.py sim_class=Simulation_with_eclouds.Simulation - -# Run MPI -# mpiexec -n 4 ../withmpi.py sim_class=Simulation_with_eclouds.Simulation diff --git a/test_ring_with_objects/002_plot_results_from_last_sim.py b/test_ring_with_objects/002_plot_results_from_last_sim.py deleted file mode 100644 index 61f7c19..0000000 --- a/test_ring_with_objects/002_plot_results_from_last_sim.py +++ /dev/null @@ -1,69 +0,0 @@ -import sys -sys.path.append('../../') - -import pylab as pl -import numpy as np - -import PyPARIS.myfilemanager as mfm - -ob = mfm.object_with_arrays_and_scalar_from_h5('beam_coord.h5') - -beam_x = ob.beam_x -beam_y = ob.beam_y -beam_z = ob.beam_z -sx = ob.sx -sy = ob.sy -sz = ob.sz -epsx = ob.epsx -epsy = ob.epsy -epsz = ob.epsz - -import pylab as plt - -plt.figure(2, figsize=(16, 8), tight_layout=True) -plt.subplot(2,3,1) -plt.plot(beam_x) -plt.ylabel('x [m]');plt.xlabel('Turn') -plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') -plt.subplot(2,3,2) -plt.plot(beam_y) -plt.ylabel('y [m]');plt.xlabel('Turn') -plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') -plt.subplot(2,3,3) -plt.plot(beam_z) -plt.ylabel('z [m]');plt.xlabel('Turn') -plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') -plt.subplot(2,3,4) -plt.plot(np.fft.rfftfreq(len(beam_x), d=1.), np.abs(np.fft.rfft(beam_x))) -plt.ylabel('Amplitude');plt.xlabel('Qx') -plt.subplot(2,3,5) -plt.plot(np.fft.rfftfreq(len(beam_y), d=1.), np.abs(np.fft.rfft(beam_y))) -plt.ylabel('Amplitude');plt.xlabel('Qy') -plt.subplot(2,3,6) -plt.plot(np.fft.rfftfreq(len(beam_z), d=1.), np.abs(np.fft.rfft(beam_z))) -plt.xlim(0, 0.1) -plt.ylabel('Amplitude');plt.xlabel('Qz') - -fig, axes = plt.subplots(3, figsize=(16, 8), tight_layout=True) -twax = [plt.twinx(ax) for ax in axes] -axes[0].plot(sx) -twax[0].plot(epsx, '-g') -axes[0].set_xlabel('Turns') -axes[0].set_ylabel(r'$\sigma_x$') -twax[0].set_ylabel(r'$\varepsilon_x$') -axes[1].plot(sy) -twax[1].plot(epsy, '-g') -axes[1].set_xlabel('Turns') -axes[1].set_ylabel(r'$\sigma_y$') -twax[1].set_ylabel(r'$\varepsilon_y$') -axes[2].plot(sz) -twax[2].plot(epsz, '-g') -axes[2].set_xlabel('Turns') -axes[2].set_ylabel(r'$\sigma_z$') -twax[2].set_ylabel(r'$\varepsilon_z$') -axes[0].grid() -axes[1].grid() -axes[2].grid() -for ax in list(axes)+list(twax): - ax.ticklabel_format(useOffset=False, style='sci', scilimits=(0,0),axis='y') -plt.show() diff --git a/test_ring_with_objects/LHC.py b/test_ring_with_objects/LHC.py deleted file mode 100644 index 59f49e5..0000000 --- a/test_ring_with_objects/LHC.py +++ /dev/null @@ -1,123 +0,0 @@ -from PyHEADTAIL.machines.synchrotron import BasicSynchrotron -import numpy as np -from scipy.constants import c, e, m_p - -class EmptyObject(object): - pass - -class LHC(BasicSynchrotron): - - def __init__(self, machine_configuration=None, optics_mode='smooth', use_cython=False, **kwargs): - - - pp = EmptyObject() - - pp.machine_configuration = machine_configuration - pp.optics_mode = optics_mode - pp.use_cython = use_cython - - pp.longitudinal_mode = 'non-linear' - pp.alpha = 3.225e-04 - pp.h_RF = 35640 - pp.mass = m_p - pp.charge = e - - pp.RF_at = 'end_of_transverse' - - if pp.machine_configuration=='Injection': - pp.p0 = 450e9 * e /c - pp.p_increment = 0. - pp.accQ_x = 64.28 - pp.accQ_y = 59.31 - pp.V_RF = 6e6 - pp.dphi_RF = 0. - elif pp.machine_configuration=='6.5_TeV_collision_tunes': - pp.p0 = 6500e9 * e /c - pp.p_increment = 0. - pp.accQ_x = 64.31 - pp.accQ_y = 59.32 - pp.V_RF = 12e6 - pp.dphi_RF = 0. - else: - raise ValueError('machine_configuration not recognized!') - - - - if pp.optics_mode=='smooth': - if 's' in kwargs.keys(): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') - - pp.n_segments = kwargs['n_segments'] - pp.circumference = 26658.8832 - - pp.name = None - - pp.beta_x = 92.7 - pp.D_x = 0 - pp.beta_y = 93.2 - pp.D_y = 0 - - pp.alpha_x = None - pp.alpha_y = None - - pp.s = None - - elif pp.optics_mode=='non-smooth': - if 'n_segments' in kwargs.keys(): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') - pp.n_segments = None - pp.circumference = None - - pp.name = kwargs['name'] - - pp.beta_x = kwargs['beta_x'] - pp.beta_y = kwargs['beta_y'] - - try: - pp.D_x = kwargs['D_x'] - except KeyError: - pp.D_x = 0*np.array(kwargs['s']) - try: - pp.D_y = kwargs['D_y'] - except KeyError: - pp.D_y = 0*np.array(kwargs['s']) - - pp.alpha_x = kwargs['alpha_x'] - pp.alpha_y = kwargs['alpha_y'] - - pp.s = kwargs['s'] - - else: - raise ValueError('optics_mode not recognized!') - - - # detunings - pp.Qp_x = 0 - pp.Qp_y = 0 - - pp.app_x = 0 - pp.app_y = 0 - pp.app_xy = 0 - - - for attr in kwargs.keys(): - if kwargs[attr] is not None: - if type(kwargs[attr]) is list or type(kwargs[attr]) is np.ndarray: - str2print = '[%s ...]'%repr(kwargs[attr][0]) - else: - str2print = repr(kwargs[attr]) - self.prints('Synchrotron init. From kwargs: %s = %s' - % (attr, str2print)) - - if not hasattr(pp, attr): - raise NameError("I don't understand %s"%attr) - - setattr(pp, attr, kwargs[attr]) - - - super(LHC, self).__init__(optics_mode=pp.optics_mode, circumference=pp.circumference, n_segments=pp.n_segments, s=pp.s, name=pp.name, - alpha_x=pp.alpha_x, beta_x=pp.beta_x, D_x=pp.D_x, alpha_y=pp.alpha_y, beta_y=pp.beta_y, D_y=pp.D_y, - accQ_x=pp.accQ_x, accQ_y=pp.accQ_y, Qp_x=pp.Qp_x, Qp_y=pp.Qp_y, app_x=pp.app_x, app_y=pp.app_y, app_xy=pp.app_xy, - alpha_mom_compaction=pp.alpha, longitudinal_mode=pp.longitudinal_mode, - h_RF=np.atleast_1d(pp.h_RF), V_RF=np.atleast_1d(pp.V_RF), dphi_RF=np.atleast_1d(pp.dphi_RF), p0=pp.p0, p_increment=pp.p_increment, - charge=pp.charge, mass=pp.mass, RF_at=pp.RF_at, use_cython=pp.use_cython) - - diff --git a/test_ring_with_objects/Simulation.py b/test_ring_with_objects/Simulation.py deleted file mode 100644 index b82b197..0000000 --- a/test_ring_with_objects/Simulation.py +++ /dev/null @@ -1,200 +0,0 @@ -import os, sys -BIN = os.path.expanduser("../../") -sys.path.append(BIN) - -import PyPARIS.share_segments as shs -import PyPARIS.communication_helpers as ch - -import numpy as np -from scipy.constants import c - - -class Simulation(object): - def __init__(self): - self.N_turns = 128 - self.N_buffer_float_size = 500000 - self.N_buffer_int_size = 450 - - def init_all(self): - n_slices = 100 - z_cut = 2.5e-9*c - - self.n_slices = n_slices - self.z_cut = z_cut - - from LHC import LHC - self.machine = LHC(machine_configuration='Injection', n_segments=43, D_x=0., - RF_at='end_of_transverse') - - # We suppose that all the object that cannot be slice parallelized are at the end of the ring - i_end_parallel = len(self.machine.one_turn_map)-1 #only RF is not parallelizable - - # split the machine - sharing = shs.ShareSegments(i_end_parallel, self.ring_of_CPUs.N_nodes) - myid = self.ring_of_CPUs.myid - i_start_part, i_end_part = sharing.my_part(myid) - self.mypart = self.machine.one_turn_map[i_start_part:i_end_part] - if self.ring_of_CPUs.I_am_a_worker: - print 'I am id=%d (worker) and my part is %d long'%(myid, len(self.mypart)) - elif self.ring_of_CPUs.I_am_the_master: - self.non_parallel_part = self.machine.one_turn_map[i_end_parallel:] - print 'I am id=%d (master) and my part is %d long'%(myid, len(self.mypart)) - - def init_master(self): - - # beam parameters - epsn_x = 2.5e-6 - epsn_y = 3.5e-6 - sigma_z = 0.05 - intensity = 1e11 - macroparticlenumber_track = 50000 - - # initialization bunch - bunch = self.machine.generate_6D_Gaussian_bunch_matched( - macroparticlenumber_track, intensity, epsn_x, epsn_y, sigma_z=sigma_z) - print 'Bunch initialized.' - - # initial slicing - from PyHEADTAIL.particles.slicing import UniformBinSlicer - self.slicer = UniformBinSlicer(n_slices = self.n_slices, z_cuts=(-self.z_cut, self.z_cut)) - - #slice for the first turn - slice_obj_list = bunch.extract_slices(self.slicer) - - #prepare to save results - self.beam_x, self.beam_y, self.beam_z = [], [], [] - self.sx, self.sy, self.sz = [], [], [] - self.epsx, self.epsy, self.epsz = [], [], [] - - pieces_to_be_treated = slice_obj_list - - return pieces_to_be_treated - - def init_worker(self): - pass - - def treat_piece(self, piece): - for ele in self.mypart: - ele.track(piece) - - def finalize_turn_on_master(self, pieces_treated): - - # re-merge bunch - bunch = sum(pieces_treated) - - #finalize present turn (with non parallel part, e.g. synchrotron motion) - for ele in self.non_parallel_part: - ele.track(bunch) - - #save results - self.beam_x.append(bunch.mean_x()) - self.beam_y.append(bunch.mean_y()) - self.beam_z.append(bunch.mean_z()) - self.sx.append(bunch.sigma_x()) - self.sy.append(bunch.sigma_y()) - self.sz.append(bunch.sigma_z()) - self.epsx.append(bunch.epsn_x()*1e6) - self.epsy.append(bunch.epsn_y()*1e6) - self.epsz.append(bunch.epsn_z()) - - # prepare next turn (re-slice) - new_pieces_to_be_treated = bunch.extract_slices(self.slicer) - orders_to_pass = [] - - return orders_to_pass, new_pieces_to_be_treated - - - def execute_orders_from_master(self, orders_from_master): - pass - - - - - def finalize_simulation(self): - - # save results - import PyPARIS.myfilemanager as mfm - mfm.dict_to_h5({\ - 'beam_x':self.beam_x, - 'beam_y':self.beam_y, - 'beam_z':self.beam_z, - 'sx':self.sx, - 'sy':self.sy, - 'sz':self.sz, - 'epsx':self.epsx, - 'epsy':self.epsy, - 'epsz':self.epsz}, - 'beam_coord.h5') - - # output plots - if False: - beam_x = self.beam_x - beam_y = self.beam_y - beam_z = self.beam_z - sx = self.sx - sy = self.sy - sz = self.sz - epsx = self.epsx - epsy = self.epsy - epsz = self.epsz - - import pylab as plt - - plt.figure(2, figsize=(16, 8), tight_layout=True) - plt.subplot(2,3,1) - plt.plot(beam_x) - plt.ylabel('x [m]');plt.xlabel('Turn') - plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - plt.subplot(2,3,2) - plt.plot(beam_y) - plt.ylabel('y [m]');plt.xlabel('Turn') - plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - plt.subplot(2,3,3) - plt.plot(beam_z) - plt.ylabel('z [m]');plt.xlabel('Turn') - plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - plt.subplot(2,3,4) - plt.plot(np.fft.rfftfreq(len(beam_x), d=1.), np.abs(np.fft.rfft(beam_x))) - plt.ylabel('Amplitude');plt.xlabel('Qx') - plt.subplot(2,3,5) - plt.plot(np.fft.rfftfreq(len(beam_y), d=1.), np.abs(np.fft.rfft(beam_y))) - plt.ylabel('Amplitude');plt.xlabel('Qy') - plt.subplot(2,3,6) - plt.plot(np.fft.rfftfreq(len(beam_z), d=1.), np.abs(np.fft.rfft(beam_z))) - plt.xlim(0, 0.1) - plt.ylabel('Amplitude');plt.xlabel('Qz') - - fig, axes = plt.subplots(3, figsize=(16, 8), tight_layout=True) - twax = [plt.twinx(ax) for ax in axes] - axes[0].plot(sx) - twax[0].plot(epsx, '-g') - axes[0].set_xlabel('Turns') - axes[0].set_ylabel(r'$\sigma_x$') - twax[0].set_ylabel(r'$\varepsilon_y$') - axes[1].plot(sy) - twax[1].plot(epsy, '-g') - axes[1].set_xlabel('Turns') - axes[1].set_ylabel(r'$\sigma_x$') - twax[1].set_ylabel(r'$\varepsilon_y$') - axes[2].plot(sz) - twax[2].plot(epsz, '-g') - axes[2].set_xlabel('Turns') - axes[2].set_ylabel(r'$\sigma_x$') - twax[2].set_ylabel(r'$\varepsilon_y$') - axes[0].grid() - axes[1].grid() - axes[2].grid() - for ax in list(axes)+list(twax): - ax.ticklabel_format(useOffset=False, style='sci', scilimits=(0,0),axis='y') - plt.show() - - def piece_to_buffer(self, piece): - buf = ch.beam_2_buffer(piece) - return buf - - def buffer_to_piece(self, buf): - piece = ch.buffer_2_beam(buf) - return piece - - - diff --git a/test_ring_with_objects/Simulation_with_eclouds.py b/test_ring_with_objects/Simulation_with_eclouds.py deleted file mode 100644 index e9466d1..0000000 --- a/test_ring_with_objects/Simulation_with_eclouds.py +++ /dev/null @@ -1,242 +0,0 @@ -import sys, os -BIN = os.path.expanduser("../../") -sys.path.append(BIN) - -import numpy as np -from scipy.constants import c, e - -import PyPARIS.share_segments as shs -import PyPARIS.communication_helpers as ch - -class Simulation(object): - def __init__(self): - self.N_turns = 2 - - def init_all(self): - n_slices = 100 - z_cut = 2.5e-9*c - - self.n_slices = n_slices - self.z_cut = z_cut - - n_segments=70 - - from LHC import LHC - self.machine = LHC(machine_configuration='Injection', n_segments=n_segments, D_x=0., - RF_at='end_of_transverse') - - # We suppose that all the object that cannot be slice parallelized are at the end of the ring - i_end_parallel = len(self.machine.one_turn_map)-1 #only RF is not parallelizable - - # split the machine - sharing = shs.ShareSegments(i_end_parallel, self.ring_of_CPUs.N_nodes) - myid = self.ring_of_CPUs.myid - i_start_part, i_end_part = sharing.my_part(myid) - self.mypart = self.machine.one_turn_map[i_start_part:i_end_part] - if self.ring_of_CPUs.I_am_a_worker: - print 'I am id=%d (worker) and my part is %d long'%(myid, len(self.mypart)) - elif self.ring_of_CPUs.I_am_the_master: - self.non_parallel_part = self.machine.one_turn_map[i_end_parallel:] - print 'I am id=%d (master) and my part is %d long'%(myid, len(self.mypart)) - - - # config e-cloud - chamb_type = 'polyg' - x_aper = 2.300000e-02 - y_aper = 1.800000e-02 - filename_chm = 'pyecloud_config/LHC_chm_ver.mat' - B_multip_per_eV = [1.190000e-12] - B_multip_per_eV = np.array(B_multip_per_eV) - fraction_device = 0.65 - intensity = 1.150000e+11 - epsn_x = 2.5e-6 - epsn_y = 2.5e-6 - init_unif_edens_flag = 1 - init_unif_edens = 9.000000e+11 - N_MP_ele_init = 100000 - N_mp_max = N_MP_ele_init*4. - Dh_sc = .2e-3 - nel_mp_ref_0 = init_unif_edens*4*x_aper*y_aper/N_MP_ele_init - - import PyECLOUD.PyEC4PyHT as PyEC4PyHT - ecloud = PyEC4PyHT.Ecloud(L_ecloud=self.machine.circumference/n_segments, slicer=None, - Dt_ref=10e-12, pyecl_input_folder='pyecloud_config', - chamb_type = chamb_type, - x_aper=x_aper, y_aper=y_aper, - filename_chm=filename_chm, Dh_sc=Dh_sc, - init_unif_edens_flag=init_unif_edens_flag, - init_unif_edens=init_unif_edens, - N_mp_max=N_mp_max, - nel_mp_ref_0=nel_mp_ref_0, - B_multip=B_multip_per_eV*self.machine.p0/e*c, - slice_by_slice_mode=True) - - my_new_part = [] - self.my_list_eclouds = [] - for ele in self.mypart: - my_new_part.append(ele) - if ele in self.machine.transverse_map: - ecloud_new = ecloud.generate_twin_ecloud_with_shared_space_charge() - my_new_part.append(ecloud_new) - self.my_list_eclouds.append(ecloud_new) - self.mypart = my_new_part - - def init_master(self): - - # beam parameters - epsn_x = 2.5e-6 - epsn_y = 3.5e-6 - sigma_z = 0.05 - intensity = 1e11 - macroparticlenumber_track = 50000 - - # initialization bunch - bunch = self.machine.generate_6D_Gaussian_bunch_matched( - macroparticlenumber_track, intensity, epsn_x, epsn_y, sigma_z=sigma_z) - print 'Bunch initialized.' - - # initial slicing - from PyHEADTAIL.particles.slicing import UniformBinSlicer - self.slicer = UniformBinSlicer(n_slices = self.n_slices, z_cuts=(-self.z_cut, self.z_cut)) - - #slice for the first turn - slice_obj_list = bunch.extract_slices(self.slicer) - - #prepare to save results - self.beam_x, self.beam_y, self.beam_z = [], [], [] - self.sx, self.sy, self.sz = [], [], [] - self.epsx, self.epsy, self.epsz = [], [], [] - - pieces_to_be_treated = slice_obj_list - - return pieces_to_be_treated - - def init_worker(self): - pass - - def treat_piece(self, piece): - for ele in self.mypart: - ele.track(piece) - - def finalize_turn_on_master(self, pieces_treated): - - # re-merge bunch - bunch = sum(pieces_treated) - - #finalize present turn (with non parallel part, e.g. synchrotron motion) - for ele in self.non_parallel_part: - ele.track(bunch) - - #csave results - self.beam_x.append(bunch.mean_x()) - self.beam_y.append(bunch.mean_y()) - self.beam_z.append(bunch.mean_z()) - self.sx.append(bunch.sigma_x()) - self.sy.append(bunch.sigma_y()) - self.sz.append(bunch.sigma_z()) - self.epsx.append(bunch.epsn_x()*1e6) - self.epsy.append(bunch.epsn_y()*1e6) - self.epsz.append(bunch.epsn_z()) - - # prepare next turn (re-slice) - new_pieces_to_be_treated = bunch.extract_slices(self.slicer) - orders_to_pass = ['reset_clouds'] - - return orders_to_pass, new_pieces_to_be_treated - - - def execute_orders_from_master(self, orders_from_master): - if 'reset_clouds' in orders_from_master: - for ec in self.my_list_eclouds: ec.finalize_and_reinitialize() - - - - def finalize_simulation(self): - - # save results - import PyPARIS.myfilemanager as mfm - mfm.dict_to_h5({\ - 'beam_x':self.beam_x, - 'beam_y':self.beam_y, - 'beam_z':self.beam_z, - 'sx':self.sx, - 'sy':self.sy, - 'sz':self.sz, - 'epsx':self.epsx, - 'epsy':self.epsy, - 'epsz':self.epsz}, - 'beam_coord.h5') - - # output plots - if False: - beam_x = self.beam_x - beam_y = self.beam_y - beam_z = self.beam_z - sx = self.sx - sy = self.sy - sz = self.sz - epsx = self.epsx - epsy = self.epsy - epsz = self.epsz - - import pylab as plt - - plt.figure(2, figsize=(16, 8), tight_layout=True) - plt.subplot(2,3,1) - plt.plot(beam_x) - plt.ylabel('x [m]');plt.xlabel('Turn') - plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - plt.subplot(2,3,2) - plt.plot(beam_y) - plt.ylabel('y [m]');plt.xlabel('Turn') - plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - plt.subplot(2,3,3) - plt.plot(beam_z) - plt.ylabel('z [m]');plt.xlabel('Turn') - plt.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - plt.subplot(2,3,4) - plt.plot(np.fft.rfftfreq(len(beam_x), d=1.), np.abs(np.fft.rfft(beam_x))) - plt.ylabel('Amplitude');plt.xlabel('Qx') - plt.subplot(2,3,5) - plt.plot(np.fft.rfftfreq(len(beam_y), d=1.), np.abs(np.fft.rfft(beam_y))) - plt.ylabel('Amplitude');plt.xlabel('Qy') - plt.subplot(2,3,6) - plt.plot(np.fft.rfftfreq(len(beam_z), d=1.), np.abs(np.fft.rfft(beam_z))) - plt.xlim(0, 0.1) - plt.ylabel('Amplitude');plt.xlabel('Qz') - - fig, axes = plt.subplots(3, figsize=(16, 8), tight_layout=True) - twax = [plt.twinx(ax) for ax in axes] - axes[0].plot(sx) - twax[0].plot(epsx, '-g') - axes[0].set_xlabel('Turns') - axes[0].set_ylabel(r'$\sigma_x$') - twax[0].set_ylabel(r'$\varepsilon_y$') - axes[1].plot(sy) - twax[1].plot(epsy, '-g') - axes[1].set_xlabel('Turns') - axes[1].set_ylabel(r'$\sigma_x$') - twax[1].set_ylabel(r'$\varepsilon_y$') - axes[2].plot(sz) - twax[2].plot(epsz, '-g') - axes[2].set_xlabel('Turns') - axes[2].set_ylabel(r'$\sigma_x$') - twax[2].set_ylabel(r'$\varepsilon_y$') - axes[0].grid() - axes[1].grid() - axes[2].grid() - for ax in list(axes)+list(twax): - ax.ticklabel_format(useOffset=False, style='sci', scilimits=(0,0),axis='y') - plt.show() - - def piece_to_buffer(self, piece): - buf = ch.beam_2_buffer(piece) - return buf - - def buffer_to_piece(self, buf): - piece = ch.buffer_2_beam(buf) - return piece - - - - diff --git a/test_ring_with_objects/cleanall b/test_ring_with_objects/cleanall deleted file mode 100755 index 9363e65..0000000 --- a/test_ring_with_objects/cleanall +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -rm *.txt -rm *.err -rm *.out -rm *.cmd diff --git a/test_ring_with_objects/pyecloud_config/LHC_chm_ver.mat b/test_ring_with_objects/pyecloud_config/LHC_chm_ver.mat deleted file mode 100755 index 2a41ac7be48cdfbae810a7a7997288ddffba6cce..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1200 zcmeZu4DoSvQZUssQ1EpO(M`+DNmU5QNi0drFUqx2D9A6)tk6+#E=o--Nlj76&$CkS z&CgTtO{`QfvQRLzurf5XGBi>!GB7k^AOkRZ`tkv_9bjZ&U<1+|Kn$WmfE9>Ae4rEq z$ZSRiCWf#I1_n+bdje2!mnRRCcKbB@Eus#F8zZOL2Ssv6{JuEV{+GzX7~M}(?3ooW zojbR8vi*@m50~w+oMf+ew0enX&IJ2N%|t`z9X<9>lQ%MDsC3vrIvsjlM8Da7c6r|P zIX9~9bysyqE`C&Cuk!5Xfu9S*?DZh@ep86}{&^5}`yWH}?SBa|XMYsL-2M6xd-flO z*t;Lw=fmWo{@Bk1@yGr{Q1hVv*dGqH?-A7gJ5cw)+-CrF zuN2h%eo+6|Lj5-l>R*`uUqHhn78*VV(C|724L?|TLj3^`Z&>(~6pxjNcmzf#7<`rD zdek*7&Hk0F3dg66GJBcxKO2OmHP|O;rWI`6(rSM$XKl{5>Mr~Dz6y6vU+=SjowG!Z=vpX-S+wKm4Jjj-y!_{A0YDk z6(H*OCqne^zW_0BKhz)l-$MMcALuA3=E%gav@OGQK!9H$F8dC$k_vGp{%qls`fF_VNAn7z=?(_N1Cufy2C?X|ts- I3s18L0Di5=zW@LL diff --git a/test_ring_with_objects/pyecloud_config/machine_parameters.input b/test_ring_with_objects/pyecloud_config/machine_parameters.input deleted file mode 100755 index 8637b80..0000000 --- a/test_ring_with_objects/pyecloud_config/machine_parameters.input +++ /dev/null @@ -1,10 +0,0 @@ -# MACHINE PARAMETERS - -chamb_type = None #redefine in the script - - -track_method= 'BorisMultipole' -N_sub_steps = 5 -B_multip = [0.] - - diff --git a/test_ring_with_objects/pyecloud_config/secondary_emission_parameters.input b/test_ring_with_objects/pyecloud_config/secondary_emission_parameters.input deleted file mode 100755 index 618b83e..0000000 --- a/test_ring_with_objects/pyecloud_config/secondary_emission_parameters.input +++ /dev/null @@ -1,18 +0,0 @@ -# secondary emission model -Emax=332.; -del_max = 0. -R0 = 0. -switch_model=0 - -# hilleret model for sec. emission -E_th=35.; -sigmafit =1.0828; -mufit = 1.6636; - -switch_no_increase_energy=0 -thresh_low_energy=-1 - -scrub_en_th=20.#eV - -secondary_angle_distribution = 'cosine_3D' - diff --git a/test_ring_with_objects/pyecloud_config/simulation_parameters.input b/test_ring_with_objects/pyecloud_config/simulation_parameters.input deleted file mode 100755 index 11b8269..0000000 --- a/test_ring_with_objects/pyecloud_config/simulation_parameters.input +++ /dev/null @@ -1,63 +0,0 @@ -# SIMULATION PARAMETERS - -machine_param_file='machine_parameters.input' -secondary_emission_parameters_file='secondary_emission_parameters.input' -beam_parameters_file='beam.beam' - -logfile_path = 'logfile.txt' -progress_path = 'progress' -stopfile = 'stop' - -Dt = None -t_end = None #s (no effect if log. profile is imported from file) - -#import numpy as np -#dec_fact_out = int(np.round(5 * 25e-12/Dt)) - -lam_th = None #e-/m -Dx_hist = 1e-3 #m -r_center = 1e-3 #m - - -Dt_En_hist = 25e-9 #s -Nbin_En_hist= 2000 -En_hist_max= 2e3 #eV - -t_ion=100.; #s - -N_mp_max=250000; #size of allocated vectors - -#Regen parameters - -N_mp_regen=250000; -N_mp_regen_low=5000; -N_mp_after_regen=10000; -t_ON_regen_low=10. -fact_split=1.5; -fact_clean=1e-6; -regen_hist_cut = 1.e-4 - -N_mp_soft_regen = 75000 -N_mp_after_soft_regen = 25000 - -nel_mp_ref_0 = None #redefine in the script - -# Number of bins -Nx_regen=51;#it must be odd! -Ny_regen=51;#it must be odd! -Nvx_regen=51;#it must be odd! -Nvy_regen=101;#it must be odd! -Nvz_regen=51;#it must be odd! - - -#Sp_ch params -Dt_sc = None -Dh_sc = None -t_sc_ON=0e-9; #s -#PyPICmode = 'FFT_OpenBoundary' -sparse_solver = 'klu' - -flag_movie = 0 #1/0 -flag_sc_movie = 0 #1/0 - -save_mp_state_time_file = -1 From 892bb858a9b03ca252441f107340066d406bdbba Mon Sep 17 00:00:00 2001 From: giadarol Date: Tue, 6 Aug 2019 19:00:31 +0200 Subject: [PATCH 09/12] A fix --- ring_of_CPUs_multiturn.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ring_of_CPUs_multiturn.py b/ring_of_CPUs_multiturn.py index fb7f5d7..3af6fae 100644 --- a/ring_of_CPUs_multiturn.py +++ b/ring_of_CPUs_multiturn.py @@ -333,7 +333,7 @@ def run(self): if self.enable_orders_from_master: - self._broadcast_from_master(orders_from_master) + orders_from_master = self._broadcast_from_master(orders_from_master) # check if simulation has to be ended if 'stop' in orders_from_master: break From 325e806dab336ac8a40fb9613569aeed7ba57098 Mon Sep 17 00:00:00 2001 From: giadarol Date: Wed, 7 Aug 2019 11:17:22 +0200 Subject: [PATCH 10/12] Update README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 26b89aa..f16be65 100644 --- a/README.md +++ b/README.md @@ -1 +1,5 @@ # PyPARIS + +This package should be tested using the examples in: +https://github.com/PyCOMPLETE/PyPARIS_CoupledBunch_sim_class +https://github.com/PyCOMPLETE/PyPARIS_sim_class From 92bde29234b0fcda27f6d63c79f373ba2209a301 Mon Sep 17 00:00:00 2001 From: giadarol Date: Wed, 7 Aug 2019 11:22:43 +0200 Subject: [PATCH 11/12] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f16be65..be2d35e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # PyPARIS This package should be tested using the examples in: + https://github.com/PyCOMPLETE/PyPARIS_CoupledBunch_sim_class + https://github.com/PyCOMPLETE/PyPARIS_sim_class From e4990dcf039225bc383c836e3157318728dfe174 Mon Sep 17 00:00:00 2001 From: giadarol Date: Wed, 7 Aug 2019 11:32:12 +0200 Subject: [PATCH 12/12] Moved example to PyPARIS_CoupledBunch_sim_class --- .../000_run_sim_without_ecloud.sh | 10 - .../001_make_matrices.py | 65 --- .../002_some_checks.py | 100 ----- .../LHC_custom.py | 92 ----- .../Simulation.py | 196 --------- .../for000_run_sim.py | 12 - .../001_multibunch_without_ecloud/mystyle.py | 378 ------------------ 7 files changed, 853 deletions(-) delete mode 100644 test_multibunch/001_multibunch_without_ecloud/000_run_sim_without_ecloud.sh delete mode 100644 test_multibunch/001_multibunch_without_ecloud/001_make_matrices.py delete mode 100644 test_multibunch/001_multibunch_without_ecloud/002_some_checks.py delete mode 100644 test_multibunch/001_multibunch_without_ecloud/LHC_custom.py delete mode 100644 test_multibunch/001_multibunch_without_ecloud/Simulation.py delete mode 100644 test_multibunch/001_multibunch_without_ecloud/for000_run_sim.py delete mode 100644 test_multibunch/001_multibunch_without_ecloud/mystyle.py diff --git a/test_multibunch/001_multibunch_without_ecloud/000_run_sim_without_ecloud.sh b/test_multibunch/001_multibunch_without_ecloud/000_run_sim_without_ecloud.sh deleted file mode 100644 index 2b0f73d..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/000_run_sim_without_ecloud.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/bash - -# Run MPI -# mpiexec -n 8 python for000_run_sim.py - -# Run multiproc -../../../PyPARIS/multiprocexec.py -n 4 sim_class=Simulation.Simulation --multiturn - -# Run single core -#python for000_run_sim.py diff --git a/test_multibunch/001_multibunch_without_ecloud/001_make_matrices.py b/test_multibunch/001_multibunch_without_ecloud/001_make_matrices.py deleted file mode 100644 index 828f494..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/001_make_matrices.py +++ /dev/null @@ -1,65 +0,0 @@ -import sys, os -sys.path.append('../../../') - -import numpy as np - - -sim_folder = '.' -tag = 'noecloud' -n_rings = 4 - -to_be_saved = [ - 'epsn_x', - 'epsn_y', - 'epsn_z', - 'macroparticlenumber', - 'mean_dp', - 'mean_x', - 'mean_xp', - 'mean_y', - 'mean_yp', - 'mean_z', - 'sigma_dp', - 'sigma_x', - 'sigma_y', - 'sigma_z'] - - - -list_files = [sim_folder+'/bunch_monitor_ring%03d.h5'%ii for ii in range(n_rings)] - -import PyPARIS.myfilemanager as mfm -dict_data = mfm.monitorh5list_to_dict(list_files, permissive=True) - -print 'Data loaded!' - -n_turns = int(np.max(dict_data['i_turn']))+1 -n_bunches = int(np.max(dict_data['i_bunch']))+1 - -list_bunches = [] -for i_bunch_obs in range(n_bunches): - print('Bunch %d/%d'%(i_bunch_obs, n_bunches)) - dict_bunch = {kk:np.zeros(n_turns, dtype=np.float64)+np.nan for kk in dict_data.keys()} - for ii in xrange(len(dict_data['i_bunch'])): - if int(dict_data['i_bunch'][ii]) == int(i_bunch_obs): - i_turn = int(dict_data['i_turn'][ii]) - for kk in dict_data.keys(): - dict_bunch[kk][i_turn] = dict_data[kk][ii] - - list_bunches.append(dict_bunch) - - -dict_matrices = {kk: np.zeros((n_turns, n_bunches)) for kk in to_be_saved} - -for i_bunch_obs in range(n_bunches): - n_turns_this = len(list_bunches[i_bunch_obs]['epsn_x']) - mask_notnan = ~np.isnan(list_bunches[i_bunch_obs]['macroparticlenumber']) - - for kk in to_be_saved: - dict_matrices[kk][:n_turns_this, i_bunch_obs][mask_notnan] =\ - list_bunches[i_bunch_obs][kk][mask_notnan] - - -import scipy.io as sio -sio.savemat(tag+'_matrices.mat', dict_matrices, oned_as='row') - diff --git a/test_multibunch/001_multibunch_without_ecloud/002_some_checks.py b/test_multibunch/001_multibunch_without_ecloud/002_some_checks.py deleted file mode 100644 index dc7a7fb..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/002_some_checks.py +++ /dev/null @@ -1,100 +0,0 @@ -import sys, os -sys.path.append('../../../') - - -import numpy as np -import matplotlib.pyplot as plt -from matplotlib.ticker import MaxNLocator - -import PyPARIS.myfilemanager as mfm - -import mystyle as ms - -tag = 'noecloud' -i_bunch = 3 - -flag_check_damp_time = True -tau_damp_x = 200. -tau_damp_y = 100. - -flag_check_Qs = True -Q_s = 5.664e-03 - -ob = mfm.myloadmat_to_obj(tag+'_matrices.mat') - -plt.close('all') - -# Plot transverse positions -fig1 = plt.figure(1, figsize=(8,6*1.2)) -fig1.set_facecolor('w') -ms.mystyle_arial(fontsz=16) - -axx = fig1.add_subplot(2,1,1) -axy = fig1.add_subplot(2,1,2, sharex=axx) - -axx.plot(ob.mean_x[:, i_bunch]) -axy.plot(ob.mean_y[:, i_bunch]) - -if flag_check_damp_time: - turn_num = np.arange(0, len(ob.mean_x[:, i_bunch]), dtype=np.float) - axx.plot(ob.mean_x[0, i_bunch]*np.exp(-turn_num/tau_damp_x), - linewidth=2, color='red', linestyle='--', - label=r'Damping time = %.0f turns'%tau_damp_x) - axy.plot(ob.mean_y[0, i_bunch]*np.exp(-turn_num/tau_damp_y), - linewidth=2, color='red', linestyle='--', - label=r'Damping time = %.0f turns'%tau_damp_y) - -axx.legend(prop={'size':14}).draggable() -axy.legend(prop={'size':14}).draggable() - -axx.set_ylabel('x [m]') -axy.set_ylabel('y [m]') -axy.set_xlabel('Turn') - -# Plot transverse spectra -fig2 = plt.figure(2, figsize=(8,6*1.2)) -fig2.set_facecolor('w') - -axfx = fig2.add_subplot(2,1,1) -axfy = fig2.add_subplot(2,1,2, sharex=axfx) - -spectx = np.abs(np.fft.rfft(ob.mean_x[:, i_bunch])) -specty = np.abs(np.fft.rfft(ob.mean_y[:, i_bunch])) -freq = np.fft.rfftfreq(len(ob.mean_x[:, i_bunch])) - -axfx.plot(freq, spectx) -axfy.plot(freq, specty) - -# Check longitudinal plane -fig3 = plt.figure(3, figsize=(8,6*1.2)) -fig3.set_facecolor('w') -axz = fig3.add_subplot(2,1,1, sharex=axx) -axfz = fig3.add_subplot(2,1,2) - -axz.plot(ob.mean_z[:-10, i_bunch]) -spectz = np.abs(np.fft.rfft(ob.mean_z[:-10, i_bunch])) -spectz[0] = 0. # I am non interested in the average -freqz = np.fft.rfftfreq(len(ob.mean_x[:-10, i_bunch])) -axfz.plot(freqz, spectz) -axfz.axvline(x=Q_s) - -for ax in [axx, axy, axfx, axfy, axz, axfz]: - ax.ticklabel_format(style='sci', scilimits=(0,0),axis='y') - -for ax in [axx, axy, axfx, axfy, axz, axfz]: - ax.yaxis.set_major_locator(MaxNLocator(5)) - -for ax in [axx, axy, axfx, axfy, axz, axfz]: - ax.grid(True) - -for fig in [fig1, fig2, fig3]: - fig.suptitle('Bunch %d'%i_bunch) - fig.subplots_adjust( - top=0.885, - bottom=0.1, - left=0.125, - right=0.9, - hspace=0.345, - wspace=0.2) - -plt.show() diff --git a/test_multibunch/001_multibunch_without_ecloud/LHC_custom.py b/test_multibunch/001_multibunch_without_ecloud/LHC_custom.py deleted file mode 100644 index ebc1e89..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/LHC_custom.py +++ /dev/null @@ -1,92 +0,0 @@ -from PyHEADTAIL.machines.synchrotron import BasicSynchrotron -import numpy as np -from scipy.constants import c, e, m_p - -class EmptyObject(object): - pass - -class LHC(BasicSynchrotron): - - def __init__(self, n_segments, machine_configuration, **kwargs): - - pp = EmptyObject() - - pp.machine_configuration = machine_configuration - pp.n_segments = n_segments - - pp.circumference = 35640*2.5e-9*c - pp.longitudinal_mode = 'non-linear' - pp.p_increment = 0. - pp.charge = e - pp.mass = m_p - pp.alpha = 3.225e-04 - - - if pp.machine_configuration =='HLLHC-injection': - pp.alpha_x = 0. - pp.beta_x = 92.7 - pp.D_x = 0. - pp.alpha_y = 0. - pp.beta_y = 93.2 - pp.D_y = 0. - - pp.accQ_x = 62.28 - pp.accQ_y = 60.31 - - pp.h_RF = 35640 - pp.V_RF = 8e6 - pp.dphi_RF = 0. - - pp.p0 = 450.e9 * e /c - - elif pp.machine_configuration =='HLLHC-collision': - pp.alpha_x = 0. - pp.beta_x = 92.7 - pp.D_x = 0. - pp.alpha_y = 0. - pp.beta_y = 93.2 - pp.D_y = 0. - - pp.accQ_x = 62.31 - pp.accQ_y = 60.32 - - pp.h_RF = 35640 - pp.V_RF = 16e6 - pp.dphi_RF = 0. - - pp.p0 = 7000e9 * e /c - - - else: - raise ValueError('ERROR: unknown machine configuration', machine_configuration) - - # detunings - pp.Qp_x = 0 - pp.Qp_y = 0 - - pp.app_x = 0 - pp.app_y = 0 - pp.app_xy = 0 - - for attr in kwargs.keys(): - if kwargs[attr] is not None: - if type(kwargs[attr]) is list or type(kwargs[attr]) is np.ndarray: - str2print = '[%s ...]'%repr(kwargs[attr][0]) - else: - str2print = repr(kwargs[attr]) - self.prints('Synchrotron init. From kwargs: %s = %s' - % (attr, str2print)) - - if not hasattr(pp, attr): - raise NameError("I don't understand %s"%attr) - - setattr(pp, attr, kwargs[attr]) - - - super(LHC, self).__init__(optics_mode='smooth', circumference=pp.circumference, n_segments=pp.n_segments, - alpha_x=pp.alpha_x, beta_x=pp.beta_x, D_x=pp.D_x, alpha_y=pp.alpha_y, beta_y=pp.beta_y, D_y=pp.D_y, - accQ_x=pp.accQ_x, accQ_y=pp.accQ_y, Qp_x=pp.Qp_x, Qp_y=pp.Qp_y, app_x=pp.app_x, app_y=pp.app_y, app_xy=pp.app_xy, - alpha_mom_compaction=pp.alpha, longitudinal_mode=pp.longitudinal_mode, - h_RF=np.atleast_1d(pp.h_RF), V_RF=np.atleast_1d(pp.V_RF), dphi_RF=np.atleast_1d(pp.dphi_RF), p0=pp.p0, p_increment=pp.p_increment, - charge=pp.charge, mass=pp.mass, RF_at='end_of_transverse') - diff --git a/test_multibunch/001_multibunch_without_ecloud/Simulation.py b/test_multibunch/001_multibunch_without_ecloud/Simulation.py deleted file mode 100644 index 7f2bb26..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/Simulation.py +++ /dev/null @@ -1,196 +0,0 @@ -import sys, os -BIN = os.path.expanduser("../../../") -sys.path.append(BIN) -import types - -import numpy as np -from scipy.constants import c - -import PyPARIS.communication_helpers as ch -import PyPARIS.share_segments as shs -import PyPARIS.slicing_tool as sl - -verbose = False - -sigma_z_bunch = 1e-2 - -machine_configuration = 'HLLHC-injection' -n_segments = 4 - -Qp_x = 0. -Qp_y = 0. - -flag_aperture = True - -enable_transverse_damper = True -dampingrate_x = 200. -dampingrate_y = 100. - -# Beam properties -non_linear_long_matching = False - -bunch_intensity = 1e11 -epsn_x = 2.5e-6 -epsn_y = 2.5e-6 -sigma_z = sigma_z_bunch - -#Filling pattern: here head is left and tail is right -b_spac_s = 25e-9 -filling_pattern = 4*([1.]) - -macroparticlenumber = 10000 -min_inten_slice4EC = 1e7 - -x_kick_in_sigmas = 0.25 -y_kick_in_sigmas = 0.25 -z_kick_in_m = 0.005 - - -target_size_internal_grid_sigma = 10. - -enable_kick_x = True -enable_kick_y = False - -pickle_beam = False - - -class Simulation(object): - def __init__(self): - self.N_turns = 2000 - self.N_buffer_float_size = 10000000 - self.N_buffer_int_size = 20 - self.N_parellel_rings = 4 - - self.n_slices_per_bunch = 200 - self.z_cut_slicing = 3*sigma_z_bunch - self.N_pieces_per_transfer = 300 - - - def init_all(self): - - print('Exec init...') - - self.ring_of_CPUs.verbose = verbose - - from LHC_custom import LHC - self.machine = LHC(n_segments = n_segments, machine_configuration = machine_configuration, - Qp_x=Qp_x, Qp_y=Qp_y) - print('Expected Qs = %.3e'%self.machine.Q_s) - self.n_non_parallelizable = 1 #RF - - inj_optics = self.machine.transverse_map.get_injection_optics() - sigma_x_smooth = np.sqrt(inj_optics['beta_x']*epsn_x/self.machine.betagamma) - sigma_y_smooth = np.sqrt(inj_optics['beta_y']*epsn_y/self.machine.betagamma) - - if flag_aperture: - # setup transverse losses (to "protect" the ecloud) - import PyHEADTAIL.aperture.aperture as aperture - apt_xy = aperture.EllipticalApertureXY(x_aper=target_size_internal_grid_sigma*sigma_x_smooth, - y_aper=target_size_internal_grid_sigma*sigma_x_smooth) - self.machine.one_turn_map.append(apt_xy) - self.n_non_parallelizable +=1 - - if enable_transverse_damper: - # setup transverse damper - from PyHEADTAIL.feedback.transverse_damper import TransverseDamper - damper = TransverseDamper(dampingrate_x=dampingrate_x, dampingrate_y=dampingrate_y) - self.machine.one_turn_map.append(damper) - self.n_non_parallelizable +=1 - - # split the machine - i_end_parallel = len(self.machine.one_turn_map)-self.n_non_parallelizable - sharing = shs.ShareSegments(i_end_parallel, self.ring_of_CPUs.N_nodes_per_ring) - i_start_part, i_end_part = sharing.my_part(self.ring_of_CPUs.myid_in_ring) - self.mypart = self.machine.one_turn_map[i_start_part:i_end_part] - - if self.ring_of_CPUs.I_am_at_end_ring: - self.non_parallel_part = self.machine.one_turn_map[i_end_parallel:] - print('Hello, I am %d.%d, my part looks like: %s.'%(self.ring_of_CPUs.myring, self.ring_of_CPUs.myid_in_ring, self.mypart)) - - - - - def init_master(self): - - print('Building the beam!') - - from scipy.constants import c as clight, e as qe - from PyHEADTAIL.particles.slicing import UniformBinSlicer - - import gen_multibunch_beam as gmb - list_bunches = gmb.gen_matched_multibunch_beam(self.machine, macroparticlenumber, filling_pattern, b_spac_s, - bunch_intensity, epsn_x, epsn_y, sigma_z, non_linear_long_matching, min_inten_slice4EC) - - if pickle_beam: - import pickle - with open('init_beam.pkl', 'w') as fid: - pickle.dump({'list_bunches': list_bunches}, fid) - - # compute and apply initial displacements - inj_opt = self.machine.transverse_map.get_injection_optics() - sigma_x = np.sqrt(inj_opt['beta_x']*epsn_x/self.machine.betagamma) - sigma_y = np.sqrt(inj_opt['beta_y']*epsn_y/self.machine.betagamma) - x_kick = x_kick_in_sigmas*sigma_x - y_kick = y_kick_in_sigmas*sigma_y - for bunch in list_bunches: - bunch.x += x_kick - bunch.y += y_kick - bunch.z += z_kick_in_m - - - return list_bunches - - def init_start_ring(self): - stats_to_store = [ - 'mean_x', 'mean_xp', 'mean_y', 'mean_yp', 'mean_z', 'mean_dp', - 'sigma_x', 'sigma_y', 'sigma_z','sigma_dp', 'epsn_x', 'epsn_y', - 'epsn_z', 'macroparticlenumber', - 'i_bunch', 'i_turn'] - - n_stored_turns = len(filling_pattern)*(self.ring_of_CPUs.N_turns/self.ring_of_CPUs.N_parellel_rings + self.ring_of_CPUs.N_parellel_rings) - - from PyHEADTAIL.monitors.monitors import BunchMonitor - self.bunch_monitor = BunchMonitor('bunch_monitor_ring%03d'%self.ring_of_CPUs.myring, - n_stored_turns, - {'Comment':'PyHDTL simulation'}, - write_buffer_every = 1, - stats_to_store = stats_to_store) - - def perform_bunch_operations_at_start_ring(self, bunch): - # Attach bound methods to monitor i_bunch and i_turns - # (In the future we might upgrade PyHEADTAIL to pass the lambda to the monitor) - if bunch.macroparticlenumber>0: - bunch.i_bunch = types.MethodType(lambda self: self.slice_info['i_bunch'], bunch) - bunch.i_turn = types.MethodType(lambda self: self.slice_info['i_turn'], bunch) - self.bunch_monitor.dump(bunch) - - def slice_bunch_at_start_ring(self, bunch): - list_slices = sl.slice_a_bunch(bunch, self.z_cut_slicing, self.n_slices_per_bunch) - return list_slices - - def treat_piece(self, piece): - for ele in self.mypart: - ele.track(piece) - - def merge_slices_at_end_ring(self, list_slices): - bunch = sl.merge_slices_into_bunch(list_slices) - return bunch - - def perform_bunch_operations_at_end_ring(self, bunch): - #finalize present turn (with non parallel part, e.g. synchrotron motion) - if bunch.macroparticlenumber>0: - for ele in self.non_parallel_part: - ele.track(bunch) - - - def piece_to_buffer(self, piece): - buf = ch.beam_2_buffer(piece) - return buf - - def buffer_to_piece(self, buf): - piece = ch.buffer_2_beam(buf) - return piece - - - - diff --git a/test_multibunch/001_multibunch_without_ecloud/for000_run_sim.py b/test_multibunch/001_multibunch_without_ecloud/for000_run_sim.py deleted file mode 100644 index 81bb9fc..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/for000_run_sim.py +++ /dev/null @@ -1,12 +0,0 @@ -import os, sys -import sys, os -BIN = os.path.expanduser("../../../") -sys.path.append(BIN) - - -from PyPARIS.ring_of_CPUs_multiturn import RingOfCPUs_multiturn -import Simulation - -simulation_content = Simulation.Simulation() -myCPUring = RingOfCPUs_multiturn(simulation_content) -myCPUring.run() diff --git a/test_multibunch/001_multibunch_without_ecloud/mystyle.py b/test_multibunch/001_multibunch_without_ecloud/mystyle.py deleted file mode 100644 index 061d3cc..0000000 --- a/test_multibunch/001_multibunch_without_ecloud/mystyle.py +++ /dev/null @@ -1,378 +0,0 @@ -from matplotlib import rc, rcdefaults, RcParams -import matplotlib -import pylab as pl -from colorsys import hsv_to_rgb -import matplotlib.pyplot as plt -import numpy as np - - -def mystyle(fontsz=16): - rcdefaults() - version = matplotlib.__version__.split('.')[0] - if version == '2': - print('Reverting matplotlib look to v1.5') - plt.rcParams['axes.autolimit_mode'] = 'round_numbers' - plt.rcParams['axes.xmargin'] = 0 - plt.rcParams['axes.ymargin'] = 0 - plt.rcParams['xtick.direction'] = 'in' - plt.rcParams['ytick.direction'] = 'in' - plt.rcParams['xtick.top'] = True - plt.rcParams['ytick.right'] = True - plt.rcParams['legend.numpoints'] = 1 - plt.style.use('classic') - - - - font = {#'family' : 'normal', - #'weight' : 'bold', - 'size' : fontsz} -# print fontsz - rc('font', **font) - -def mystyle_arial(fontsz=16, dist_tick_lab=10): - - mystyle(fontsz) - rc('font',**{'family':'sans-serif','sans-serif':['arial'], 'size':fontsz}) - rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=dist_tick_lab) - -def sciy(): - pl.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='y') - -def scix(): - pl.gca().ticklabel_format(style='sci', scilimits=(0,0),axis='x') - -def colorprog(i_prog, Nplots, v1 = .9, v2 = 1., cm='hsv'): - if hasattr(Nplots, '__len__'): - Nplots = len(Nplots) - if cm == 'hsv': - return hsv_to_rgb(float(i_prog)/float(Nplots), v1, v2) - elif cm == 'rainbow': - return [pl.cm.rainbow(k) for k in np.linspace(0, 1, Nplots)][i_prog] - else: - raise ValueError('What?!') - -def comb_legend(sp1, sp2, *args, **kwargs): - """ - Combine legends for twinx()ed subplots - """ - lines, labels = sp1.get_legend_handles_labels() - lines2, labels2 = sp2.get_legend_handles_labels() - sp2.legend(lines + lines2, labels + labels2, *args, **kwargs) - - -def mystyle_2(fontsz=16, dist_tick_lab=10, figsize=(12,10)): - rcdefaults() - RcParams[u'axes.grid'] = True - RcParams[u'axes.linewidth'] = 2.0 - RcParams[u'figure.facecolor'] = 'w' - - rc('font',**{'family':'sans-serif','sans-serif':['arial'], 'size':fontsz}) - rc(('xtick.major','xtick.minor','ytick.major','ytick.minor'), pad=dist_tick_lab) - - -def figure(title, figs=None, figsize=(12, 10), **kwargs): - fig = plt.figure(figsize=figsize, **kwargs) - fig.canvas.set_window_title(title) - if figs != None: - figs.append(fig) - fig.patch.set_facecolor('w') - plt.suptitle(title, fontsize=16) - fig.subplots_adjust(left=0.07, right=0.80, wspace=0.5) - return fig - - -""" -RcParams - - -RcParams({u'agg.path.chunksize': 0, - u'animation.avconv_args': [], - u'animation.avconv_path': u'avconv', - u'animation.bitrate': -1, - u'animation.codec': u'mpeg4', - u'animation.convert_args': [], - u'animation.convert_path': u'convert', - u'animation.ffmpeg_args': [], - u'animation.ffmpeg_path': u'ffmpeg', - u'animation.frame_format': u'png', - u'animation.html': u'none', - u'animation.mencoder_args': [], - u'animation.mencoder_path': u'mencoder', - u'animation.writer': u'ffmpeg', - u'axes.axisbelow': False, - u'axes.edgecolor': u'k', - u'axes.facecolor': u'w', - u'axes.formatter.limits': [-7, 7], - u'axes.formatter.use_locale': False, - u'axes.formatter.use_mathtext': False, - u'axes.formatter.useoffset': True, - u'axes.grid': False, - u'axes.grid.axis': u'both', - u'axes.grid.which': u'major', - u'axes.hold': True, - u'axes.labelcolor': u'k', - u'axes.labelpad': 5.0, - u'axes.labelsize': u'medium', - u'axes.labelweight': u'normal', - u'axes.linewidth': 1.0, - u'axes.prop_cycle': cycler(u'color', [u'b', u'g', u'r', u'c', u'm', u'y', u'k']), - u'axes.spines.bottom': True, - u'axes.spines.left': True, - u'axes.spines.right': True, - u'axes.spines.top': True, - u'axes.titlesize': u'large', - u'axes.titleweight': u'normal', - u'axes.unicode_minus': True, - u'axes.xmargin': 0.0, - u'axes.ymargin': 0.0, - u'axes3d.grid': True, - u'backend': u'Qt4Agg', - u'backend.qt4': u'PyQt4', - u'backend.qt5': u'PyQt5', - u'backend_fallback': True, - u'boxplot.bootstrap': None, - u'boxplot.boxprops.color': u'b', - u'boxplot.boxprops.linestyle': u'-', - u'boxplot.boxprops.linewidth': 1.0, - u'boxplot.capprops.color': u'k', - u'boxplot.capprops.linestyle': u'-', - u'boxplot.capprops.linewidth': 1.0, - u'boxplot.flierprops.color': u'b', - u'boxplot.flierprops.linestyle': u'none', - u'boxplot.flierprops.linewidth': 1.0, - u'boxplot.flierprops.marker': u'+', - u'boxplot.flierprops.markeredgecolor': u'k', - u'boxplot.flierprops.markerfacecolor': u'b', - u'boxplot.flierprops.markersize': 6.0, - u'boxplot.meanline': False, - u'boxplot.meanprops.color': u'r', - u'boxplot.meanprops.linestyle': u'-', - u'boxplot.meanprops.linewidth': 1.0, - u'boxplot.medianprops.color': u'r', - u'boxplot.medianprops.linestyle': u'-', - u'boxplot.medianprops.linewidth': 1.0, - u'boxplot.notch': False, - u'boxplot.patchartist': False, - u'boxplot.showbox': True, - u'boxplot.showcaps': True, - u'boxplot.showfliers': True, - u'boxplot.showmeans': False, - u'boxplot.vertical': True, - u'boxplot.whiskerprops.color': u'b', - u'boxplot.whiskerprops.linestyle': u'--', - u'boxplot.whiskerprops.linewidth': 1.0, - u'boxplot.whiskers': 1.5, - u'contour.corner_mask': True, - u'contour.negative_linestyle': u'dashed', - u'datapath': u'/afs/cern.ch/user/p/pyhdtl/public/anaconda/lib/python2.7/site-packages/matplotlib/mpl-data', - u'docstring.hardcopy': False, - u'errorbar.capsize': 3.0, - u'examples.directory': u'', - u'figure.autolayout': False, - u'figure.dpi': 80.0, - u'figure.edgecolor': u'w', - u'figure.facecolor': u'0.75', - u'figure.figsize': [8.0, 6.0], - u'figure.frameon': True, - u'figure.max_open_warning': 20, - u'figure.subplot.bottom': 0.1, - u'figure.subplot.hspace': 0.2, - u'figure.subplot.left': 0.125, - u'figure.subplot.right': 0.9, - u'figure.subplot.top': 0.9, - u'figure.subplot.wspace': 0.2, - u'figure.titlesize': u'medium', - u'figure.titleweight': u'normal', - u'font.cursive': [u'Apple Chancery', - u'Textile', - u'Zapf Chancery', - u'Sand', - u'Script MT', - u'Felipa', - u'cursive'], - u'font.family': [u'sans-serif'], - u'font.fantasy': [u'Comic Sans MS', - u'Chicago', - u'Charcoal', - u'ImpactWestern', - u'Humor Sans', - u'fantasy'], - u'font.monospace': [u'Bitstream Vera Sans Mono', - u'DejaVu Sans Mono', - u'Andale Mono', - u'Nimbus Mono L', - u'Courier New', - u'Courier', - u'Fixed', - u'Terminal', - u'monospace'], - u'font.sans-serif': [u'Bitstream Vera Sans', - u'DejaVu Sans', - u'Lucida Grande', - u'Verdana', - u'Geneva', - u'Lucid', - u'Arial', - u'Helvetica', - u'Avant Garde', - u'sans-serif'], - u'font.serif': [u'Bitstream Vera Serif', - u'DejaVu Serif', - u'New Century Schoolbook', - u'Century Schoolbook L', - u'Utopia', - u'ITC Bookman', - u'Bookman', - u'Nimbus Roman No9 L', - u'Times New Roman', - u'Times', - u'Palatino', - u'Charter', - u'serif'], - u'font.size': 12.0, - u'font.stretch': u'normal', - u'font.style': u'normal', - u'font.variant': u'normal', - u'font.weight': u'normal', - u'grid.alpha': 1.0, - u'grid.color': u'k', - u'grid.linestyle': u':', - u'grid.linewidth': 0.5, - u'image.aspect': u'equal', - u'image.cmap': u'jet', - u'image.composite_image': True, - u'image.interpolation': u'bilinear', - u'image.lut': 256, - u'image.origin': u'upper', - u'image.resample': False, - u'interactive': True, - u'keymap.all_axes': [u'a'], - u'keymap.back': [u'left', u'c', u'backspace'], - u'keymap.forward': [u'right', u'v'], - u'keymap.fullscreen': [u'f', u'ctrl+f'], - u'keymap.grid': [u'g'], - u'keymap.home': [u'h', u'r', u'home'], - u'keymap.pan': [u'p'], - u'keymap.quit': [u'ctrl+w', u'cmd+w'], - u'keymap.save': [u's', u'ctrl+s'], - u'keymap.xscale': [u'k', u'L'], - u'keymap.yscale': [u'l'], - u'keymap.zoom': [u'o'], - u'legend.borderaxespad': 0.5, - u'legend.borderpad': 0.4, - u'legend.columnspacing': 2.0, - u'legend.edgecolor': u'inherit', - u'legend.facecolor': u'inherit', - u'legend.fancybox': False, - u'legend.fontsize': u'large', - u'legend.framealpha': None, - u'legend.frameon': True, - u'legend.handleheight': 0.7, - u'legend.handlelength': 2.0, - u'legend.handletextpad': 0.8, - u'legend.isaxes': True, - u'legend.labelspacing': 0.5, - u'legend.loc': u'upper right', - u'legend.markerscale': 1.0, - u'legend.numpoints': 2, - u'legend.scatterpoints': 3, - u'legend.shadow': False, - u'lines.antialiased': True, - u'lines.color': u'b', - u'lines.dash_capstyle': u'butt', - u'lines.dash_joinstyle': u'round', - u'lines.linestyle': u'-', - u'lines.linewidth': 1.0, - u'lines.marker': u'None', - u'lines.markeredgewidth': 0.5, - u'lines.markersize': 6.0, - u'lines.solid_capstyle': u'projecting', - u'lines.solid_joinstyle': u'round', - u'markers.fillstyle': u'full', - u'mathtext.bf': u'serif:bold', - u'mathtext.cal': u'cursive', - u'mathtext.default': u'it', - u'mathtext.fallback_to_cm': True, - u'mathtext.fontset': u'cm', - u'mathtext.it': u'serif:italic', - u'mathtext.rm': u'serif', - u'mathtext.sf': u'sans\\-serif', - u'mathtext.tt': u'monospace', - u'nbagg.transparent': True, - u'patch.antialiased': True, - u'patch.edgecolor': u'k', - u'patch.facecolor': u'b', - u'patch.linewidth': 1.0, - u'path.effects': [], - u'path.simplify': True, - u'path.simplify_threshold': 0.1111111111111111, - u'path.sketch': None, - u'path.snap': True, - u'pdf.compression': 6, - u'pdf.fonttype': 3, - u'pdf.inheritcolor': False, - u'pdf.use14corefonts': False, - u'pgf.debug': False, - u'pgf.preamble': [], - u'pgf.rcfonts': True, - u'pgf.texsystem': u'xelatex', - u'plugins.directory': u'.matplotlib_plugins', - u'polaraxes.grid': True, - u'ps.distiller.res': 6000, - u'ps.fonttype': 3, - u'ps.papersize': u'letter', - u'ps.useafm': False, - u'ps.usedistiller': False, - u'savefig.bbox': None, - u'savefig.directory': u'~', - u'savefig.dpi': 100.0, - u'savefig.edgecolor': u'w', - u'savefig.facecolor': u'w', - u'savefig.format': u'png', - u'savefig.frameon': True, - u'savefig.jpeg_quality': 95, - u'savefig.orientation': u'portrait', - u'savefig.pad_inches': 0.1, - u'savefig.transparent': False, - u'svg.fonttype': u'path', - u'svg.image_inline': True, - u'svg.image_noscale': False, - u'text.antialiased': True, - u'text.color': u'k', - u'text.dvipnghack': None, - u'text.hinting': u'auto', - u'text.hinting_factor': 8, - u'text.latex.preamble': [], - u'text.latex.preview': False, - u'text.latex.unicode': False, - u'text.usetex': False, - u'timezone': u'UTC', - u'tk.window_focus': False, - u'toolbar': u'toolbar2', - u'verbose.fileo': u'sys.stdout', - u'verbose.level': u'silent', - u'webagg.open_in_browser': True, - u'webagg.port': 8988, - u'webagg.port_retries': 50, - u'xtick.color': u'k', - u'xtick.direction': u'in', - u'xtick.labelsize': u'medium', - u'xtick.major.pad': 4.0, - u'xtick.major.size': 4.0, - u'xtick.major.width': 0.5, - u'xtick.minor.pad': 4.0, - u'xtick.minor.size': 2.0, - u'xtick.minor.visible': False, - u'xtick.minor.width': 0.5, - u'ytick.color': u'k', - u'ytick.direction': u'in', - u'ytick.labelsize': u'medium', - u'ytick.major.pad': 4.0, - u'ytick.major.size': 4.0, - u'ytick.major.width': 0.5, - u'ytick.minor.pad': 4.0, - u'ytick.minor.size': 2.0, - u'ytick.minor.visible': False, - u'ytick.minor.width': 0.5}) -""" -