diff --git a/002_change_version_number.py b/002_change_version_number.py index 21a18cf9..b29cf671 100644 --- a/002_change_version_number.py +++ b/002_change_version_number.py @@ -4,7 +4,7 @@ for filename in files: if filename[-3:] == '.py': - print filename + print(filename) os.system('cp %s %s'%(filename, filename + 'old')) with open(filename) as fid: content = fid.read() diff --git a/003_change_preamble.py b/003_change_preamble.py index 44b7ae78..71a4eaab 100644 --- a/003_change_preamble.py +++ b/003_change_preamble.py @@ -109,5 +109,5 @@ with open(path, 'w') as f: f.writelines(new_lines) - print('Modified %s' % path) + print(('Modified %s' % path)) diff --git a/BassErsk.py b/BassErsk.py index 7dd724c4..53a7601c 100644 --- a/BassErsk.py +++ b/BassErsk.py @@ -1,6 +1,6 @@ from cmath import * from numpy import * -from errffor import errf +from .errffor import errf def wfun(z): diff --git a/MP_system.py b/MP_system.py index a500f298..6e7d55b3 100644 --- a/MP_system.py +++ b/MP_system.py @@ -52,7 +52,7 @@ import numpy as np from numpy.random import rand -import hist_for as histf +from . import hist_for as histf from scipy.constants import e, m_e @@ -134,7 +134,7 @@ def __init__(self, N_mp_max, nel_mp_ref_0, fact_split, fact_clean, def clean_small_MPs(self): - print "Cloud %s: Start clean. N_mp=%d Nel=%e"%(self.name, self.N_mp, np.sum(self.nel_mp[0:self.N_mp])) + print("Cloud %s: Start clean. N_mp=%d Nel=%e"%(self.name, self.N_mp, np.sum(self.nel_mp[0:self.N_mp]))) flag_clean = (self.nel_mp < self.nel_mp_cl_th) flag_keep = ~(flag_clean) @@ -154,11 +154,11 @@ def clean_small_MPs(self): if self.flag_lifetime_hist: self.t_last_impact[0:self.N_mp] = np.array(self.t_last_impact[flag_keep].copy()) - print "Cloud %s: Done clean. N_mp=%d Nel=%e"%(self.name, self.N_mp, np.sum(self.nel_mp[0:self.N_mp])) + print("Cloud %s: Done clean. N_mp=%d Nel=%e"%(self.name, self.N_mp, np.sum(self.nel_mp[0:self.N_mp]))) if self.N_mp == 0: self.set_nel_mp_ref(self.nel_mp_ref_0) - print('Cloud %s: nel_mp_ref set to nel_mp_ref_0'%self.name) + print(('Cloud %s: nel_mp_ref set to nel_mp_ref_0'%self.name)) def set_nel_mp_ref(self, val): self.nel_mp_ref = val @@ -176,7 +176,7 @@ def perform_soft_regeneration(self, target_N_mp): new_nel_mp_ref = self.nel_mp_ref_0 #if new_nel_mp_ref>self.nel_mp_ref_0:removed from version 3.16 - print 'Cloud %s: Start SOFT regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg) + print('Cloud %s: Start SOFT regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg)) self.set_nel_mp_ref(new_nel_mp_ref) @@ -204,13 +204,13 @@ def perform_soft_regeneration(self, target_N_mp): correct_fact = chrg_before / chrg_after - print 'Cloud %s: Applied correction factor = %e'%(self.name, correct_fact) + print('Cloud %s: Applied correction factor = %e'%(self.name, correct_fact)) self.nel_mp[0:self.N_mp] = self.nel_mp[0:self.N_mp] * correct_fact chrg = np.sum(self.nel_mp) erg = np.sum(0.5 / np.abs(self.charge / self.mass) * self.nel_mp[0:self.N_mp] * (self.vx_mp[0:self.N_mp] * self.vx_mp[0:self.N_mp] + self.vy_mp[0:self.N_mp] * self.vy_mp[0:self.N_mp] + self.vz_mp[0:self.N_mp] * self.vz_mp[0:self.N_mp])) - print 'Cloud %s: Done SOFT regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg) + print('Cloud %s: Done SOFT regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg)) def check_for_soft_regeneration(self): @@ -222,7 +222,7 @@ def check_for_async_regeneration(self): if self.flag_async_regen: if self.N_mp > self.N_mp_async_regen: - print('Cloud %s: Asynchronous clean and regeneration.' %self.name) + print(('Cloud %s: Asynchronous clean and regeneration.' %self.name)) self.clean_small_MPs() if self.N_mp > self.N_mp_async_regen: self.perform_soft_regeneration(target_N_mp=self.N_mp_after_async_regen) @@ -232,7 +232,7 @@ def check_for_regeneration(self): if (self.N_mp > self.N_mp_regen or (self.N_mp < self.N_mp_regen_low and self.nel_mp_ref > self.nel_mp_ref_0)): chrg = np.sum(self.nel_mp) erg = np.sum(0.5 / np.abs(self.charge / self.mass) * self.nel_mp[0:self.N_mp] * (self.vx_mp[0:self.N_mp] * self.vx_mp[0:self.N_mp] + self.vy_mp[0:self.N_mp] * self.vy_mp[0:self.N_mp] + self.vz_mp[0:self.N_mp] * self.vz_mp[0:self.N_mp])) - print 'Cloud %s: Start regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg) + print('Cloud %s: Start regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg)) new_nel_mp_ref = chrg / self.N_mp_after_regen if new_nel_mp_ref < self.nel_mp_ref_0: @@ -253,7 +253,7 @@ def check_for_regeneration(self): x_max = (len(hist_vect) - i_cut + 1) * self.Dx_hist_reg + self.bias_x_hist_reg - print 'Cloud %s: x_max = %e'%(self.name, x_max) + print('Cloud %s: x_max = %e'%(self.name, x_max)) flag_clean = (abs(self.x_mp) > x_max) flag_keep = ~(flag_clean) @@ -303,7 +303,7 @@ def check_for_regeneration(self): bias_vz = np.ceil(float(self.Nvz_reg) / 2) #Attention when trnslating to python - print 'Cloud %s: particles_assigned_to grid'%(self.name) + print('Cloud %s: particles_assigned_to grid'%(self.name)) ## #% MATLAB-like indices @@ -324,7 +324,7 @@ def check_for_regeneration(self): indices_nonzero_cells = np.array(list(set(indexes))) indices_nonzero_cells = np.sort(indices_nonzero_cells) - vect_dens = dict(zip(indices_nonzero_cells, np.zeros(len(indices_nonzero_cells)))) + vect_dens = dict(list(zip(indices_nonzero_cells, np.zeros(len(indices_nonzero_cells))))) #lil_matrix((Nx_reg*Ny_reg*Nvx_reg*Nvy_reg*Nvz_reg,1));#allocate a sparse matrix # @@ -332,7 +332,7 @@ def check_for_regeneration(self): index_curr = indexes[i_mp] vect_dens[index_curr] = vect_dens[index_curr] + self.nel_mp[i_mp] - nonzero_cells = np.array(map(vect_dens.get, indices_nonzero_cells)) + nonzero_cells = np.array(list(map(vect_dens.get, indices_nonzero_cells))) #%% retrieve indices of nonempty cells #% NB use C-like indices @@ -436,7 +436,7 @@ def check_for_regeneration(self): chrg = np.sum(self.nel_mp) erg = np.sum(0.5 / np.abs(self.charge / self.mass) * self.nel_mp[0:self.N_mp] * (self.vx_mp[0:self.N_mp] * self.vx_mp[0:self.N_mp] + self.vy_mp[0:self.N_mp] * self.vy_mp[0:self.N_mp] + self.vz_mp[0:self.N_mp] * self.vz_mp[0:self.N_mp])) - print 'Cloud %s: Done regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg) + print('Cloud %s: Done regeneration. N_mp=%d Nel_tot=%1.2e En_tot=%1.2e'%(self.name, self.N_mp, chrg, erg)) def add_uniform_MP_distrib(self, DNel, E_init, x_max, x_min, y_max, y_min): @@ -569,7 +569,7 @@ def add_from_file(self, filename_MPs): self.nel_mp[self.N_mp:self.N_mp + Nint_new_MP] = np.squeeze(dict_MP_init['nel_mp']) if self.flag_lifetime_hist: - if 't_last_impact' in dict_MP_init.keys(): + if 't_last_impact' in list(dict_MP_init.keys()): self.t_last_impact[self.N_mp:self.N_mp + Nint_new_MP] = np.squeeze( dict_MP_init['t_last_impact']) else: diff --git a/PyEC4PyHT.py b/PyEC4PyHT.py index 19e5ecb3..080d1616 100644 --- a/PyEC4PyHT.py +++ b/PyEC4PyHT.py @@ -57,9 +57,9 @@ import numpy as np from scipy.constants import c, e, m_e -import myloadmat_to_obj as mlm -import init -import buildup_simulation as bsim +from . import myloadmat_to_obj as mlm +from . import init +from . import buildup_simulation as bsim class Empty(object): @@ -105,7 +105,7 @@ def __init__(self, L_ecloud, slicer, Dt_ref, pyecl_input_folder='./', flag_clean beam_monitor=None, verbose=False, save_pyecl_outp_as=None, **kwargs): - print 'PyECLOUD Version 8.2.0' + print('PyECLOUD Version 8.2.0') # These git commands return the hash and the branch of the specified git directory. path_to_git = os.path.dirname(os.path.abspath(__file__)) + '/.git' @@ -125,8 +125,8 @@ def __init__(self, L_ecloud, slicer, Dt_ref, pyecl_input_folder='./', flag_clean print(e) print(git_branch) - print 'PyHEADTAIL module' - print 'Initializing ecloud from folder: ' + pyecl_input_folder + print('PyHEADTAIL module') + print('Initializing ecloud from folder: ' + pyecl_input_folder) self.slicer = slicer self.Dt_ref = Dt_ref self.L_ecloud = L_ecloud @@ -173,13 +173,13 @@ def __init__(self, L_ecloud, slicer, Dt_ref, pyecl_input_folder='./', flag_clean self.y_probes = -1 self.Ex_ele_last_track_at_probes = -1 self.Ey_ele_last_track_at_probes = -1 - if 'probes_position' in kwargs.keys(): + if 'probes_position' in list(kwargs.keys()): self.save_ele_field_probes = True self.probes_position = kwargs['probes_position'] self.N_probes = len(self.probes_position) self.x_probes = [] self.y_probes = [] - for ii_probe in xrange(self.N_probes): + for ii_probe in range(self.N_probes): self.x_probes.append(self.probes_position[ii_probe]['x']) self.y_probes.append(self.probes_position[ii_probe]['y']) @@ -236,7 +236,7 @@ def track(self, beam): if self.track_only_first_time: if self.N_tracks > 0: - print 'Warning: Track skipped because track_only_first_time is True.' + print('Warning: Track skipped because track_only_first_time is True.') return if self.verbose: @@ -252,9 +252,9 @@ def track(self, beam): slices = beam.get_slices(self.slicer) - for i in xrange(slices.n_slices - 1, -1, -1): + for i in range(slices.n_slices - 1, -1, -1): if self.verbose: - print('Slice %d/%d'%(i, slices.n_slices)) + print(('Slice %d/%d'%(i, slices.n_slices))) # select particles in the slice ix = slices.particle_indices_of_slice(i) @@ -272,18 +272,18 @@ def track(self, beam): if self.verbose: stop_time = time.mktime(time.localtime()) - print 'Done track %d in %.1f s'%(self.N_tracks, stop_time - start_time) + print('Done track %d in %.1f s'%(self.N_tracks, stop_time - start_time)) self.N_tracks += 1 def replace_with_recorded_field_map(self, delete_ecloud_data=True): if self.track_only_first_time: - print 'Warning: replace_with_recorded_field_map resets track_only_first_time = False' + print('Warning: replace_with_recorded_field_map resets track_only_first_time = False') self.track_only_first_time = False if not hasattr(self, 'efieldmap'): - from Transverse_Efield_map_for_frozen_cloud import Transverse_Efield_map + from .Transverse_Efield_map_for_frozen_cloud import Transverse_Efield_map self.efieldmap = Transverse_Efield_map(xg=self.spacech_ele.xg, yg=self.spacech_ele.yg, Ex=self.Ex_ele_last_track, Ey=self.Ey_ele_last_track, L_interaction=self.L_ecloud, slicer=self.slicer, @@ -301,7 +301,7 @@ def replace_with_recorded_field_map(self, delete_ecloud_data=True): self.cloudsim = None else: - print 'Warning: efieldmap already exists. I do nothing.' + print('Warning: efieldmap already exists. I do nothing.') def track_once_and_replace_with_recorded_field_map(self, bunch, delete_ecloud_data=True): self.save_ele_field = True @@ -325,7 +325,7 @@ def _track_single_slice(self, slic, ix, dz, force_pyecl_newpass=False): # Check if the slice interacts with the beam if hasattr(slic, 'slice_info'): - if 'interact_with_EC' in slic.slice_info.keys(): + if 'interact_with_EC' in list(slic.slice_info.keys()): interact_with_EC = slic.slice_info['interact_with_EC'] else: interact_with_EC = True @@ -351,7 +351,7 @@ def _track_single_slice(self, slic, ix, dz, force_pyecl_newpass=False): # Acquire bunch passage information if hasattr(slic, 'slice_info'): - if 'info_parent_bunch' in slic.slice_info.keys(): + if 'info_parent_bunch' in list(slic.slice_info.keys()): # check if first slice of first bunch if slic.slice_info['info_parent_bunch']['i_bunch'] == 0 and slic.slice_info['i_slice'] == 0: diff --git a/Transverse_Efield_map_for_frozen_cloud.py b/Transverse_Efield_map_for_frozen_cloud.py index 1ff16f05..f71565ca 100644 --- a/Transverse_Efield_map_for_frozen_cloud.py +++ b/Transverse_Efield_map_for_frozen_cloud.py @@ -43,7 +43,7 @@ def track(self, beam): slices = beam.get_slices(self.slicer) sid = 0 - for _ in xrange(slices.n_slices): + for _ in range(slices.n_slices): sid -= 1 diff --git a/beam_and_timing.py b/beam_and_timing.py index 46a39a5b..ba182870 100644 --- a/beam_and_timing.py +++ b/beam_and_timing.py @@ -55,7 +55,7 @@ import scipy.io as sio import scipy.special as sspe from numpy import array -import int_field_for as iff +from . import int_field_for as iff def bunch_train4(t, b_spac, t_offs, ppb_vect, sigmaz_vect): @@ -67,7 +67,7 @@ def bunch_train4(t, b_spac, t_offs, ppb_vect, sigmaz_vect): for ii in range(0, N_bucket): if np.mod(ii, N_bucket / 20) == 0: - print ('Beam profile generation %.0f'%(float(ii) / float(N_bucket) * 100) + """%""") + print(('Beam profile generation %.0f'%(float(ii) / float(N_bucket) * 100) + """%""")) ppb = ppb_vect[ii] sigmaz = sigmaz_vect[ii] @@ -98,13 +98,13 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f flag_unif_Dt = True if flag_bunched_beam: - print 'Start beam profile generation.' + print('Start beam profile generation.') if type(filling_pattern_file) is str: if '.mat' in filling_pattern_file: dict_fillp = sio.loadmat(filling_pattern_file) ppb_vect = np.squeeze(dict_fillp['ppb_vect']) - if 'sigmaz_vect' in dict_fillp.keys(): + if 'sigmaz_vect' in list(dict_fillp.keys()): sigmaz_vect = np.squeeze(dict_fillp['sigmaz_vect']) else: raise ValueError('Input of filling scheme via txt files is discontinued!') @@ -133,10 +133,10 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f raise ValueError('Bunch length is not defined!!!') lam_t_array = bunch_train4(t, b_spac, t_offs, ppb_vect, sigmaz_vect) - print 'Done beam profile generation.' + print('Done beam profile generation.') else: - print 'Loading beam profile from file:' - print beam_long_prof_file + print('Loading beam profile from file:') + print(beam_long_prof_file) dict_lam = sio.loadmat(beam_long_prof_file) t = np.squeeze(dict_lam['t'].real) @@ -147,11 +147,11 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f if (np.max(np.abs(Dt_vect)) - np.mean(np.abs(Dt_vect))) > 1e-4 * np.mean(np.abs(Dt_vect)): flag_unif_Dt = False else: - print 'Beam profile loaded from file.' - print 'Uniform time step detected.' - print 'The time step Dt provided in simulation_parameters.input will be ignored.' + print('Beam profile loaded from file.') + print('Uniform time step detected.') + print('The time step Dt provided in simulation_parameters.input will be ignored.') Dt = t[1] - t[0] - print 'Time step set to Dt = %.3e s.'%Dt + print('Time step set to Dt = %.3e s.'%Dt) if flag_secodary_beam: if len(t) != len(t_primary_beam): @@ -167,16 +167,16 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f flag_PyPIC_state_mode = False if beam_field_file == -1 or beam_field_file == 'computeFD': - print 'No beam field file provided -> Calculate field using Poisson solver' + print('No beam field file provided -> Calculate field using Poisson solver') if Dh_beam_field is None: raise ValueError('Grid size Dh_beam_field MUST be provided for beam field computation!') - import space_charge_class as scc + from . import space_charge_class as scc from numpy import exp, pi scb = scc.space_charge(chamb, Dh_beam_field, Dt_sc=1.) - print 'Computing beam charge density' + print('Computing beam charge density') #rho=1./(2.*pi*sigmax*sigmay)*exp(-(scb.xn-x_beam_pos)**2/(2.*sigmax**2)-(scb.yn-y_beam_pos)**2/(2.*sigmay**2)) rho = 1. / (4. * Dh_beam_field**2) * (sspe.erf((scb.xn - x_beam_pos) / (np.sqrt(2) * sigmax) + Dh_beam_field / (2 * np.sqrt(2) * sigmax))\ @@ -191,11 +191,11 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f xx_beam = scb.xg yy_beam = scb.yg #self.scb = scb #######DEBUG!! - print 'Done beam field computation.' + print('Done beam field computation.') elif beam_field_file == 'computeBE': - print 'No beam field file provided -> Calculate field using Bassetti Erskine formula' + print('No beam field file provided -> Calculate field using Bassetti Erskine formula') if chamb.chamb_type != 'ellip': raise ValueError('You can only use Bassetti Erskine formula with an elliptic chamber!') @@ -204,7 +204,7 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f if x_beam_pos != 0. or y_beam_pos != 0.: raise ValueError('x_beam_pos, y_beam_pos and MUST be 0 for Bassetti Erskine formula!') - print "sigmax=%.3e, sigmay=%.3e, Nx=%d, Ny=%d, nimag=%d"%(sigmax, sigmay, Nx, Ny, nimag) + print("sigmax=%.3e, sigmay=%.3e, Nx=%d, Ny=%d, nimag=%d"%(sigmax, sigmay, Nx, Ny, nimag)) if progress_mapgen_file is not None: fprog = open(progress_mapgen_file, 'w') @@ -212,7 +212,7 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f fprog.write("sigmax=%.3e, sigmay=%.3e, Nx=%d, Ny=%d, nimag=%d\n"%(sigmax, sigmay, Nx, Ny, nimag)) fprog.close() - import BassErsk as BE + from . import BassErsk as BE a = chamb.x_aper b = chamb.y_aper @@ -223,11 +223,11 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f Ex = np.zeros((len(xx), len(yy)), dtype=complex) Ey = np.zeros((len(xx), len(yy)), dtype=complex) - print 'Start beam field map generation.' + print('Start beam field map generation.') for ii in range(len(xx)): if np.mod(ii, Nx / 20) == 0: - print ('Beam field map generation %.0f'%(float(ii) / float(Nx) * 100) + """%""") + print(('Beam field map generation %.0f'%(float(ii) / float(Nx) * 100) + """%""")) if progress_mapgen_file is not None: fprog = open(progress_mapgen_file, 'a') @@ -250,7 +250,7 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f fprog = open(progress_mapgen_file, 'a') fprog.write('Done.\n') fprog.close() - print 'Done beam field map generation.' + print('Done beam field map generation.') elif beam_field_file == 'compute_FDSW_multigrid': if Dh_beam_field is None: @@ -295,8 +295,8 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f del(PyPICobj) else: - print 'Loading beam field map from file:' - print beam_field_file + print('Loading beam field map from file:') + print(beam_field_file) dict_beam = sio.loadmat(beam_field_file) Ex_beam = np.squeeze(dict_beam['Ex'].real) @@ -328,8 +328,8 @@ def __init__(self, flag_bunched_beam, fact_beam, coast_dens, beam_charge, beam_f self.yy_beam = yy_beam if not(flag_unif_Dt): - print 'Cloud simulation in non-uniform Dt mode.' - print 'Dt provided in input will be used only as reference for savings and substeps.' + print('Cloud simulation in non-uniform Dt mode.') + print('Dt provided in input will be used only as reference for savings and substeps.') self.flag_unif_Dt = flag_unif_Dt self.Nt = Nt diff --git a/buildup_simulation.py b/buildup_simulation.py index f7ef87c6..b8e132dd 100644 --- a/buildup_simulation.py +++ b/buildup_simulation.py @@ -53,8 +53,8 @@ #-End-preamble--------------------------------------------------------- -import init as init -import cPickle +from . import init as init +import pickle import numpy as np import os @@ -64,7 +64,7 @@ class BuildupSimulation(object): def __init__(self, pyecl_input_folder='./', skip_beam=False, skip_spacech_ele=False, skip_pyeclsaver=False, ignore_kwargs=[], spacech_ele=None, **kwargs): - print 'PyECLOUD Version 8.2.0' + print('PyECLOUD Version 8.2.0') beamtim, spacech_ele, t_sc_ON, flag_presence_sec_beams, sec_beams_list, \ config_dict, flag_multiple_clouds, cloud_list, checkpoint_folder, \ cross_ion = init.read_input_files_and_init_components(\ @@ -110,14 +110,14 @@ def run(self, t_end_sim=None): flag_presence_sec_beams = self.flag_presence_sec_beams sec_beams_list = self.sec_beams_list - print 'Start timestep iter' + print('Start timestep iter') ## simulation while not beamtim.end_simulation(): if t_end_sim is not None and beamtim.tt_curr is not None: if beamtim.tt_curr >= t_end_sim: - print 'Reached user defined t_end_sim --> Ending simulation' + print('Reached user defined t_end_sim --> Ending simulation') break beamtim.next_time_step() @@ -129,7 +129,7 @@ def run(self, t_end_sim=None): self.sim_time_step() if beamtim.flag_new_bunch_pass: - print '**** Done pass_numb = %d/%d\n'%(beamtim.pass_numb, beamtim.N_pass_tot) + print('**** Done pass_numb = %d/%d\n'%(beamtim.pass_numb, beamtim.N_pass_tot)) def sim_time_step(self, beamtim_obj=None, Dt_substep_custom=None, N_sub_steps_custom=None, kick_mode_for_beam_field=False, @@ -295,7 +295,7 @@ def sim_time_step(self, beamtim_obj=None, Dt_substep_custom=None, N_sub_steps_cu def load_state(self, filename_simulation_state, force_disable_save_simulation_state=True, filen_main_outp='Pyecltest_restarted', load_from_folder='./'): # , reset_pyeclsaver = True): with open(load_from_folder + filename_simulation_state, 'rb') as fid: - dict_state = cPickle.load(fid) + dict_state = pickle.load(fid) self.beamtim = dict_state['beamtim'] self.spacech_ele = dict_state['spacech_ele'] @@ -321,20 +321,20 @@ def load_state(self, filename_simulation_state, force_disable_save_simulation_st filen_outp_root = cloud.pyeclsaver.filen_main_outp.split('.mat')[0] cloud.pyeclsaver.filen_main_outp = filen_outp_root + filen_outp_ext + '.mat' - print 'Restoring PyPIC LU object...' + print('Restoring PyPIC LU object...') self.spacech_ele.PyPICobj.build_sparse_solver() if self.spacech_ele.flag_em_tracking: - print 'Restoring PyPIC Ax, Ay and As state objects...' + print('Restoring PyPIC Ax, Ay and As state objects...') self.spacech_ele.state_Ax = self.spacech_ele.PyPICobj.get_state_object() self.spacech_ele.state_Ay = self.spacech_ele.PyPICobj.get_state_object() self.spacech_ele.state_As = self.spacech_ele.PyPICobj.get_state_object() - print 'Done reload.' + print('Done reload.') return dict_state def load_checkpoint(self, filename_simulation_checkpoint, load_from_folder='./'): - print('Reloading from checkpoint: %s...' % (load_from_folder + filename_simulation_checkpoint)) + print(('Reloading from checkpoint: %s...' % (load_from_folder + filename_simulation_checkpoint))) i_checkp = int(filename_simulation_checkpoint.split('.pkl')[0].split('_')[-1]) dict_state = self.load_state(filename_simulation_checkpoint, force_disable_save_simulation_state=False, filen_main_outp=None, load_from_folder=load_from_folder) diff --git a/cross_ionization.py b/cross_ionization.py index 99e3903e..10349b25 100644 --- a/cross_ionization.py +++ b/cross_ionization.py @@ -64,10 +64,10 @@ def __init__(self, pyecl_input_folder, process_name, process_definitions, cloud_ # Warn if target density doesn't correspond to density of gas ionization class? self.name = process_name - print('Init process %s' % self.name) + print(('Init process %s' % self.name)) self.target_dens = process_definitions['target_density'] - print('Target density = %.2e' %(self.target_dens)) + print(('Target density = %.2e' %(self.target_dens))) self.last_reported_target_dens = self.target_dens self.target_area = target_area @@ -75,12 +75,12 @@ def __init__(self, pyecl_input_folder, process_name, process_definitions, cloud_ self.E_eV_init = process_definitions['E_eV_init'] - if 'extract_sigma' in process_definitions.keys(): + if 'extract_sigma' in list(process_definitions.keys()): self.extract_sigma = process_definitions['extract_sigma'] else: self.extract_sigma = True - if 'generate_equally' in process_definitions.keys(): + if 'generate_equally' in list(process_definitions.keys()): self.generate_equally = process_definitions['generate_equally'] else: self.generate_equally = False @@ -88,7 +88,7 @@ def __init__(self, pyecl_input_folder, process_name, process_definitions, cloud_ # Check that ionization product names correspond to existing clouds product_names = process_definitions['products'] for product in product_names: - assert product in cloud_dict.keys(), "Product name %s does not correspond to a defined cloud name."%(product) + assert product in list(cloud_dict.keys()), "Product name %s does not correspond to a defined cloud name."%(product) self.products = product_names # Read cross section file @@ -101,7 +101,7 @@ def __init__(self, pyecl_input_folder, process_name, process_definitions, cloud_ else: cross_section_file_path = cross_section_file - print('Cross-section from file %s' %cross_section_file_path) + print(('Cross-section from file %s' %cross_section_file_path)) cross_section = sio.loadmat(cross_section_file_path) @@ -166,7 +166,7 @@ def generate(self, Dt, cloud_dict, mass_proj, N_proj, nel_mp_proj, self.target_dens = self.N_target / self.target_area if self.target_dens < 0.1 * self.last_reported_target_dens: - print('Cross-ionization process %s target density = %.2e' %(self.name, self.target_dens)) + print(('Cross-ionization process %s target density = %.2e' %(self.name, self.target_dens))) self.last_reported_target_dens = self.target_dens new_mp_info = {} @@ -309,16 +309,16 @@ def __init__(self, pyecl_input_folder, cross_ion_definitions, cloud_list, self.products = [] # Init projectiles and make list of products - for projectile in cross_ion_definitions.keys(): - print('Projectile %s:' %(projectile)) + for projectile in list(cross_ion_definitions.keys()): + print(('Projectile %s:' %(projectile))) # Check that projectile name corresponds to existing cloud - assert projectile in cloud_dict.keys(), "Projectile name %s does not correspond to a defined cloud name."%(projectile) + assert projectile in list(cloud_dict.keys()), "Projectile name %s does not correspond to a defined cloud name."%(projectile) self.projectiles_dict.update({projectile : []}) # Init processes - for process_name in cross_ion_definitions[projectile].keys(): + for process_name in list(cross_ion_definitions[projectile].keys()): process_definitions = cross_ion_definitions[projectile][process_name] process = Ionization_Process(pyecl_input_folder, process_name, process_definitions, cloud_dict, chamber_area) @@ -352,7 +352,7 @@ def generate(self, Dt, cloud_list): new_mps_to_gen = self._init_new_mp_dict(self.products) - for projectile in self.projectiles_dict.keys(): + for projectile in list(self.projectiles_dict.keys()): thiscloud = cloud_dict[projectile] MP_e = thiscloud.MP_e N_mp = MP_e.N_mp @@ -439,7 +439,7 @@ def _extract_sigma(self, Dt, cloud_dict, n_rep, energy_eV): y_mp = np.zeros(n_rep) z_mp = np.zeros(n_rep) - for projectile in self.projectiles_dict.keys(): + for projectile in list(self.projectiles_dict.keys()): thiscloud = cloud_dict[projectile] mass = thiscloud.MP_e.mass @@ -451,7 +451,7 @@ def _extract_sigma(self, Dt, cloud_dict, n_rep, energy_eV): if process.extract_sigma: - print('Extracting cross section for process %s' %process.name ) + print(('Extracting cross section for process %s' %process.name )) save_dict = {} save_dict['energy_eV'] = energy_eV @@ -463,7 +463,7 @@ def _extract_sigma(self, Dt, cloud_dict, n_rep, energy_eV): for i_ene, energy in enumerate(energy_eV): if np.mod(i_ene, N_ene / 10) == 0: - print ('Extracting sigma %.0f'%(float(i_ene) / float(N_ene) * 100) + """%""") + print(('Extracting sigma %.0f'%(float(i_ene) / float(N_ene) * 100) + """%""")) # Test process.get_sigma() sigma_m2 = process.get_sigma(np.array([energy])) @@ -479,7 +479,7 @@ def _extract_sigma(self, Dt, cloud_dict, n_rep, energy_eV): y_proj=y_mp, z_proj=z_mp, v_mp_proj=v_mp, flag_generate=False) - for product in mp_info_from_proc.keys(): + for product in list(mp_info_from_proc.keys()): DN_gen = np.sum(mp_info_from_proc[product]['nel_new_MPs']) if v_ene > 0: sigma_m2_est = DN_gen / process.target_dens / v_ene / Dt / np.sum(nel_mp) @@ -489,7 +489,7 @@ def _extract_sigma(self, Dt, cloud_dict, n_rep, energy_eV): save_dict[this_sigma_name][i_ene] = sigma_m2_est * 1e4 sio.savemat(process.extract_sigma_path, save_dict, oned_as='row') - print('Saved extracted cross section as %s' %process.extract_sigma_path) + print(('Saved extracted cross section as %s' %process.extract_sigma_path)) def _init_new_mp_dict(self, products): @@ -510,7 +510,7 @@ def _init_new_mp_dict(self, products): def _add_to_mp_dict(self, mp_dict, dict_to_add): #sum_dict = {} - for key in mp_dict.keys(): + for key in list(mp_dict.keys()): if key == 'N_new_MPs': mp_dict[key] += dict_to_add['N_new_MPs'] else: diff --git a/dynamics_Boris_f2py.py b/dynamics_Boris_f2py.py index be1dcce3..6e0fdc93 100644 --- a/dynamics_Boris_f2py.py +++ b/dynamics_Boris_f2py.py @@ -52,8 +52,8 @@ from numpy import array, cross, sum, squeeze import scipy.io as sio -import int_field_for as iff -from boris_step import boris_step +from . import int_field_for as iff +from .boris_step import boris_step def crprod(bx, by, bz, cx, cy, cz): @@ -98,7 +98,7 @@ def get_B(self, xn, yn): class B_file(): def __init__(self, B0x, B0y, B0z, fact_Bmap, B_map_file): - print 'Loading B map' + print('Loading B map') dict_Bmap = sio.loadmat(B_map_file) self.Bmap_x = fact_Bmap * squeeze(dict_Bmap['Bx'].real) @@ -129,7 +129,7 @@ class pusher_Boris(): def __init__(self, Dt, B0x, B0y, B0z, \ B_map_file, fact_Bmap, Bz_map_file, N_sub_steps=1): - print "Tracker: Boris" + print("Tracker: Boris") self.N_sub_steps = N_sub_steps self.Dtt = Dt / float(N_sub_steps) @@ -142,13 +142,13 @@ def __init__(self, Dt, B0x, B0y, B0z, \ self.B_ob = B_none(B0x, B0y, B0z) elif B_map_file is 'analytic_qaudrupole_unit_grad': - print "B map analytic quadrupole" + print("B map analytic quadrupole") self.B_ob = B_quad(B0x, B0y, B0z, fact_Bmap) else: self.B_ob = B_file(B0x, B0y, B0z, fact_Bmap, B_map_file) - print "N_subst_init=%d" % self.N_sub_steps + print("N_subst_init=%d" % self.N_sub_steps) #@profile def step(self, MP_e, Ex_n, Ey_n, Ez_n=0., Bx_n=0., By_n=0., Bz_n=0.): diff --git a/dynamics_Boris_multipole.py b/dynamics_Boris_multipole.py index 17503d6c..315b9078 100644 --- a/dynamics_Boris_multipole.py +++ b/dynamics_Boris_multipole.py @@ -52,7 +52,7 @@ import math import numpy as np -from boris_cython import boris_step_multipole +from .boris_cython import boris_step_multipole class pusher_Boris_multipole(): @@ -72,16 +72,16 @@ def __init__(self, Dt, N_sub_steps=1, B_multip=None, B_skew=None): # B_multip are derivatives of B_field # B_field are field strengths at x=1 m, y=0 - factorial = np.array([math.factorial(ii) for ii in xrange(len(B_multip))], dtype=float) + factorial = np.array([math.factorial(ii) for ii in range(len(B_multip))], dtype=float) self.B_field = np.array(B_multip, dtype=float) / factorial if B_skew is None: self.B_field_skew = np.zeros_like(self.B_field, dtype=float) else: self.B_field_skew = np.array(B_skew, dtype=float) / factorial - print "Tracker: Boris multipole" + print("Tracker: Boris multipole") - print "N_subst_init=%d" % self.N_sub_steps + print("N_subst_init=%d" % self.N_sub_steps) #@profile def step(self, MP_e, Ex_n, Ey_n, Ez_n=0., Bx_n=np.asarray([0.]), By_n=np.asarray([0.]), Bz_n=np.asarray([0.])): diff --git a/dynamics_dipole.py b/dynamics_dipole.py index c1007701..3722d91f 100644 --- a/dynamics_dipole.py +++ b/dynamics_dipole.py @@ -50,7 +50,7 @@ # #-End-preamble--------------------------------------------------------- -import sincc_cosincc_cubsincc as cs +from . import sincc_cosincc_cubsincc as cs me = 9.10938291e-31 @@ -61,7 +61,7 @@ class pusher_dipole_magnet(): def __init__(self, Dt, B): - print "Tracker: Dipole - strong B" + print("Tracker: Dipole - strong B") omegac = B * qm self.sincc_v = cs.sincc(omegac * Dt) self.cosincc_v = cs.cosincc(omegac * Dt) diff --git a/dynamics_strong_B_generalized.py b/dynamics_strong_B_generalized.py index 733e4d04..482c6eaf 100644 --- a/dynamics_strong_B_generalized.py +++ b/dynamics_strong_B_generalized.py @@ -53,7 +53,7 @@ from numpy import sqrt, sin, cos, squeeze, sum import scipy.io as sio -import int_field_for as iff +from . import int_field_for as iff me = 9.10938291e-31 qe = 1.602176565e-19 @@ -65,7 +65,7 @@ class pusher_strong_B_generalized(): def __init__(self, Dt, B0x, B0y, \ B_map_file, fact_Bmap, B_zero_thrhld): - print "Tracker: Generalized strong B" + print("Tracker: Generalized strong B") self.Dt = Dt self.B0x = B0x @@ -75,14 +75,14 @@ def __init__(self, Dt, B0x, B0y, \ self.flag_B_map = False self.analyt_quad_grad1 = False elif B_map_file is 'analytic_qaudrupole_unit_grad': - print "B map analytic quadrupole" + print("B map analytic quadrupole") self.flag_B_map = False self.analyt_quad_grad1 = True self.fact_Bmap = fact_Bmap else: self.flag_B_map = True self.analyt_quad_grad1 = False - print 'Loading B map' + print('Loading B map') dict_Bmap = sio.loadmat(B_map_file) self.Bmap_x = fact_Bmap * squeeze(dict_Bmap['Bx'].real) diff --git a/electron_emission.py b/electron_emission.py index e10a89c8..d03b9265 100644 --- a/electron_emission.py +++ b/electron_emission.py @@ -50,7 +50,7 @@ # #-End-preamble--------------------------------------------------------- -from __future__ import division + import time import numpy as np import numpy.random as random diff --git a/gas_ionization_class.py b/gas_ionization_class.py index 4871c91a..fe769a7d 100644 --- a/gas_ionization_class.py +++ b/gas_ionization_class.py @@ -61,7 +61,7 @@ class residual_gas_ionization: def __init__(self, unif_frac, P_nTorr, sigma_ion_MBarn, Temp_K, chamb, E_init_ion, flag_lifetime_hist = False): - print 'Start res. gas ioniz. init.' + print('Start res. gas ioniz. init.') self.unif_frac = unif_frac self.P_nTorr = P_nTorr self.sigma_ion_MBarn = sigma_ion_MBarn @@ -76,7 +76,7 @@ def __init__(self, unif_frac, P_nTorr, sigma_ion_MBarn, Temp_K, chamb, E_init_io self.flag_lifetime_hist = flag_lifetime_hist - print 'Done res. gas ioniz. init.' + print('Done res. gas ioniz. init.') #@profile def generate(self, MP_e, lambda_t, Dt, sigmax, sigmay, x_beam_pos=0., y_beam_pos=0.): diff --git a/gen_photoemission_class.py b/gen_photoemission_class.py index 559ade2e..da47a951 100644 --- a/gen_photoemission_class.py +++ b/gen_photoemission_class.py @@ -50,14 +50,14 @@ # #-End-preamble--------------------------------------------------------- -from __future__ import division, print_function + import numpy as np import numpy.random as random import scipy.io as sio from scipy.constants import c -import electron_emission +from . import electron_emission class PyECLOUD_PhotoemissionException(ValueError): diff --git a/generate_python3 b/generate_python3 index 97eca765..142c7d01 100755 --- a/generate_python3 +++ b/generate_python3 @@ -3,4 +3,4 @@ rm -rf ../python3/PyECLOUD cp -r ../PyECLOUD ../python3/PyECLOUD rm ../python3/PyECLOUD/*.so 2to3 --output-dir=../python3/PyECLOUD -W -n ../PyECLOUD -rm -rf ../python3/PyECLOUD/.git +#rm -rf ../python3/PyECLOUD/.git diff --git a/geom_impact_ellip.py b/geom_impact_ellip.py index 0bb2efd5..77f81c24 100644 --- a/geom_impact_ellip.py +++ b/geom_impact_ellip.py @@ -64,7 +64,7 @@ def __init__(self, x_aper, y_aper, flag_verbose_file=True): self.area = pi * self.x_aper * self.y_aper - print("The area of the chamber is %.3e m^2"%self.area) + print(("The area of the chamber is %.3e m^2"%self.area)) self.N_mp_impact = 0 self.N_mp_corrected = 0 @@ -111,7 +111,7 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa x_nan = x_in[mask_nan] y_nan = y_in[mask_nan] fbckt = open('bcktr_errors.txt', 'a') - for ii_bk in xrange(len(y_nan)): + for ii_bk in range(len(y_nan)): fbckt.write('%e\t%e\tnan\n'%(x_nan[ii_bk], y_nan[ii_bk])) fbckt.close() @@ -123,7 +123,7 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa t0[flag_ident] = 0 if sum(abs(t0.imag)) > 0: - print 'imag detected' + print('imag detected') raise ValueError('Backtracking: complex t0!!!!') x_int = t0 * x_out + (1 - t0) * x_in @@ -153,7 +153,7 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa if self.flag_verbose_file: fbckt = open('bcktr_errors.txt', 'a') - for ii_bk in xrange(len(x_int_pat)): + for ii_bk in range(len(x_int_pat)): fbckt.write('%e\t%e\n'%(x_int_pat[ii_bk], y_int_pat[ii_bk])) fbckt.close() @@ -171,7 +171,7 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa flag_impact = (((x_int / a)**2 + (y_int / b)**2) >= 1) if sum(flag_impact) > 0: - print 'err inside' + print('err inside') raise ValueError('Outside after backtracking!!!!') par_cross = arctan2(a * y_int, b * x_int) diff --git a/geom_impact_poly.py b/geom_impact_poly.py index 07628d0b..b7a67e9f 100644 --- a/geom_impact_poly.py +++ b/geom_impact_poly.py @@ -60,7 +60,7 @@ class polyg_cham_geom_object: def __init__(self, filename_chm, flag_non_unif_sey, flag_verbose_file=False, flag_verbose_stdout=False): - print 'Polygonal chamber - numpy implementation' + print('Polygonal chamber - numpy implementation') if type(filename_chm) == str: dict_chm = sio.loadmat(filename_chm) @@ -137,7 +137,7 @@ def is_outside(self, x_mp, y_mp): y_mp_chk = y_mp[flag_outside] N_pts = len(x_mp_chk) flag_inside_chk = array(N_pts * [True]) - for ii in xrange(self.N_edg): + for ii in range(self.N_edg): flag_inside_chk[flag_inside_chk] = ((y_mp_chk[flag_inside_chk] - self.Vy[ii]) * (self.Vx[ii + 1] - self.Vx[ii])\ - (x_mp_chk[flag_inside_chk] - self.Vx[ii]) * (self.Vy[ii + 1] - self.Vy[ii])) > 0 flag_outside[flag_outside] = ~flag_inside_chk @@ -153,7 +153,7 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa self.N_mp_impact = self.N_mp_impact + N_impacts - for ii in xrange(self.N_edg): + for ii in range(self.N_edg): t_curr = (self.Nx[ii] * (self.Vx[ii] - x_in) + self.Ny[ii] * (self.Vy[ii] - y_in)) / \ (self.Nx[ii] * (x_out - x_in) + self.Ny[ii] * (y_out - y_in)) @@ -211,16 +211,16 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa self.N_mp_corrected = self.N_mp_corrected + N_errors if self.flag_verbose_stdout: - print """Reporting backtrack error of kind 1: no impact found""" - print """x_in, y_in, x_out, y_out""" - for i_err in xrange(N_errors): + print("""Reporting backtrack error of kind 1: no impact found""") + print("""x_in, y_in, x_out, y_out""") + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e'%(x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) - print lcurr - print """End reporting backtrack error of kind 1""" + print(lcurr) + print("""End reporting backtrack error of kind 1""") if self.flag_verbose_file: with open('bcktr_errors.txt', 'a') as fbckt: - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e'%(x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) fbckt.write('1,' + lcurr + '\n') @@ -237,16 +237,16 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa N_errors = len(x_in_error) if self.flag_verbose_stdout: - print """Reporting backtrack error of kind 2: outside after backtracking""" - print """x_in, y_in, x_out, y_out""" - for i_err in xrange(N_errors): + print("""Reporting backtrack error of kind 2: outside after backtracking""") + print("""x_in, y_in, x_out, y_out""") + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e'%(x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) - print lcurr - print """End reporting backtrack error of kind 2""" + print(lcurr) + print("""End reporting backtrack error of kind 2""") if self.flag_verbose_file: with open('bcktr_errors.txt', 'a') as fbckt: - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e'%(x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) fbckt.write('2,' + lcurr + '\n') @@ -261,8 +261,8 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa #~ pl.plot(x_int[flag_impact], y_int[flag_impact],'.r') #~ pl.show() if self.flag_verbose_stdout: - print """Reporting backtrack error of kind 3: outside after correction""" - print """x_in, y_in, x_out, y_out""" + print("""Reporting backtrack error of kind 3: outside after correction""") + print("""x_in, y_in, x_out, y_out""") x_in_error = x_in[flag_impact] y_in_error = y_in[flag_impact] x_out_error = x_out[flag_impact] @@ -270,16 +270,16 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa N_errors = len(x_in_error) if self.flag_verbose_stdout: - print """Reporting backtrack error of kind 3: outside after correction""" - print """x_in, y_in, x_out, y_out""" - for i_err in xrange(N_errors): + print("""Reporting backtrack error of kind 3: outside after correction""") + print("""x_in, y_in, x_out, y_out""") + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e'%(x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) - print lcurr - print """End reporting backtrack error of kind 3""" + print(lcurr) + print("""End reporting backtrack error of kind 3""") if self.flag_verbose_file: with open('bcktr_errors.txt', 'a') as fbckt: - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e'%(x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) fbckt.write('3,' + lcurr + '\n') diff --git a/geom_impact_poly_fast_impact.py b/geom_impact_poly_fast_impact.py index 64e7e084..9cd6dbca 100644 --- a/geom_impact_poly_fast_impact.py +++ b/geom_impact_poly_fast_impact.py @@ -51,13 +51,13 @@ #-End-preamble--------------------------------------------------------- -from __future__ import division, print_function + from numpy import sum, arctan2, sin, cos import scipy.io as sio import numpy as np import numpy.random as random -import geom_impact_poly_cython as gipc +from . import geom_impact_poly_cython as gipc class PyECLOUD_ChamberException(ValueError): @@ -89,7 +89,7 @@ def __init__(self, filename_chm, flag_non_unif_sey, flag_verbose_file=False, fla self.R0_segments = np.squeeze(dict_chm['R0_segments']) self.Emax_segments = np.squeeze(dict_chm['Emax_segments']) - if 'flag_charging' in dict_chm.keys(): + if 'flag_charging' in list(dict_chm.keys()): self.flag_charging = np.squeeze(dict_chm['flag_charging']) self.Q_max_segments = np.squeeze(dict_chm['Q_max_segments']) self.EQ_segments = np.squeeze(dict_chm['EQ_segments']) @@ -208,14 +208,14 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa if self.flag_verbose_stdout: print('Reporting backtrack error of kind 1: no impact found') print('x_in, y_in, x_out, y_out') - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e' % (x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) print(lcurr) print('End reporting backtrack error of kind 1') if self.flag_verbose_file: with open('bcktr_errors.txt', 'a') as fbckt: - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e' % (x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) fbckt.write('1,' + lcurr + '\n') @@ -234,14 +234,14 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa if self.flag_verbose_stdout: print('Reporting backtrack error of kind 2: outside after backtracking') print('x_in, y_in, x_out, y_out') - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e' % (x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) print(lcurr) print('End reporting backtrack error of kind 2') if self.flag_verbose_file: with open('bcktr_errors.txt', 'a') as fbckt: - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e' % (x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) fbckt.write('2,' + lcurr + '\n') @@ -267,14 +267,14 @@ def impact_point_and_normal(self, x_in, y_in, z_in, x_out, y_out, z_out, resc_fa if self.flag_verbose_stdout: print('Reporting backtrack error of kind 3: outside after correction') print('x_in, y_in, x_out, y_out') - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e' % (x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) print(lcurr) print('End reporting backtrack error of kind 3') if self.flag_verbose_file: with open('bcktr_errors.txt', 'a') as fbckt: - for i_err in xrange(N_errors): + for i_err in range(N_errors): lcurr = '%.10e,%.10e,%.10e,%.10e' % (x_in_error[i_err], y_in_error[i_err], x_out_error[i_err], y_out_error[i_err]) fbckt.write('3,' + lcurr + '\n') @@ -295,7 +295,7 @@ def is_convex(self): got_negative = False got_positive = False num_points = self.N_edg - for A in xrange(num_points): + for A in range(num_points): B = np.mod((A + 1), num_points) C = np.mod((B + 1), num_points) diff --git a/geom_impact_rect_fast_impact.py b/geom_impact_rect_fast_impact.py index 7c82f997..e8efdeac 100644 --- a/geom_impact_rect_fast_impact.py +++ b/geom_impact_rect_fast_impact.py @@ -50,7 +50,7 @@ # #-End-preamble--------------------------------------------------------- -import geom_impact_poly_fast_impact as gipfi +from . import geom_impact_poly_fast_impact as gipfi import numpy as np na = np.array diff --git a/h000_find_and_modify_preamble.py b/h000_find_and_modify_preamble.py index 24e562a4..69a4bcb4 100644 --- a/h000_find_and_modify_preamble.py +++ b/h000_find_and_modify_preamble.py @@ -80,7 +80,7 @@ f.write(content) if end in content: - print 'End to be changed:' + print('End to be changed:') print(path) content = content.replace(end, newend) @@ -88,7 +88,7 @@ f.write(content) if '#--------------' in content: - print 'Test' + print('Test') print(path) diff --git a/impact_management_class.py b/impact_management_class.py index e348720b..ace7a18a 100644 --- a/impact_management_class.py +++ b/impact_management_class.py @@ -51,8 +51,8 @@ #-End-preamble--------------------------------------------------------- import numpy as np -import hist_for as histf -import seg_impact as segi +from . import hist_for as histf +from . import seg_impact as segi from scipy.constants import e as qe @@ -65,7 +65,7 @@ def __init__( flag_seg=False, flag_En_hist_seg=False, cos_angle_width=0.05, flag_cos_angle_hist=True): - print 'Start impact man. init.' + print('Start impact man. init.') if flag_seg and not(hasattr(chamb, 'N_vert')): raise ValueError( @@ -96,9 +96,9 @@ def __init__( self.cos_angle_width = cos_angle_width N_angles = int(1. / cos_angle_width) + 1 self.cos_angle_hist = np.zeros(N_angles, float) - print 'Saving cosine of angle of incident electrons.' + print('Saving cosine of angle of incident electrons.') else: - print 'Not saving cosine of angle of incident electrons.' + print('Not saving cosine of angle of incident electrons.') self.xg_hist = xg_hist self.Nxg_hist = Nxg_hist @@ -132,9 +132,9 @@ def __init__( self.energ_eV_impact_seg = np.zeros(chamb.N_vert, float) if flag_En_hist_seg: self.seg_En_hist_lines = [ - np.zeros(Nbin_En_hist, float) for _ in xrange(chamb.N_vert)] + np.zeros(Nbin_En_hist, float) for _ in range(chamb.N_vert)] - print 'Done impact man. init.' + print('Done impact man. init.') def reset_impact_hist_tot(self): self.nel_impact_hist_tot *= 0. @@ -149,7 +149,7 @@ def reset_En_hist_line(self): self.En_hist_line *= 0. def reset_seg_En_hist_lines(self): - for ii in xrange(self.chamb.N_vert): + for ii in range(self.chamb.N_vert): self.seg_En_hist_lines[ii] *= 0. def reset_hist_impact_seg(self): @@ -278,7 +278,7 @@ def backtrack_and_second_emiss(self, old_pos, MP_e, tt_curr=None): i_found, nel_impact * E_impact_eV, self.energ_eV_impact_seg) if self.flag_En_hist_seg: - for iseg in xrange(self.chamb.N_vert): + for iseg in range(self.chamb.N_vert): mask_this_seg = i_found == iseg if np.sum(mask_this_seg) > 0: En_imp_hist_this_seg = E_impact_eV[mask_this_seg] @@ -361,13 +361,13 @@ def backtrack_and_second_emiss(self, old_pos, MP_e, tt_curr=None): def extract_sey_curves(self, n_rep, E_impact_eV_test, cos_theta_test, charge, mass): deltas = {} - for etype in self.sey_mod.event_types.keys(): + for etype in list(self.sey_mod.event_types.keys()): etype_name = self.sey_mod.event_types[etype] deltas[etype_name] = np.zeros( (len(cos_theta_test), len(E_impact_eV_test))) print('Extracting SEY curves...') for i_ct, ct in enumerate(cos_theta_test): - print('%d/%d' % (i_ct + 1, len(cos_theta_test))) + print(('%d/%d' % (i_ct + 1, len(cos_theta_test)))) for i_ene, Ene in enumerate(E_impact_eV_test): # nel_emit, flag_elast, flag_truesec = sey_mod.SEY_process(nel_impact=np.ones(n_rep), @@ -394,7 +394,7 @@ def extract_sey_curves(self, n_rep, E_impact_eV_test, cos_theta_test, charge, ma nel_mp_th=1, flag_seg=True) - for etype in self.sey_mod.event_types.keys(): + for etype in list(self.sey_mod.event_types.keys()): etype_name = self.sey_mod.event_types[etype] thisdelta = deltas[etype_name] thisdelta[i_ct, i_ene] = np.sum( @@ -412,14 +412,14 @@ def extract_energy_distributions(self, n_rep, E_impact_eV_test, cos_theta_test, Dextract_ene = emit_ene_g_hist[1] - emit_ene_g_hist[0] extract_ene_hist = {} - for etype in self.sey_mod.event_types.keys(): + for etype in list(self.sey_mod.event_types.keys()): etype_name = self.sey_mod.event_types[etype] extract_ene_hist[etype_name] = np.zeros( shape=(len(emit_ene_g_hist), len(cos_theta_test)), dtype=float) print('Extracting energy distributions...') for i_ct, ct in enumerate(cos_theta_test): - print('%d/%d' % (i_ct + 1, len(cos_theta_test))) + print(('%d/%d' % (i_ct + 1, len(cos_theta_test)))) Ene = E_impact_eV_test nel_impact = np.ones(n_rep) # Assuming normal is along x @@ -454,7 +454,7 @@ def extract_energy_distributions(self, n_rep, E_impact_eV_test, cos_theta_test, E_all_MPs_eV = np.concatenate([E_replace_eV, E_new_MPs_eV]) extended_event_type = event_info['extended_event_type'] - for etype in self.sey_mod.event_types.keys(): + for etype in list(self.sey_mod.event_types.keys()): etype_name = self.sey_mod.event_types[etype] extract_type = extract_ene_hist[etype_name] # if there are no events of type etype diff --git a/init.py b/init.py index 28f69302..0637cccc 100644 --- a/init.py +++ b/init.py @@ -50,47 +50,47 @@ # #-End-preamble--------------------------------------------------------- -from __future__ import division, print_function + import os import numpy as np from scipy.constants import c, m_e, e as qe from scipy.constants import m_p -import myloadmat_to_obj as mlm - -import beam_and_timing as beatim -from geom_impact_ellip import ellip_cham_geom_object -import geom_impact_poly_fast_impact as gipfi -import geom_impact_rect_fast_impact as girfi - -from sec_emission_model_ECLOUD import SEY_model_ECLOUD -from sec_emission_model_accurate_low_ene import SEY_model_acc_low_ene -from sec_emission_model_ECLOUD_nunif import SEY_model_ECLOUD_non_unif -from sec_emission_model_ECLOUD_nunif import SEY_model_ECLOUD_non_unif_charging -from sec_emission_model_cos_low_ener import SEY_model_cos_le -from sec_emission_model_flat_low_ener import SEY_model_flat_le -from sec_emission_model_from_file import SEY_model_from_file -from sec_emission_model_furman_pivi import SEY_model_furman_pivi -from sec_emission_model_perfect_absorber import SEY_model_perfect_absorber - -import dynamics_dipole as dyndip -import dynamics_Boris_f2py as dynB -import dynamics_strong_B_generalized as dyngen -import dynamics_Boris_multipole as dynmul - -import MP_system as MPs -import space_charge_class as scc -import space_charge_class_electromagnetic as scc_em -import impact_management_class as imc -import pyecloud_saver as pysav -import gas_ionization_class as gic -import gen_photoemission_class as gpc - -import parse_beam_file as pbf -import parse_cloud_file as pcf -import input_parameters_format_specification as inp_spec -import cloud_manager as cman -import cross_ionization as cion +from . import myloadmat_to_obj as mlm + +from . import beam_and_timing as beatim +from .geom_impact_ellip import ellip_cham_geom_object +from . import geom_impact_poly_fast_impact as gipfi +from . import geom_impact_rect_fast_impact as girfi + +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_accurate_low_ene import SEY_model_acc_low_ene +from .sec_emission_model_ECLOUD_nunif import SEY_model_ECLOUD_non_unif +from .sec_emission_model_ECLOUD_nunif import SEY_model_ECLOUD_non_unif_charging +from .sec_emission_model_cos_low_ener import SEY_model_cos_le +from .sec_emission_model_flat_low_ener import SEY_model_flat_le +from .sec_emission_model_from_file import SEY_model_from_file +from .sec_emission_model_furman_pivi import SEY_model_furman_pivi +from .sec_emission_model_perfect_absorber import SEY_model_perfect_absorber + +from . import dynamics_dipole as dyndip +from . import dynamics_Boris_f2py as dynB +from . import dynamics_strong_B_generalized as dyngen +from . import dynamics_Boris_multipole as dynmul + +from . import MP_system as MPs +from . import space_charge_class as scc +from . import space_charge_class_electromagnetic as scc_em +from . import impact_management_class as imc +from . import pyecloud_saver as pysav +from . import gas_ionization_class as gic +from . import gen_photoemission_class as gpc + +from . import parse_beam_file as pbf +from . import parse_cloud_file as pcf +from . import input_parameters_format_specification as inp_spec +from . import cloud_manager as cman +from . import cross_ionization as cion def read_parameter_files(pyecl_input_folder='./', skip_beam_files=False): simulation_param_file = 'simulation_parameters.input' @@ -132,7 +132,7 @@ def read_input_files_and_init_components(pyecl_input_folder='./', skip_beam=Fals config_dict = read_parameter_files(pyecl_input_folder, skip_beam_files=skip_beam) # Override config values with kwargs - for attr, value in kwargs.items(): + for attr, value in list(kwargs.items()): if attr in ignore_kwargs: continue print('Ecloud init. From kwargs: %s = %r' % (attr, value)) @@ -230,7 +230,7 @@ def read_input_files_and_init_components(pyecl_input_folder='./', skip_beam=Fals sec_beams_list = [] if flag_presence_sec_beams: N_sec_beams = len(sec_b_par_list) - for ii in xrange(N_sec_beams): + for ii in range(N_sec_beams): print('Initialize secondary beam %d/%d' % (ii + 1, N_sec_beams)) sb_par = sec_b_par_list[ii] diff --git a/input_parameters_format_specification.py b/input_parameters_format_specification.py index 306f5bd1..d59bf2a9 100644 --- a/input_parameters_format_specification.py +++ b/input_parameters_format_specification.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time @@ -75,7 +75,7 @@ def update_config_dict(config_dict, module, module_name, verbose=False, default_ if verbose: print('%s: %s = %s' % (module_name, parameter, value)) - for parameter, default_value in optional_parameters.items(): # iterates on keys and values of the dictionary + for parameter, default_value in list(optional_parameters.items()): # iterates on keys and values of the dictionary if hasattr(module, parameter): # the parameter is specified in the input file value = getattr(module, parameter) diff --git a/main.py b/main.py index 9848433b..47b39582 100644 --- a/main.py +++ b/main.py @@ -53,11 +53,11 @@ #for compatibility with old PyECLOUD versions try: - from buildup_simulation import BuildupSimulation - print 'Imported from local folder' + from .buildup_simulation import BuildupSimulation + print('Imported from local folder') except ImportError: from PyECLOUD.buildup_simulation import BuildupSimulation - print 'Imported from PyECLOUD folder' + print('Imported from PyECLOUD folder') sim = BuildupSimulation() diff --git a/myfilemanager.py b/myfilemanager.py index bc12f6aa..1f4caee5 100644 --- a/myfilemanager.py +++ b/myfilemanager.py @@ -3,7 +3,7 @@ class obj_from_dict: def __init__(self, dictto): - for kk in dictto.keys(): + for kk in list(dictto.keys()): setattr(self, kk, dictto[kk]) @@ -18,7 +18,7 @@ def myloadmat(filename, squeeze = True): import scipy.io as sio dict_var=sio.loadmat(filename) if squeeze: - for kk in dict_var.keys(): + for kk in list(dict_var.keys()): try: dict_var[kk]=np.squeeze(dict_var[kk]) except: @@ -32,7 +32,7 @@ def dict_of_arrays_and_scalar_from_h5(filename): import h5py with h5py.File(filename, 'r') as fid: f_dict = {} - for kk in fid.keys(): + for kk in list(fid.keys()): f_dict[kk] = np.array(fid[kk]).copy() if f_dict[kk].shape == (): f_dict[kk] = f_dict[kk].tolist() @@ -47,7 +47,7 @@ def monitorh5_to_dict(filename, key= 'Bunch'): with h5py.File(filename, 'r') as monitor_ev: monitor = monitor_ev[key] monitor_dict = {} - for kk in monitor.keys(): + for kk in list(monitor.keys()): monitor_dict[kk] = np.array(monitor[kk]).copy() return monitor_dict @@ -58,15 +58,15 @@ def monitorh5_to_obj(filename, key= 'Bunch'): 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)): - print('Loading '+filename_list[i_file]) + for i_file in range(1, len(filename_list)): + print(('Loading '+filename_list[i_file])) try: monitor_dict_curr = monitorh5_to_dict(filename_list[i_file], key=key) if flag_transpose: - for kk in monitor_dict.keys(): + for kk in list(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(): + for kk in list(monitor_dict.keys()): monitor_dict[kk] = np.array(list(monitor_dict[kk])+list(monitor_dict_curr[kk])) except IOError as err: print('Got:') @@ -83,7 +83,7 @@ def monitorh5list_to_obj(filename_list, key= 'Bunch', flag_transpose=False, perm 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(): + for kk in list(dict_save.keys()): fid.create_dataset(kk, data=dict_save[kk], compression=compression, compression_opts=compression_opts) diff --git a/myloadmat_to_obj.py b/myloadmat_to_obj.py index b760c2e1..4fff9c85 100644 --- a/myloadmat_to_obj.py +++ b/myloadmat_to_obj.py @@ -1,2 +1,2 @@ -from myfilemanager import myloadmat, myloadmat_to_obj, obj_from_dict, obj_to_dict +from .myfilemanager import myloadmat, myloadmat_to_obj, obj_from_dict, obj_to_dict diff --git a/mystyle.py b/mystyle.py index ba2064b4..08f7ef9f 100644 --- a/mystyle.py +++ b/mystyle.py @@ -65,9 +65,9 @@ def comb_legend(sp1, sp2, *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' + RcParams['axes.grid'] = True + RcParams['axes.linewidth'] = 2.0 + RcParams['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) diff --git a/other/fit_furman_pivi_parameters/001_fit_FP_parameters.py b/other/fit_furman_pivi_parameters/001_fit_FP_parameters.py index d4d98470..14a67b74 100644 --- a/other/fit_furman_pivi_parameters/001_fit_FP_parameters.py +++ b/other/fit_furman_pivi_parameters/001_fit_FP_parameters.py @@ -216,9 +216,9 @@ def average_true_sec_energy_PDF(energy, p_1, p2, p3, p4, p5, p6, p7, p8, p9, p10 popt, pcov = curve_fit(average_true_sec_energy_PDF, energy, ene_hilleret, bounds=(1., 30.)) print('Fitted parameters for average true energy PDF:') print('p_n:') -print(popt[0:10]) +print((popt[0:10])) print('eps_n:') -print(1.634185 / (popt[0:10] - 1)) +print((1.634185 / (popt[0:10] - 1))) plt.figure(2, figsize=(20, 15), facecolor='white') E_0s = np.array([10., 20., 35., 50., 75., 100., 300., 500.]) diff --git a/other/furman_pivi_test/FP_fit_LHC_ArcDipReal_450GeV_sey1.70_2.5e11ppb_bl_1.00ns/000_run_simulation.py b/other/furman_pivi_test/FP_fit_LHC_ArcDipReal_450GeV_sey1.70_2.5e11ppb_bl_1.00ns/000_run_simulation.py index 6b515397..01faf2bf 100644 --- a/other/furman_pivi_test/FP_fit_LHC_ArcDipReal_450GeV_sey1.70_2.5e11ppb_bl_1.00ns/000_run_simulation.py +++ b/other/furman_pivi_test/FP_fit_LHC_ArcDipReal_450GeV_sey1.70_2.5e11ppb_bl_1.00ns/000_run_simulation.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time diff --git a/other/inspect_potential_and_field/001_some_plots.py b/other/inspect_potential_and_field/001_some_plots.py index ae0ff5a7..5834e91e 100644 --- a/other/inspect_potential_and_field/001_some_plots.py +++ b/other/inspect_potential_and_field/001_some_plots.py @@ -56,7 +56,7 @@ for i_frame, z_obs in enumerate(list(z_movie) + [z_single_frame_interactive]): - print('Frame %d/%d'%(i_frame, len(z_movie))) + print(('Frame %d/%d'%(i_frame, len(z_movie)))) if not gen_movie and i_frame < len(z_movie): continue diff --git a/other/inspect_potential_and_field/machines_for_testing.py b/other/inspect_potential_and_field/machines_for_testing.py index efceabb1..b72d5203 100644 --- a/other/inspect_potential_and_field/machines_for_testing.py +++ b/other/inspect_potential_and_field/machines_for_testing.py @@ -38,7 +38,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): raise ValueError('machine_configuration not recognized!') if pp.optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -57,7 +57,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.s = None elif pp.optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -92,7 +92,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/other/make_distribution_movie/000_make_edistrib_movie.py b/other/make_distribution_movie/000_make_edistrib_movie.py index 551cd765..88309c9e 100644 --- a/other/make_distribution_movie/000_make_edistrib_movie.py +++ b/other/make_distribution_movie/000_make_edistrib_movie.py @@ -24,7 +24,7 @@ folder_sim = '../../testing/tests_buildup/LHC_ArcDipReal_450GeV_sey1.70_2.5e11ppb_bl_1.00ns_stress_saver/' main_outp_filename = 'Pyecltest_angle3D.mat' -passlist = range(first_passage, first_passage + num_passage) +passlist = list(range(first_passage, first_passage + num_passage)) x_beam_pos = 0. y_beam_pos = 0. @@ -96,7 +96,7 @@ (nphotog, _, _) = rho_video.shape - for ii in xrange(0, nphotog, N_dec): + for ii in range(0, nphotog, N_dec): fig = pl.figure(1, figsize=(4.5, 6)) # ,figsize=(4.5,6) t_curr = t_video[ii] @@ -104,7 +104,7 @@ lam_b1_curr = np.interp(t_curr, t, lam_b1) cendens_curr = np.interp(t_curr, t, cendens) - print 'Pass %d %d/%d'%(pass_ind, ii, nphotog) + print('Pass %d %d/%d'%(pass_ind, ii, nphotog)) imm = np.squeeze(rho_video[ii, :, :]) imm_ex = np.squeeze(ex_video[ii, :, :]) diff --git a/other/make_electromagnetic_space_charge_forces_movie/000_run_simulation.py b/other/make_electromagnetic_space_charge_forces_movie/000_run_simulation.py index 444b6108..845016e5 100644 --- a/other/make_electromagnetic_space_charge_forces_movie/000_run_simulation.py +++ b/other/make_electromagnetic_space_charge_forces_movie/000_run_simulation.py @@ -82,7 +82,7 @@ def _forces_movie_save(sim): pyeclsaver.Fbfz_video = np.array(pyeclsaver.Fbfz_video) pyeclsaver.t_efield_video_new = np.array(pyeclsaver.t_efield_video_new) filename_sc_forces = pyeclsaver.folder_outp + '/sc_forces/sc_forces_pass%d.mat'%(beamtim.pass_numb - 1) - print('Saving %s'%filename_sc_forces) + print(('Saving %s'%filename_sc_forces)) sio.savemat(filename_sc_forces, {'xg_sc': spacech_ele.xg, 'yg_sc': spacech_ele.yg, 't_efield_video_new': pyeclsaver.t_efield_video_new, 'Fefx_video': pyeclsaver.Fefx_video, 'Fefy_video': pyeclsaver.Fefy_video, 'Fesfx_video': pyeclsaver.Fesfx_video, 'Fesfy_video': pyeclsaver.Fesfy_video, 'Fbfx_video': pyeclsaver.Fbfx_video, diff --git a/other/make_electromagnetic_space_charge_forces_movie/001_make_sc_forces_movie.py b/other/make_electromagnetic_space_charge_forces_movie/001_make_sc_forces_movie.py index e5bc3568..52906be3 100644 --- a/other/make_electromagnetic_space_charge_forces_movie/001_make_sc_forces_movie.py +++ b/other/make_electromagnetic_space_charge_forces_movie/001_make_sc_forces_movie.py @@ -25,7 +25,7 @@ folder_imgs = 'maps/' main_outp_filename = 'Pyecltest_angle3D.mat' -passlist = range(first_passage, first_passage + num_passage) +passlist = list(range(first_passage, first_passage + num_passage)) x_beam_pos = 0. y_beam_pos = 0. @@ -100,7 +100,7 @@ (nphotog, _, _) = sc_Fe_norm_video.shape (nphotog_big, _, _) = rho_video.shape - for ii in xrange(0, nphotog, N_dec): + for ii in range(0, nphotog, N_dec): fig = pl.figure(1, figsize=(9, 9)) # ,figsize=(4.5,6) t_curr = t_video[ii] ii2, = np.where( t_video_old == t_curr) @@ -109,7 +109,7 @@ lam_b1_curr = np.interp(t_curr, t, lam_b1) cendens_curr = np.interp(t_curr, t, cendens) - print 'Pass %d %d/%d'%(pass_ind, ii, nphotog) + print('Pass %d %d/%d'%(pass_ind, ii, nphotog)) imm = np.squeeze(rho_video[ii2, :, :]) imm_Fe_norm = np.squeeze(sc_Fe_norm_video[ii, :, :]) @@ -142,7 +142,7 @@ pl.subplot(2, 2, 2) ax = pl.gca() im = ax.imshow(imm_Fe_norm.T, cmap=None, norm=None, aspect='auto', interpolation=None, - alpha=None, vmax=0.8*max(map(max, imm_Fe_norm)), origin='lower', extent=[xmin * 1e3, xmax * 1e3, ymin * 1e3, ymax * 1e3]) + alpha=None, vmax=0.8*max(list(map(max, imm_Fe_norm))), origin='lower', extent=[xmin * 1e3, xmax * 1e3, ymin * 1e3, ymax * 1e3]) pl.plot(Vx * 1e3, Vy * 1e3, 'y', linewidth=1.5) pl.axis('equal') @@ -157,7 +157,7 @@ pl.subplot(2, 2, 3) ax = pl.gca() im = ax.imshow(imm_Fb_norm.T, cmap=None, norm=None, aspect='auto', interpolation=None, - alpha=None, vmax=0.8*max(map(max, imm_Fb_norm)), origin='lower', extent=[xmin * 1e3, xmax * 1e3, ymin * 1e3, ymax * 1e3]) + alpha=None, vmax=0.8*max(list(map(max, imm_Fb_norm))), origin='lower', extent=[xmin * 1e3, xmax * 1e3, ymin * 1e3, ymax * 1e3]) pl.plot(Vx * 1e3, Vy * 1e3, 'y', linewidth=1.5) pl.axis('equal') @@ -172,7 +172,7 @@ pl.subplot(2, 2, 4) ax = pl.gca() im = ax.imshow(imm_Fes_norm.T, cmap=None, norm=None, aspect='auto', interpolation=None, - alpha=None, vmax=0.8*max(map(max, imm_Fes_norm)), origin='lower', extent=[xmin * 1e3, xmax * 1e3, ymin * 1e3, ymax * 1e3]) + alpha=None, vmax=0.8*max(list(map(max, imm_Fes_norm))), origin='lower', extent=[xmin * 1e3, xmax * 1e3, ymin * 1e3, ymax * 1e3]) pl.plot(Vx * 1e3, Vy * 1e3, 'y', linewidth=1.5) pl.axis('equal') diff --git a/other/photoemission_angular_distribution/001_test_generated_file.py b/other/photoemission_angular_distribution/001_test_generated_file.py index dc67c28b..05ae91cc 100644 --- a/other/photoemission_angular_distribution/001_test_generated_file.py +++ b/other/photoemission_angular_distribution/001_test_generated_file.py @@ -31,8 +31,8 @@ hist_list = [] -for irep in xrange(N_tests): - print 'Test %d/%d'%(irep + 1, N_tests) +for irep in range(N_tests): + print('Test %d/%d'%(irep + 1, N_tests)) # Build MP object MPe = mps.MP_system( N_mp_max=N_mp_test, diff --git a/other/photoemission_angular_distribution/example_simulation/000_run_simulation.py b/other/photoemission_angular_distribution/example_simulation/000_run_simulation.py index c8bd69f3..6cb4c4a6 100644 --- a/other/photoemission_angular_distribution/example_simulation/000_run_simulation.py +++ b/other/photoemission_angular_distribution/example_simulation/000_run_simulation.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time diff --git a/other/prepare_non_unif_tstep_profile/000_prepare_non_unif_tstep.py b/other/prepare_non_unif_tstep_profile/000_prepare_non_unif_tstep.py index c294a54f..e68486d5 100644 --- a/other/prepare_non_unif_tstep_profile/000_prepare_non_unif_tstep.py +++ b/other/prepare_non_unif_tstep_profile/000_prepare_non_unif_tstep.py @@ -65,7 +65,7 @@ for ii in range(0, N_slots): if np.mod(ii, N_slots / 20) == 0: - print ('Beam profile generation %.0f'%(float(ii) / float(N_slots) * 100) + """%""") + print(('Beam profile generation %.0f'%(float(ii) / float(N_slots) * 100) + """%""")) ppb = ppb_vect[ii] sigmaz = sigmaz_vect[ii] diff --git a/other/response_to_beam_distorsion/multibunch/000_test_cloudsim.py b/other/response_to_beam_distorsion/multibunch/000_test_cloudsim.py index 21cc3850..60eda7f2 100644 --- a/other/response_to_beam_distorsion/multibunch/000_test_cloudsim.py +++ b/other/response_to_beam_distorsion/multibunch/000_test_cloudsim.py @@ -77,7 +77,7 @@ # REMEBMBER TO START POPPING FROM THE RIGHT SIDE print('Start cloud sim') -for ii in xrange(len(list_slices) - 1, -1, -1): +for ii in range(len(list_slices) - 1, -1, -1): ecloud.track(list_slices[ii]) #~ for cc in ecloud.cloudsim.cloud_list: #~ cc.pyeclsaver.t_last_save = 0. diff --git a/other/response_to_beam_distorsion/multibunch/machines_for_testing.py b/other/response_to_beam_distorsion/multibunch/machines_for_testing.py index dcb69343..838046ed 100644 --- a/other/response_to_beam_distorsion/multibunch/machines_for_testing.py +++ b/other/response_to_beam_distorsion/multibunch/machines_for_testing.py @@ -44,7 +44,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): raise ValueError('machine_configuration not recognized!') if optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -63,7 +63,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.s = None elif optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -98,7 +98,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/other/response_to_beam_distorsion/single_bunch/LHC_custom.py b/other/response_to_beam_distorsion/single_bunch/LHC_custom.py index b65706b6..c7c49cfd 100644 --- a/other/response_to_beam_distorsion/single_bunch/LHC_custom.py +++ b/other/response_to_beam_distorsion/single_bunch/LHC_custom.py @@ -70,7 +70,7 @@ def __init__(self, n_segments, machine_configuration, **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/other/scriptable_simulation/000_run_simulation.py b/other/scriptable_simulation/000_run_simulation.py index a79d9a96..7a44d3e0 100644 --- a/other/scriptable_simulation/000_run_simulation.py +++ b/other/scriptable_simulation/000_run_simulation.py @@ -38,9 +38,9 @@ def observe_Nel(sim): for ii, t_stop in enumerate(t_stop_list): print('\n\n==============================') - print('Simulation run %d - t_stop = %s s'%(ii, repr(t_stop))) - print(' starting at tt=%s s'%repr(sim.beamtim.tt_curr)) + print(('Simulation run %d - t_stop = %s s'%(ii, repr(t_stop)))) + print((' starting at tt=%s s'%repr(sim.beamtim.tt_curr))) sim.run(t_end_sim = t_stop) - print(' after run a tt=%s'%repr(sim.beamtim.tt_curr)) + print((' after run a tt=%s'%repr(sim.beamtim.tt_curr))) diff --git a/other/sey_files/resample_sey.py b/other/sey_files/resample_sey.py index b454f74b..8ded1a38 100644 --- a/other/sey_files/resample_sey.py +++ b/other/sey_files/resample_sey.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import numpy as np import scipy.io as sio diff --git a/other/slim_output/001_check_outp_size.py b/other/slim_output/001_check_outp_size.py index 9aa3e16f..cd1f9535 100644 --- a/other/slim_output/001_check_outp_size.py +++ b/other/slim_output/001_check_outp_size.py @@ -16,7 +16,7 @@ ind_sorted = np.argsort(fsizes) for ind in ind_sorted: - print('%s : %f kB'%(fields[ind], fsizes[ind]/1e3)) + print(('%s : %f kB'%(fields[ind], fsizes[ind]/1e3))) import matplotlib.pyplot as plt plt.figure(1) diff --git a/parse_beam_file.py b/parse_beam_file.py index ec8294d6..8dca9f87 100644 --- a/parse_beam_file.py +++ b/parse_beam_file.py @@ -9,7 +9,7 @@ class beam_descr_from_fil: def __init__(self, beamfilename, betafx_from_mach_parms_file, Dx_from_mach_parms_file, betafy_from_mach_parms_file, Dy_from_mach_parms_file): - print('Parsing beam file: %s' % beamfilename) + print(('Parsing beam file: %s' % beamfilename)) # Parse beam input file beam_beam = inp_spec.import_module_from_file('beam_beam', beamfilename) diff --git a/parse_cloud_file.py b/parse_cloud_file.py index 7b55a1f9..d5f46b90 100644 --- a/parse_cloud_file.py +++ b/parse_cloud_file.py @@ -20,7 +20,7 @@ def __init__(self, cloudfilename, default_param_obj): inp_spec.copy_to_config_dict(config_dict, 'additional_cloud_parameters', default_param_obj) else: - print('Parsing cloud file: %s' % cloudfilename) + print(('Parsing cloud file: %s' % cloudfilename)) # Parse cloud input file cloud_params = inp_spec.import_module_from_file('additional_cloud_parameters', cloudfilename) diff --git a/proc_video3.py b/proc_video3.py index 142c708d..fb294cfb 100644 --- a/proc_video3.py +++ b/proc_video3.py @@ -79,8 +79,8 @@ #subprocess.check_call(('rm', '*.png')) - for ii in xrange(0, nphotog, N_dec): - print 'Pass %d %d/%d'%(pass_ind, ii, nphotog) + for ii in range(0, nphotog, N_dec): + print('Pass %d %d/%d'%(pass_ind, ii, nphotog)) imm = np.squeeze(rho_video[ii, :, :]) if flag_log: imm = np.log10(np.abs(imm)) diff --git a/pyecloud_saver.py b/pyecloud_saver.py index 918fcb7a..9ed09f1c 100644 --- a/pyecloud_saver.py +++ b/pyecloud_saver.py @@ -50,19 +50,19 @@ # #-End-preamble--------------------------------------------------------- -from __future__ import print_function + import scipy.io as sio import numpy as np import os import subprocess -import hist_for as histf +from . import hist_for as histf import time from scipy.constants import e as qe -import myloadmat_to_obj as mlm +from . import myloadmat_to_obj as mlm import shutil try: # cPickle is faster in python2 - import cPickle as pickle + import pickle as pickle except ImportError: # No cPickle in python3 import pickle @@ -341,7 +341,7 @@ def _pass_by_pass_data_init(self, impact_man, self.nel_hist_emit_seg = [] self.energ_eV_impact_seg = [] if impact_man.flag_En_hist_seg: - self.En_hist_seg = [ [] for _ in xrange(impact_man.chamb.N_vert)] + self.En_hist_seg = [ [] for _ in range(impact_man.chamb.N_vert)] # detailed hist self.flag_hist_det = False @@ -368,7 +368,7 @@ def _pass_by_pass_data_init(self, impact_man, # Custom data self.pbp_custom_data = {} if self.pass_by_pass_custom_observables is not None: - for kk in self.pass_by_pass_custom_observables.keys(): + for kk in list(self.pass_by_pass_custom_observables.keys()): self.pbp_custom_data[kk] = [] @@ -422,7 +422,7 @@ def _pass_by_pass_data_save(self, MP_e, impact_man, beamtim, buildup_sim): self.nel_hist_det.append(self.nel_hist_det_line.copy()) if self.pass_by_pass_custom_observables is not None: - for kk in self.pass_by_pass_custom_observables.keys(): + for kk in list(self.pass_by_pass_custom_observables.keys()): self.pbp_custom_data[kk].append( self.pass_by_pass_custom_observables[kk](buildup_sim)) @@ -471,7 +471,7 @@ def build_outp_dict(self, buildup_sim): # Extracted sey saved_dict['sey_test_E_impact_eV'] = self.sey_test_E_impact_eV, saved_dict['sey_test_cos_theta'] = self.sey_test_cos_theta - for etypn in self.sey_test_deltas.keys(): + for etypn in list(self.sey_test_deltas.keys()): saved_dict['sey_test_del_%s_mat' % etypn] = self.sey_test_deltas[etypn] # Extracted energy distributions @@ -479,7 +479,7 @@ def build_outp_dict(self, buildup_sim): saved_dict['ene_dist_test_cos_theta'] = self.ene_dist_test_cos_theta saved_dict['ene_dist_test_E_impact_eV'] = self.ene_dist_test_E_impact_eV saved_dict['emit_ene_g_hist'] = self.emit_ene_dist_test['emit_ene_g_hist'] - for etypn in self.emit_ene_dist_test.keys(): + for etypn in list(self.emit_ene_dist_test.keys()): if 'hist' not in etypn: saved_dict['emit_ene_test_%s_mat' % etypn] = self.emit_ene_dist_test[etypn] @@ -490,10 +490,10 @@ def build_outp_dict(self, buildup_sim): # custom once if self.save_once_custom_observables is not None: - for kk in self.save_once_custom_observables.keys(): + for kk in list(self.save_once_custom_observables.keys()): saved_dict[kk] = self.save_once_custom_observables[kk](buildup_sim) - for kk in saved_dict.keys(): + for kk in list(saved_dict.keys()): saved_dict[kk] = np.array(saved_dict[kk]) if self.save_only is not None: @@ -660,7 +660,7 @@ def load_from_output(self, last_t=None): dict_restored = {} for var in saved_every_timestep_list: - if var in dict_history.keys(): + if var in list(dict_history.keys()): if dict_history[var].shape == np.array(0).shape: dict_restored[var] = dict_history[var] else: @@ -668,25 +668,25 @@ def load_from_output(self, last_t=None): self.i_last_save = len(dict_restored['Nel_timep']) - 1 for var in saved_every_passage_list: - if var in dict_history.keys(): + if var in list(dict_history.keys()): if dict_history[var].shape == np.array(0).shape: dict_restored[var] = dict_history[var].tolist() else: dict_restored[var] = dict_history[var][: idx_t_hist + 1].tolist() for var in not_time_dependent_list: - if var in dict_history.keys(): + if var in list(dict_history.keys()): if var in should_be_list_list: dict_restored[var] = dict_history[var].tolist() else: dict_restored[var] = dict_history[var] # Treating t_sc_video separately because of different indicies - if 't_sc_video' in dict_history.keys(): + if 't_sc_video' in list(dict_history.keys()): dict_restored['t_sc_video'] = dict_history['t_sc_video'][: idx_t_sc_video + 1].tolist() # Restore this pyecloud_saver object with values from dict_restored - for var in dict_restored.keys(): + for var in list(dict_restored.keys()): setattr(self, var, dict_restored[var]) def _stepbystep_check_for_data_resize(self): @@ -715,7 +715,7 @@ def _stepbystep_check_for_data_resize(self): if self.flag_electric_energy: list_members.append('En_electric_eV_time') - for kk in self.sbs_custom_data.keys(): + for kk in list(self.sbs_custom_data.keys()): vv = self.sbs_custom_data[kk] self.sbs_custom_data[kk] = np.concatenate((vv, 0 * vv)) @@ -793,7 +793,7 @@ def _stepbystep_data_init(self, Dt_ref, dec_fact_out, el_density_probes, r_cente self.x_el_dens_probes = [] self.y_el_dens_probes = [] self.r_el_dens_probes = [] - for ii in xrange(self.N_el_dens_probes): + for ii in range(self.N_el_dens_probes): self.x_el_dens_probes.append(el_density_probes[ii]['x']) self.y_el_dens_probes.append(el_density_probes[ii]['y']) self.r_el_dens_probes.append(el_density_probes[ii]['r_obs']) @@ -804,7 +804,7 @@ def _stepbystep_data_init(self, Dt_ref, dec_fact_out, el_density_probes, r_cente self.sbs_custom_data = {} if step_by_step_custom_observables is not None: - for kk in step_by_step_custom_observables.keys(): + for kk in list(step_by_step_custom_observables.keys()): self.sbs_custom_data[kk] = 0 * self.t def _stepbystep_data_save(self, impact_man, MP_e, beamtim, buildup_sim, cross_ion): @@ -847,7 +847,7 @@ def _stepbystep_data_save(self, impact_man, MP_e, beamtim, buildup_sim, cross_io self.cen_density[self.i_last_save] = np.sum(MP_e.nel_mp[flag_center]) / (np.pi * self.r_center * self.r_center) if self.flag_el_dens_probes: - for ii in xrange(self.N_el_dens_probes): + for ii in range(self.N_el_dens_probes): flag_center = ((MP_e.x_mp - self.x_el_dens_probes[ii])**2 + (MP_e.y_mp - self.y_el_dens_probes[ii])**2) < self.r_el_dens_probes[ii]**2 flag_center[MP_e.N_mp:] = False self.el_dens_at_probes[ii, self.i_last_save] = np.sum(MP_e.nel_mp[flag_center]) / (np.pi * self.r_el_dens_probes[ii]**2) @@ -862,7 +862,7 @@ def _stepbystep_data_save(self, impact_man, MP_e, beamtim, buildup_sim, cross_io self.DN_cross_ion[self.i_last_save]) = cross_ion.save_cross_ion_data(self.cloud_name) if self.step_by_step_custom_observables is not None: - for kk in self.step_by_step_custom_observables.keys(): + for kk in list(self.step_by_step_custom_observables.keys()): self.sbs_custom_data[kk][self.i_last_save] = self.step_by_step_custom_observables[kk](buildup_sim) def _stepbystep_get_dict(self): @@ -893,7 +893,7 @@ def _stepbystep_get_dict(self): if self.flag_el_dens_probes: dict_sbs_data['el_dens_at_probes'] = self.el_dens_at_probes[:, :self.i_last_save] - for kk in self.sbs_custom_data.keys(): + for kk in list(self.sbs_custom_data.keys()): dict_sbs_data[kk] = self.sbs_custom_data[kk][:self.i_last_save + 1] return dict_sbs_data @@ -1193,7 +1193,7 @@ def _energy_cos_and_lifetime_angle_hist_save(self, beamtim, impact_man, MP_e): # Energy histogram per segment if impact_man.flag_seg: if impact_man.flag_En_hist_seg: - for iseg in xrange(impact_man.chamb.N_vert): + for iseg in range(impact_man.chamb.N_vert): self.En_hist_seg[iseg].append(impact_man.seg_En_hist_lines[iseg].copy()) impact_man.reset_seg_En_hist_lines() diff --git a/sec_emission_model_ECLOUD.py b/sec_emission_model_ECLOUD.py index 57e8fc12..7717683e 100644 --- a/sec_emission_model_ECLOUD.py +++ b/sec_emission_model_ECLOUD.py @@ -53,7 +53,7 @@ import numpy as np from numpy import sqrt, exp from numpy.random import rand -import electron_emission as ee +from . import electron_emission as ee def yield_fun2(E, costheta, Emax, del_max, R0, E0, s, flag_costheta_delta_scale=True, flag_costheta_Emax_shift=True): @@ -102,7 +102,7 @@ def __init__( self.secondary_angle_distribution = secondary_angle_distribution if secondary_angle_distribution is not None: - import electron_emission + from . import electron_emission self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution) else: self.angle_dist_func = None @@ -115,7 +115,7 @@ def __init__( self.flag_costheta_delta_scale = flag_costheta_delta_scale self.flag_costheta_Emax_shift = flag_costheta_Emax_shift - print('Secondary emission model: ECLOUD E0=%.4f s=%.4f' % (self.E0, self.s)) + print(('Secondary emission model: ECLOUD E0=%.4f s=%.4f' % (self.E0, self.s))) def SEY_model_evol(self, Dt): pass diff --git a/sec_emission_model_ECLOUD_nunif.py b/sec_emission_model_ECLOUD_nunif.py index 1744f9a5..56409cda 100644 --- a/sec_emission_model_ECLOUD_nunif.py +++ b/sec_emission_model_ECLOUD_nunif.py @@ -53,7 +53,7 @@ from numpy import sqrt, exp, take from numpy.random import rand import numpy as np -from sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD from scipy.constants import e as qe def yield_fun2(E, costheta, Emax, del_max, R0, E0): @@ -94,7 +94,7 @@ def __init__(self, chamb, Emax, del_max, R0, E0=150., self.secondary_angle_distribution = secondary_angle_distribution if secondary_angle_distribution is not None: - import electron_emission + from . import electron_emission self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution) else: self.angle_dist_func = None @@ -109,7 +109,7 @@ def __init__(self, chamb, Emax, del_max, R0, E0=150., self.E0 = E0 - print 'Secondary emission model: ECLOUD non uniform E0=%f'%self.E0 + print('Secondary emission model: ECLOUD non uniform E0=%f'%self.E0) def SEY_process(self, nel_impact, E_impact_eV, costheta_impact, i_impact): @@ -136,7 +136,7 @@ def __init__(self, chamb, Emax, del_max, R0, E0=150., E_th, sigmafit, mufit, switch_no_increase_energy, thresh_low_energy, secondary_angle_distribution, ) - print 'Secondary emission model: ECLOUD non uniform E0=%f, with charging'%self.E0 + print('Secondary emission model: ECLOUD non uniform E0=%f, with charging'%self.E0) self.chamb = chamb self.Q_segments = 0. * self.del_max_segments diff --git a/sec_emission_model_accurate_low_ene.py b/sec_emission_model_accurate_low_ene.py index 6a3da54d..0c05db1a 100644 --- a/sec_emission_model_accurate_low_ene.py +++ b/sec_emission_model_accurate_low_ene.py @@ -52,7 +52,7 @@ from numpy import sqrt, exp from numpy.random import rand -from sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD def yield_fun3(E, costheta, Emax, del_max, R0, E0): @@ -88,7 +88,7 @@ def __init__(self, Emax, del_max, R0, E0=150, self.secondary_angle_distribution = secondary_angle_distribution if secondary_angle_distribution is not None: - import electron_emission + from . import electron_emission self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution) else: self.angle_dist_func = None diff --git a/sec_emission_model_cos_low_ener.py b/sec_emission_model_cos_low_ener.py index 9d9abc2c..6e8d44a2 100644 --- a/sec_emission_model_cos_low_ener.py +++ b/sec_emission_model_cos_low_ener.py @@ -52,7 +52,7 @@ from numpy import sqrt, exp, cos, pi from numpy.random import rand -from sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD def yield_fun2(E, costheta, Emax, del_max, R0, E0): @@ -90,7 +90,7 @@ def __init__(self, Emax, del_max, R0, E0=30., self.secondary_angle_distribution = secondary_angle_distribution if secondary_angle_distribution is not None: - import electron_emission + from . import electron_emission self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution) else: self.angle_dist_func = None @@ -99,7 +99,7 @@ def __init__(self, Emax, del_max, R0, E0=30., self.del_max = del_max self.R0 = R0 self.E0 = E0 - print 'Secondary emission model: Cosine Low Energy E0=%f'%self.E0 + print('Secondary emission model: Cosine Low Energy E0=%f'%self.E0) def SEY_process(self, nel_impact, E_impact_eV, costheta_impact, i_impact): yiel, ref_frac = yield_fun2(E_impact_eV, costheta_impact, self.Emax, self.del_max, self.R0, E0=self.E0) diff --git a/sec_emission_model_flat_low_ener.py b/sec_emission_model_flat_low_ener.py index 976b9fcb..88f73b23 100644 --- a/sec_emission_model_flat_low_ener.py +++ b/sec_emission_model_flat_low_ener.py @@ -52,7 +52,7 @@ from numpy import sqrt, exp, cos, pi, logical_and from numpy.random import rand -from sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD def yield_fun2(E, costheta, Emax, del_max, R0): @@ -91,7 +91,7 @@ def __init__(self, Emax, del_max, R0, self.secondary_angle_distribution = secondary_angle_distribution if secondary_angle_distribution is not None: - import electron_emission + from . import electron_emission self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution) else: self.angle_dist_func = None @@ -99,7 +99,7 @@ def __init__(self, Emax, del_max, R0, self.Emax = Emax self.del_max = del_max self.R0 = R0 - print 'Secondary emission model: Flat Low Energy ' + print('Secondary emission model: Flat Low Energy ') def SEY_process(self, nel_impact, E_impact_eV, costheta_impact, i_impact): yiel, ref_frac = yield_fun2(E_impact_eV, costheta_impact, self.Emax, self.del_max, self.R0) diff --git a/sec_emission_model_from_file.py b/sec_emission_model_from_file.py index cf1bc391..ead56ef9 100644 --- a/sec_emission_model_from_file.py +++ b/sec_emission_model_from_file.py @@ -51,13 +51,13 @@ #-End-preamble--------------------------------------------------------- -from __future__ import division, print_function + import os import numpy as np import scipy.io as sio from numpy.random import rand -from sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD class SEY_model_from_file(SEY_model_ECLOUD): @@ -80,7 +80,7 @@ def __init__(self, sey_file, flag_costheta_delta_scale, flag_costheta_Emax_shift self.secondary_angle_distribution = secondary_angle_distribution if secondary_angle_distribution is not None: - import electron_emission + from . import electron_emission self.angle_dist_func = electron_emission.get_angle_dist_func(secondary_angle_distribution) else: self.angle_dist_func = None @@ -94,7 +94,7 @@ def __init__(self, sey_file, flag_costheta_delta_scale, flag_costheta_Emax_shift os.path.expanduser(sey_file), os.path.abspath(os.path.dirname(__file__)) + '/sey_files/' + sey_file, ] - existing_files = filter(os.path.isfile, candidate_files) + existing_files = list(filter(os.path.isfile, candidate_files)) if not existing_files: raise ValueError('SEY file %s is not found' % sey_file) sey_file_real = existing_files[0] diff --git a/sec_emission_model_furman_pivi.py b/sec_emission_model_furman_pivi.py index fcd7b021..c09fa1a6 100644 --- a/sec_emission_model_furman_pivi.py +++ b/sec_emission_model_furman_pivi.py @@ -59,7 +59,7 @@ from scipy.special import binom from scipy.special import erf from scipy.special import erfinv -import electron_emission as ee +from . import electron_emission as ee _factorial = np.array([1, 1, @@ -162,9 +162,9 @@ def __init__(self, furman_pivi_surface, self.t4 = furman_pivi_surface['t4'] if self.exclude_rediffused: - print('Secondary emission model: Furman-Pivi excluding rediffused, s=%.4f' % (self.s)) + print(('Secondary emission model: Furman-Pivi excluding rediffused, s=%.4f' % (self.s))) else: - print('Secondary emission model: Furman-Pivi, s=%.4f' % (self.s)) + print(('Secondary emission model: Furman-Pivi, s=%.4f' % (self.s))) def SEY_model_evol(self, Dt): pass diff --git a/sec_emission_model_perfect_absorber.py b/sec_emission_model_perfect_absorber.py index 4ee1ebff..13c89ed8 100644 --- a/sec_emission_model_perfect_absorber.py +++ b/sec_emission_model_perfect_absorber.py @@ -51,13 +51,13 @@ #-End-preamble--------------------------------------------------------- -from __future__ import division, print_function + import os import numpy as np import scipy.io as sio from numpy.random import rand -from sec_emission_model_ECLOUD import SEY_model_ECLOUD +from .sec_emission_model_ECLOUD import SEY_model_ECLOUD class SEY_model_perfect_absorber(object): diff --git a/space_charge_class.py b/space_charge_class.py index 8c375240..02815f97 100644 --- a/space_charge_class.py +++ b/space_charge_class.py @@ -63,7 +63,7 @@ class space_charge: def __init__(self, chamb, Dh, Dt_sc=None, PyPICmode='FiniteDifferences_ShortleyWeller' , sparse_solver='scipy_slu', f_telescope=None, target_grid=None, N_nodes_discard=None, N_min_Dh_main=None, Dh_U_eV=None): - print 'Start space charge init.' + print('Start space charge init.') if PyPICmode == 'FiniteDifferences_ShortleyWeller': import PyPIC.FiniteDifferences_ShortleyWeller_SquareGrid as PIC_FDSW @@ -140,7 +140,7 @@ def __init__(self, chamb, Dh, Dt_sc=None, PyPICmode='FiniteDifferences_ShortleyW self.comm = None - print 'Done space charge init.' + print('Done space charge init.') @property def rho(self): diff --git a/space_charge_class_electromagnetic.py b/space_charge_class_electromagnetic.py index 91f70ff0..2a01e2bd 100644 --- a/space_charge_class_electromagnetic.py +++ b/space_charge_class_electromagnetic.py @@ -51,11 +51,11 @@ #-End-preamble--------------------------------------------------------- import numpy as np -from space_charge_class import space_charge +from .space_charge_class import space_charge from scipy.constants import epsilon_0, mu_0 from scipy.constants import c as c_light -import int_field_for as iff +from . import int_field_for as iff import sys if sys.version_info.major>2: from io import StringIO @@ -64,10 +64,10 @@ import matplotlib.pyplot as plt import matplotlib as mpl -import rhocompute as rhocom +from . import rhocompute as rhocom from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import colors -import int_field_for as iff +from . import int_field_for as iff na = lambda x: np.array([x]) diff --git a/testing/tests_PyEC4PyHT/000_ecloud_instab_sim.py b/testing/tests_PyEC4PyHT/000_ecloud_instab_sim.py index 340ea33f..5e540681 100644 --- a/testing/tests_PyEC4PyHT/000_ecloud_instab_sim.py +++ b/testing/tests_PyEC4PyHT/000_ecloud_instab_sim.py @@ -59,8 +59,8 @@ bunch = machine.generate_6D_Gaussian_bunch(n_macroparticles=300000, intensity=1.5e11, epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=.11) # simulate -for i_turn in xrange(N_turns): - print 'Turn', i_turn +for i_turn in range(N_turns): + print('Turn', i_turn) machine.track(bunch, verbose=True) diff --git a/testing/tests_PyEC4PyHT/001_compare_kick_against_headtail.py b/testing/tests_PyEC4PyHT/001_compare_kick_against_headtail.py index afd8c099..9ee6493e 100644 --- a/testing/tests_PyEC4PyHT/001_compare_kick_against_headtail.py +++ b/testing/tests_PyEC4PyHT/001_compare_kick_against_headtail.py @@ -108,10 +108,10 @@ rms_err_x_list = [] rms_err_y_list = [] -for ii in xrange(N_turns - 1): +for ii in range(N_turns - 1): # track machine.track(bunch) # , verbose = True) - print 'Turn', ii + print('Turn', ii) # id and momenta after track id_after = bunch.id[bunch.id <= n_part_per_turn] @@ -194,7 +194,7 @@ 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): + for ii in range(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') diff --git a/testing/tests_PyEC4PyHT/002_compare_kick_and_betatron_motion.py b/testing/tests_PyEC4PyHT/002_compare_kick_and_betatron_motion.py index cd393e02..0c9b2fd1 100644 --- a/testing/tests_PyEC4PyHT/002_compare_kick_and_betatron_motion.py +++ b/testing/tests_PyEC4PyHT/002_compare_kick_and_betatron_motion.py @@ -94,8 +94,8 @@ rms_err_x_list = [] rms_err_y_list = [] -for ii in xrange(N_turns - 1): - print 'Turn', ii +for ii in range(N_turns - 1): + print('Turn', ii) # track # id and momenta after track diff --git a/testing/tests_PyEC4PyHT/003_particle_tune_shift_with_frozen_cloud.py b/testing/tests_PyEC4PyHT/003_particle_tune_shift_with_frozen_cloud.py index 2f465009..1de62a66 100644 --- a/testing/tests_PyEC4PyHT/003_particle_tune_shift_with_frozen_cloud.py +++ b/testing/tests_PyEC4PyHT/003_particle_tune_shift_with_frozen_cloud.py @@ -100,7 +100,7 @@ xp_i[:, i] = bunch_for_tracking.xp[:] y_i[:, i] = bunch_for_tracking.y[:] yp_i[:, i] = bunch_for_tracking.yp[:] -print '\nDONE' +print('\nDONE') from tune_analysis import tune_analysis qx_i, qy_i, qx_centroid, qy_centroid = tune_analysis(x_i, xp_i, y_i, yp_i) diff --git a/testing/tests_PyEC4PyHT/004_particle_tune_shift_with_real_cloud.py b/testing/tests_PyEC4PyHT/004_particle_tune_shift_with_real_cloud.py index 7d02ed73..8c788b70 100644 --- a/testing/tests_PyEC4PyHT/004_particle_tune_shift_with_real_cloud.py +++ b/testing/tests_PyEC4PyHT/004_particle_tune_shift_with_real_cloud.py @@ -76,14 +76,14 @@ for i in range(n_turns): machine.track(bunch) # , verbose=True) - print 'Turn', i + print('Turn', i) sys.stdout.flush() x_i[:, i] = bunch.x[:n_record] xp_i[:, i] = bunch.xp[:n_record] y_i[:, i] = bunch.y[:n_record] yp_i[:, i] = bunch.yp[:n_record] -print '\nDONE' +print('\nDONE') from tune_analysis import tune_analysis qx_i, qy_i, qx_centroid, qy_centroid = tune_analysis(x_i, xp_i, y_i, yp_i) diff --git a/testing/tests_PyEC4PyHT/005a_particle_tune_shift_comparison_gen_HT_file.py b/testing/tests_PyEC4PyHT/005a_particle_tune_shift_comparison_gen_HT_file.py index ab8d7ca4..930324e6 100644 --- a/testing/tests_PyEC4PyHT/005a_particle_tune_shift_comparison_gen_HT_file.py +++ b/testing/tests_PyEC4PyHT/005a_particle_tune_shift_comparison_gen_HT_file.py @@ -2,10 +2,10 @@ sys.path.append(os.path.expanduser('../../../')) sys.path.append(os.path.expanduser('../../../PyHEADTAIL/')) -print '' -print 'This script generates h5 file with tunes from Headtail output files.' -print 'Skip this if h5 is already available.' -print '' +print('') +print('This script generates h5 file with tunes from Headtail output files.') +print('Skip this if h5 is already available.') +print('') import numpy as np import pylab as pl @@ -28,7 +28,7 @@ n_part_per_turn = 5000 -print 'Loading HEADTAIL data...' +print('Loading HEADTAIL data...') appo = np.loadtxt(filename) parid = np.reshape(appo[:, 0], (-1, n_part_per_turn))[::N_kicks, :] @@ -40,10 +40,10 @@ dp = np.reshape(appo[:, 6], (-1, n_part_per_turn))[::N_kicks, :] n_turns = len(x[:, 0]) -print 'Done!' +print('Done!') # compute tunes from headtail data -print 'Tune analysis for headtail...' +print('Tune analysis for headtail...') from tune_analysis import tune_analysis qx_ht, qy_ht, qx_centroid_ht, qy_centroid_ht = tune_analysis(x[:, :n_record].T, xp[:, :n_record].T, y[:, :n_record].T, yp[:, :n_record].T) @@ -71,6 +71,6 @@ 'n_turns': n_turns} with h5py.File('footprint_HT.h5', 'w') as fid: - for kk in dict_save.keys(): + for kk in list(dict_save.keys()): fid[kk] = dict_save[kk] diff --git a/testing/tests_PyEC4PyHT/005b_particle_tune_shift_against_HT.py b/testing/tests_PyEC4PyHT/005b_particle_tune_shift_against_HT.py index caf17685..506c7e5e 100644 --- a/testing/tests_PyEC4PyHT/005b_particle_tune_shift_against_HT.py +++ b/testing/tests_PyEC4PyHT/005b_particle_tune_shift_against_HT.py @@ -26,7 +26,7 @@ def dict_of_arrays_and_scalar_from_h5(filename): import h5py with h5py.File(filename, 'r') as fid: f_dict = {} - for kk in fid.keys(): + for kk in list(fid.keys()): f_dict[kk] = np.array(fid[kk]).copy() if f_dict[kk].shape == (): f_dict[kk] = f_dict[kk].tolist() @@ -107,14 +107,14 @@ def dict_of_arrays_and_scalar_from_h5(filename): for i in range(n_turns): machine.track(bunch) # , verbose=True) - print 'Turn', i + print('Turn', i) sys.stdout.flush() x_i[:, i] = bunch.x[:n_record] xp_i[:, i] = bunch.xp[:n_record] y_i[:, i] = bunch.y[:n_record] yp_i[:, i] = bunch.yp[:n_record] -print '\nDONE' +print('\nDONE') from tune_analysis import tune_analysis qx_i, qy_i, qx_centroid, qy_centroid = tune_analysis(x_i, xp_i, y_i, yp_i) diff --git a/testing/tests_PyEC4PyHT/005c_particle_tune_shift_against_HT_slice_mode.py b/testing/tests_PyEC4PyHT/005c_particle_tune_shift_against_HT_slice_mode.py index afda728e..6a7c2a59 100644 --- a/testing/tests_PyEC4PyHT/005c_particle_tune_shift_against_HT_slice_mode.py +++ b/testing/tests_PyEC4PyHT/005c_particle_tune_shift_against_HT_slice_mode.py @@ -26,7 +26,7 @@ def dict_of_arrays_and_scalar_from_h5(filename): import h5py with h5py.File(filename, 'r') as fid: f_dict = {} - for kk in fid.keys(): + for kk in list(fid.keys()): f_dict[kk] = np.array(fid[kk]).copy() if f_dict[kk].shape == (): f_dict[kk] = f_dict[kk].tolist() @@ -115,10 +115,10 @@ def dict_of_arrays_and_scalar_from_h5(filename): yp_i = np.empty((n_record, n_turns)) -for ii in xrange(n_turns): +for ii in range(n_turns): slices_list = bunch.extract_slices(slicer) - print 'Turn', ii + print('Turn', ii) for slice_obj in slices_list[::-1]: machine.track(slice_obj) # , verbose = True) diff --git a/testing/tests_PyEC4PyHT/006_test_slice_by_slice_mode.py b/testing/tests_PyEC4PyHT/006_test_slice_by_slice_mode.py index f7d38854..0ee4bc29 100644 --- a/testing/tests_PyEC4PyHT/006_test_slice_by_slice_mode.py +++ b/testing/tests_PyEC4PyHT/006_test_slice_by_slice_mode.py @@ -112,12 +112,12 @@ # pl.show() -for ii in xrange(N_turns - 1): +for ii in range(N_turns - 1): slices_list = bunch.extract_slices(slicer) for slice_obj in slices_list[::-1]: machine.track(slice_obj) # , verbose = True) - print 'Turn', ii + print('Turn', ii) bunch = sum(slices_list) diff --git a/testing/tests_PyEC4PyHT/007_time_slice_by_slice_mode.py b/testing/tests_PyEC4PyHT/007_time_slice_by_slice_mode.py index 81820a25..d86bd481 100644 --- a/testing/tests_PyEC4PyHT/007_time_slice_by_slice_mode.py +++ b/testing/tests_PyEC4PyHT/007_time_slice_by_slice_mode.py @@ -73,12 +73,12 @@ t_start_slice = time.mktime(time.localtime()) -for ii in xrange(N_turns): +for ii in range(N_turns): slices_list = bunch.extract_slices(slicer) for slice_obj in slices_list[::-1]: machine.track(slice_obj) # , verbose = True) - print 'Turn', ii + print('Turn', ii) bunch = sum(slices_list) @@ -87,7 +87,7 @@ for ec in ecloud_list: ec.finalize_and_reinitialize() t_end_slice = time.mktime(time.localtime()) -print 'Sliced %.2e s per turn'%((t_end_slice - t_start_slice) / float(N_turns)) +print('Sliced %.2e s per turn'%((t_end_slice - t_start_slice) / float(N_turns))) # Simulate bunch mode machine_whole_bunch = SPS(n_segments=N_kicks, machine_configuration='Q20-injection', accQ_x=20., accQ_y=20.) @@ -105,11 +105,11 @@ machine_whole_bunch.install_after_each_transverse_segment(ecloud) t_start_bunch = time.mktime(time.localtime()) -for ii in xrange(N_turns): - print 'Turn', ii +for ii in range(N_turns): + print('Turn', ii) machine_whole_bunch.track(bunch) t_end_bunch = time.mktime(time.localtime()) -print '\n\n' -print 'Sliced %.2e s per turn'%((t_end_slice - t_start_slice) / float(N_turns)) -print 'Full bunch %.2e s per turn'%((t_end_bunch - t_start_bunch) / float(N_turns)) +print('\n\n') +print('Sliced %.2e s per turn'%((t_end_slice - t_start_slice) / float(N_turns))) +print('Full bunch %.2e s per turn'%((t_end_bunch - t_start_bunch) / float(N_turns))) diff --git a/testing/tests_PyEC4PyHT/008_test_multigrid_pinch.py b/testing/tests_PyEC4PyHT/008_test_multigrid_pinch.py index 2e571b48..133ce971 100644 --- a/testing/tests_PyEC4PyHT/008_test_multigrid_pinch.py +++ b/testing/tests_PyEC4PyHT/008_test_multigrid_pinch.py @@ -96,21 +96,21 @@ # Singlegrid tracking time import time N_rep_test = 1 -print 'Ecloud track %d times'%N_rep_test +print('Ecloud track %d times'%N_rep_test) t_start_sw = time.mktime(time.localtime()) -for _ in xrange(N_rep_test): +for _ in range(N_rep_test): ecloud_singlegrid.track(bunch) t_stop_sw = time.mktime(time.localtime()) t_sw_single = t_stop_sw - t_start_sw -print 'Singlegrid tracking time ', t_sw_single / N_rep_test +print('Singlegrid tracking time ', t_sw_single / N_rep_test) # Multigrid tracking time -print 'Ecloud track %d times'%N_rep_test +print('Ecloud track %d times'%N_rep_test) t_start_sw = time.mktime(time.localtime()) -for _ in xrange(N_rep_test): +for _ in range(N_rep_test): ecloud_multigrid.track(bunch) t_stop_sw = time.mktime(time.localtime()) t_sw_single = t_stop_sw - t_start_sw -print 'Multigrid tracking time ', t_sw_single / N_rep_test +print('Multigrid tracking time ', t_sw_single / N_rep_test) slices = bunch.get_slices(ecloud_singlegrid.slicer) @@ -134,7 +134,7 @@ sp1.plot(obcham.Vx * 1e3, obcham.Vy * 1e3, 'b') sp1.plot(ecloud_singlegrid.x_probes * 1e3, ecloud_singlegrid.y_probes * 1e3, 'or', markersize=3) sp1.plot(x_beam_offset, y_beam_offset, '*k', markersize=4) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp1.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx * 1e3, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy * 1e3, '.-k') sp1.set_ylabel('y [mm]') sp1.set_xlabel('x [mm]') @@ -208,7 +208,7 @@ sp1 = pl.subplot(2, 3, 1) pl.pcolormesh(x_grid_probes, y_grid_probes, np.log10(np.sqrt(Ex_singlegrid_matrix**2 + Ey_singlegrid_matrix**2).T), vmin=vmin, vmax=vmax) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp1.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-') pl.xlabel('x [m]') pl.ylabel('y [m]') @@ -224,7 +224,7 @@ sp2 = pl.subplot(2, 3, 4, sharex=sp1) # , sharey=sp1) pl.pcolormesh(x_grid_probes, y_grid_probes, np.log10(np.sqrt(Ex_multigrid_matrix**2 + Ey_multigrid_matrix**2).T), vmin=vmin, vmax=vmax) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp2.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-') pl.xlabel('x [m]') pl.ylabel('y [m]') @@ -240,7 +240,7 @@ sp3 = pl.subplot(2, 3, 2) pl.pcolormesh(x_grid_probes, y_grid_probes, Ex_singlegrid_matrix.T) # , vmin=vmin, vmax=vmax) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp1.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-') pl.xlabel('x [m]') pl.ylabel('y [m]') @@ -255,7 +255,7 @@ sp4 = pl.subplot(2, 3, 5, sharex=sp1) # , sharey=sp1) pl.pcolormesh(x_grid_probes, y_grid_probes, Ex_multigrid_matrix.T) # , vmin=vmin, vmax=vmax) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp2.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-') pl.xlabel('x [m]') pl.ylabel('y [m]') @@ -269,7 +269,7 @@ sp5 = pl.subplot(2, 3, 3, sharex=sp1) # , sharey=sp1) pl.pcolormesh(x_grid_probes, y_grid_probes, rho_singlegrid_matrix.T) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp2.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-') pl.xlabel('x [m]') pl.ylabel('y [m]') @@ -283,7 +283,7 @@ sp6 = pl.subplot(2, 3, 6, sharex=sp1) # , sharey=sp1) pl.pcolormesh(x_grid_probes, y_grid_probes, rho_multigrid_matrix.T) -for ii in xrange(pic_multigrid.n_grids): +for ii in range(pic_multigrid.n_grids): sp2.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx, pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-') pl.xlabel('x [m]') pl.ylabel('y [m]') diff --git a/testing/tests_PyEC4PyHT/009_particle_tune_shift_against_HT_multigrid.py b/testing/tests_PyEC4PyHT/009_particle_tune_shift_against_HT_multigrid.py index 5a7ea274..2180c4cf 100644 --- a/testing/tests_PyEC4PyHT/009_particle_tune_shift_against_HT_multigrid.py +++ b/testing/tests_PyEC4PyHT/009_particle_tune_shift_against_HT_multigrid.py @@ -26,7 +26,7 @@ def dict_of_arrays_and_scalar_from_h5(filename): import h5py with h5py.File(filename, 'r') as fid: f_dict = {} - for kk in fid.keys(): + for kk in list(fid.keys()): f_dict[kk] = np.array(fid[kk]).copy() if f_dict[kk].shape == (): f_dict[kk] = f_dict[kk].tolist() @@ -115,14 +115,14 @@ def dict_of_arrays_and_scalar_from_h5(filename): for i in range(n_turns): machine.track(bunch) # , verbose=True) - print 'Turn', i + print('Turn', i) sys.stdout.flush() x_i[:, i] = bunch.x[:n_record] xp_i[:, i] = bunch.xp[:n_record] y_i[:, i] = bunch.y[:n_record] yp_i[:, i] = bunch.yp[:n_record] -print '\nDONE' +print('\nDONE') from tune_analysis import tune_analysis qx_i, qy_i, qx_centroid, qy_centroid = tune_analysis(x_i, xp_i, y_i, yp_i) diff --git a/testing/tests_PyEC4PyHT/010_test_pyecl_output.py b/testing/tests_PyEC4PyHT/010_test_pyecl_output.py index 3c982c10..c2acfc73 100644 --- a/testing/tests_PyEC4PyHT/010_test_pyecl_output.py +++ b/testing/tests_PyEC4PyHT/010_test_pyecl_output.py @@ -68,6 +68,6 @@ Dt=25e-12, # needed for saving ) -print 'Track_bunch' +print('Track_bunch') ecloud_multigrid.track(bunch) -print 'Done.' +print('Done.') diff --git a/testing/tests_PyEC4PyHT/machines_for_testing.py b/testing/tests_PyEC4PyHT/machines_for_testing.py index 9e43fa43..641ec680 100644 --- a/testing/tests_PyEC4PyHT/machines_for_testing.py +++ b/testing/tests_PyEC4PyHT/machines_for_testing.py @@ -48,7 +48,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): raise ValueError('machine_configuration not recognized!') if optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -62,7 +62,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.s = None elif optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -97,7 +97,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) @@ -149,7 +149,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): raise ValueError('machine_configuration not recognized!') if pp.optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -163,7 +163,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.s = None elif pp.optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -198,7 +198,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) @@ -255,7 +255,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): raise ValueError('machine_configuration not recognized!') if pp.optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -274,7 +274,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.s = None elif pp.optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -309,7 +309,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/testing/tests_PyEC4PyHT/tune_analysis.py b/testing/tests_PyEC4PyHT/tune_analysis.py index 23f186c4..ed55a9f5 100644 --- a/testing/tests_PyEC4PyHT/tune_analysis.py +++ b/testing/tests_PyEC4PyHT/tune_analysis.py @@ -10,8 +10,8 @@ def tune_analysis(x_i, xp_i, y_i, yp_i): qx_i = np.empty(macroparticlenumber) qy_i = np.empty(macroparticlenumber) - print 'analysing particle spectra ... this may take some time.' - for p_idx in xrange(macroparticlenumber): + print('analysing particle spectra ... this may take some time.') + for p_idx in range(macroparticlenumber): qx_i[p_idx] = NAFFlib.get_tune(x_i[p_idx, :]) qy_i[p_idx] = NAFFlib.get_tune(y_i[p_idx, :]) diff --git a/testing/tests_PyEC4PyHT_fastion/000a_ion_simulation.py b/testing/tests_PyEC4PyHT_fastion/000a_ion_simulation.py index a6165096..69874dd1 100644 --- a/testing/tests_PyEC4PyHT_fastion/000a_ion_simulation.py +++ b/testing/tests_PyEC4PyHT_fastion/000a_ion_simulation.py @@ -12,7 +12,7 @@ import PyECLOUD.myfilemanager as mfm -print 'Start initialization' +print('Start initialization') t_start = time.mktime(time.localtime()) @@ -83,16 +83,16 @@ # make beam n_bunches = 156 -print 'Initializing', n_bunches, 'bunches, of', n_macroparticles, 'macroparticles' +print('Initializing', n_bunches, 'bunches, of', n_macroparticles, 'macroparticles') bunches = [] -for i_bun in xrange(n_bunches): - print 'Bunch', i_bun +for i_bun in range(n_bunches): + print('Bunch', i_bun) bunch = machine.generate_6D_Gaussian_bunch(n_macroparticles=n_macroparticles, intensity=intensity, epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=sigma_z) bunch.z -= machine.circumference / machine.longitudinal_map.harmonics[0] * i_bun - print 'Bunch centroid at', bunch.mean_x(), bunch.mean_y(), bunch.mean_z() + print('Bunch centroid at', bunch.mean_x(), bunch.mean_y(), bunch.mean_z()) bunches.append(bunch) beam = sum(bunches) @@ -102,7 +102,7 @@ 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) -print 'sigma_x = %.2e, sigma_y = %.2e'%(sigma_x, sigma_y) +print('sigma_x = %.2e, sigma_y = %.2e'%(sigma_x, sigma_y)) # define apertures and PIC grid size chamb_type = 'rect' @@ -157,7 +157,7 @@ # print grid size nx, ny = ecloud_sk.spacech_ele.PyPICobj.nx, ecloud_sk.spacech_ele.PyPICobj.ny -print 'nx = %d, ny = %d'%(nx, ny) +print('nx = %d, ny = %d'%(nx, ny)) # install ion clouds in the machine @@ -165,11 +165,11 @@ # run simulation -print 'Start track...' +print('Start track...') t_start_sw = time.mktime(time.localtime()) -print 'Time for initialization ', (t_start_sw - t_start), 's' -for i_turn in xrange(n_turns): - print 'Turn %d'%(i_turn + 1) +print('Time for initialization ', (t_start_sw - t_start), 's') +for i_turn in range(n_turns): + print('Turn %d'%(i_turn + 1)) machine.track(beam) t_stop_sw = time.mktime(time.localtime()) -print 'Done track in ', (t_stop_sw - t_start_sw), 's' +print('Done track in ', (t_stop_sw - t_start_sw), 's') diff --git a/testing/tests_PyEC4PyHT_fastion/001a_ion_simulation_multiturn.py b/testing/tests_PyEC4PyHT_fastion/001a_ion_simulation_multiturn.py index 47c9c1f9..c320ef6d 100644 --- a/testing/tests_PyEC4PyHT_fastion/001a_ion_simulation_multiturn.py +++ b/testing/tests_PyEC4PyHT_fastion/001a_ion_simulation_multiturn.py @@ -7,7 +7,7 @@ sys.path.append("../../../PyHEADTAIL") from PyHEADTAIL.particles.slicing import UniformBinSlicer -print 'Start initialization' +print('Start initialization') t_start = time.mktime(time.localtime()) @@ -73,16 +73,16 @@ # make beam n_bunches = 156 -print 'Initializing', n_bunches, 'bunches, of', n_macroparticles, 'macroparticles' +print('Initializing', n_bunches, 'bunches, of', n_macroparticles, 'macroparticles') bunches = [] -for i_bun in xrange(n_bunches): - print 'Bunch', i_bun +for i_bun in range(n_bunches): + print('Bunch', i_bun) bunch = machine.generate_6D_Gaussian_bunch(n_macroparticles=n_macroparticles, intensity=intensity, epsn_x=epsn_x, epsn_y=epsn_y, sigma_z=sigma_z) bunch.z -= machine.circumference / machine.longitudinal_map.harmonics[0] * i_bun - print 'Bunch centroid at', bunch.mean_x(), bunch.mean_y(), bunch.mean_z() + print('Bunch centroid at', bunch.mean_x(), bunch.mean_y(), bunch.mean_z()) bunches.append(bunch) beam = sum(bunches) @@ -92,7 +92,7 @@ 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) -print 'sigma_x = %.2e, sigma_y = %.2e'%(sigma_x, sigma_y) +print('sigma_x = %.2e, sigma_y = %.2e'%(sigma_x, sigma_y)) # define apertures and PIC grid size chamb_type = 'rect' @@ -146,7 +146,7 @@ #print grid size nx, ny = ecloud_sk.spacech_ele.PyPICobj.nx, ecloud_sk.spacech_ele.PyPICobj.ny -print('nx = %d, ny = %d'%(nx, ny)) +print(('nx = %d, ny = %d'%(nx, ny))) # install ion clouds in the machine @@ -157,10 +157,10 @@ beam_monitor.dump(beam) print('Start track...') t_start_sw = time.mktime(time.localtime()) -print('Time for initialization %.3e s'%(t_start_sw - t_start)) -for i_turn in xrange(n_turns): - print('Turn %d'%(i_turn + 1)) +print(('Time for initialization %.3e s'%(t_start_sw - t_start))) +for i_turn in range(n_turns): + print(('Turn %d'%(i_turn + 1))) machine.track(beam) beam_monitor.dump(beam) t_stop_sw = time.mktime(time.localtime()) -print('Done track in %.3e s'%(t_stop_sw - t_start_sw)) +print(('Done track in %.3e s'%(t_stop_sw - t_start_sw))) diff --git a/testing/tests_PyEC4PyHT_fastion/001b_plot_turn_evolution.py b/testing/tests_PyEC4PyHT_fastion/001b_plot_turn_evolution.py index fefc5979..07db4f29 100644 --- a/testing/tests_PyEC4PyHT_fastion/001b_plot_turn_evolution.py +++ b/testing/tests_PyEC4PyHT_fastion/001b_plot_turn_evolution.py @@ -42,7 +42,7 @@ pl.subplots_adjust(left=0.21, hspace=0.3) -for ii in xrange(N_turns + 1): +for ii in range(N_turns + 1): pl.clf() sp3 = pl.subplot(2, 1, 1) diff --git a/testing/tests_PyEC4PyHT_fastion/CLIC_DR.py b/testing/tests_PyEC4PyHT_fastion/CLIC_DR.py index 8bfc5e6b..807d9aa9 100644 --- a/testing/tests_PyEC4PyHT_fastion/CLIC_DR.py +++ b/testing/tests_PyEC4PyHT_fastion/CLIC_DR.py @@ -1,4 +1,4 @@ -from __future__ import division + import sys sys.path.append("../") @@ -48,7 +48,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', wrap_z=True raise ValueError('ERROR: unknown machine configuration', pp.machine_configuration) if optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -67,7 +67,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', wrap_z=True pp.s = None elif optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -108,7 +108,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', wrap_z=True pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/testing/tests_PyEC4PyHT_multibunch/000_test_cloudsim.py b/testing/tests_PyEC4PyHT_multibunch/000_test_cloudsim.py index 15511aa6..af0bf7c7 100644 --- a/testing/tests_PyEC4PyHT_multibunch/000_test_cloudsim.py +++ b/testing/tests_PyEC4PyHT_multibunch/000_test_cloudsim.py @@ -75,7 +75,7 @@ # REMEBMBER TO START POPPING FROM THE RIGHT SIDE print('Start cloud sim') for i_turn in [0, 1]: - for ii in xrange(len(list_slices) - 1, -1, -1): + for ii in range(len(list_slices) - 1, -1, -1): ecloud.track(list_slices[ii]) #~ for cc in ecloud.cloudsim.cloud_list: #~ cc.pyeclsaver.t_last_save = 0. diff --git a/testing/tests_PyEC4PyHT_multibunch/machines_for_testing.py b/testing/tests_PyEC4PyHT_multibunch/machines_for_testing.py index 886a36c8..76ba5cac 100644 --- a/testing/tests_PyEC4PyHT_multibunch/machines_for_testing.py +++ b/testing/tests_PyEC4PyHT_multibunch/machines_for_testing.py @@ -43,7 +43,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): raise ValueError('machine_configuration not recognized!') if pp.optics_mode == 'smooth': - if 's' in kwargs.keys(): + if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') pp.n_segments = kwargs['n_segments'] @@ -62,7 +62,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.s = None elif pp.optics_mode == 'non-smooth': - if 'n_segments' in kwargs.keys(): + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -97,7 +97,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.app_y = 0 pp.app_xy = 0 - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/testing/tests_PyPARIS_single_bunch/001_check_output.py b/testing/tests_PyPARIS_single_bunch/001_check_output.py index 23cf3feb..575f1fc5 100644 --- a/testing/tests_PyPARIS_single_bunch/001_check_output.py +++ b/testing/tests_PyPARIS_single_bunch/001_check_output.py @@ -26,7 +26,7 @@ rms_err_x_list = [] rms_err_y_list = [] -for i_turn in xrange(N_turns-1): +for i_turn in range(N_turns-1): ob = mfm.object_with_arrays_and_scalar_from_h5('particles_at_turn_%d.h5'%i_turn) diff --git a/testing/tests_PyPARIS_single_bunch/Simulation_with_eclouds.py b/testing/tests_PyPARIS_single_bunch/Simulation_with_eclouds.py index 4636e0cf..47bffc02 100644 --- a/testing/tests_PyPARIS_single_bunch/Simulation_with_eclouds.py +++ b/testing/tests_PyPARIS_single_bunch/Simulation_with_eclouds.py @@ -46,10 +46,10 @@ def init_all(self): 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)) + 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)) + print('I am id=%d (master) and my part is %d long'%(myid, len(self.mypart))) # config e-cloud @@ -103,7 +103,7 @@ def init_master(self): # initialization bunch bunch = self.machine.generate_6D_Gaussian_bunch( macroparticlenumber_track, intensity, epsn_x, epsn_y, sigma_z=sigma_z) - print 'Bunch initialized.' + print('Bunch initialized.') #replace particles with HDTL ones self.n_part_per_turn = 5000 @@ -142,7 +142,7 @@ def init_master(self): pieces_to_be_treated = slice_obj_list - print 'N_turns', self.N_turns + print('N_turns', self.N_turns) return pieces_to_be_treated diff --git a/testing/tests_PyPARIS_single_bunch/machines_for_testing.py b/testing/tests_PyPARIS_single_bunch/machines_for_testing.py index 60a517aa..68ac9d3f 100644 --- a/testing/tests_PyPARIS_single_bunch/machines_for_testing.py +++ b/testing/tests_PyPARIS_single_bunch/machines_for_testing.py @@ -51,7 +51,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): if pp.optics_mode=='smooth': - if 's' in kwargs.keys(): raise ValueError('s vector cannot be provided if optics_mode = "smooth"') + if 's' in list(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 @@ -64,7 +64,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): 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"') + if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"') pp.n_segments = None pp.circumference = None @@ -101,7 +101,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): - for attr in kwargs.keys(): + for attr in list(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]) diff --git a/testing/tests_PyPARIS_single_bunch/mystyle.py b/testing/tests_PyPARIS_single_bunch/mystyle.py index de2249c5..73e2d51d 100644 --- a/testing/tests_PyPARIS_single_bunch/mystyle.py +++ b/testing/tests_PyPARIS_single_bunch/mystyle.py @@ -1,27 +1,27 @@ -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') +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/testing/tests_buildup/000_run_simulation.py b/testing/tests_buildup/000_run_simulation.py index aaded376..6bfb0c5b 100644 --- a/testing/tests_buildup/000_run_simulation.py +++ b/testing/tests_buildup/000_run_simulation.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time diff --git a/testing/tests_buildup/000b_run_test_checkpoint.py b/testing/tests_buildup/000b_run_test_checkpoint.py index a8aa1d7f..3f829c60 100644 --- a/testing/tests_buildup/000b_run_test_checkpoint.py +++ b/testing/tests_buildup/000b_run_test_checkpoint.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time @@ -48,7 +48,7 @@ def handler(signum, frame): time_0 = time.time() try: sim.run() -except KillSimulation, exc: +except KillSimulation as exc: print(exc) print("***** Checkpoint test: Termination done!") diff --git a/testing/tests_buildup/001_comparison_against_reference.py b/testing/tests_buildup/001_comparison_against_reference.py index fc56fe76..8a9eed4e 100644 --- a/testing/tests_buildup/001_comparison_against_reference.py +++ b/testing/tests_buildup/001_comparison_against_reference.py @@ -57,8 +57,8 @@ try: os.mkdir(folder_plot) except OSError as err: - print 'Folder not created due to exception:' - print err + print('Folder not created due to exception:') + print(err) myfontsz = 10 @@ -68,8 +68,8 @@ dict_curr = mlm.myloadmat(curr_folder + '/Pyecltest_angle%s.mat' % args.angle_dist_func) # load dictionary of the current simulation -out_var_ref = dict_ref.keys() # returns the list of keys -out_var_curr = dict_curr.keys() +out_var_ref = list(dict_ref.keys()) # returns the list of keys +out_var_curr = list(dict_curr.keys()) out_var_ref.sort() # sort the keys in alphabetical order out_var_curr.sort() @@ -77,14 +77,14 @@ n_pass = 5 # reference passage -print'Curr Variables are:' +print('Curr Variables are:') for variab in out_var_curr: - print variab, dict_curr[variab].shape + print(variab, dict_curr[variab].shape) for ii, k in enumerate(out_var_curr): if '__' in k or k == 'el_dens_at_probes': - print('Skipped %s' % k) + print(('Skipped %s' % k)) continue if len(dict_curr[k].shape) == 1: # var is a vector! @@ -95,16 +95,16 @@ pl.title(out_var_curr[ii], fontsize=myfontsz) pl.plot(dict_curr[k], 'b', label='curr_sim') - print ii, k, 'curr_sim' + print(ii, k, 'curr_sim') if (k in out_var_ref) and (dict_ref[k].shape != ()): #Plot vector for the reference simulation pl.plot(dict_ref[k], '--r', label='ref_sim') - print ii, k, 'ref_sim' + print(ii, k, 'ref_sim') else: - print '%s not in reference'%k + print('%s not in reference'%k) pl.legend(prop={'size': myfontsz}, bbox_to_anchor=(1, 1), loc='best') ms.sciy() @@ -129,7 +129,7 @@ cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() ms.sciy() - print ii, k, 'curr_sim' + print(ii, k, 'curr_sim') try: ind_in_mat = n_pass @@ -163,9 +163,9 @@ gs2.tight_layout(fig, rect=[0.45, 0, 1, 1], pad=1.08, h_pad=0.5) except IOError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) except IndexError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) if (k in out_var_ref) and (dict_ref[k].shape != ()): @@ -179,7 +179,7 @@ cbar.update_ticks() sp2.tick_params(labelsize=10) ms.sciy() - print ii, k, 'ref_sim' + print(ii, k, 'ref_sim') try: ind_in_mat = n_pass @@ -204,10 +204,10 @@ gs2.tight_layout(fig, rect=[0.45, 0, 1, 1], pad=1.08, h_pad=1.5) except IOError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) else: - print '%s not in reference'%k + print('%s not in reference'%k) gs1.tight_layout(fig, rect=[0, 0, 0.45, 1], pad=1.08) top = 0.9 @@ -219,9 +219,9 @@ pl.suptitle(sim_folder + '\n' + k) pl.savefig(folder_plot + '/angle%s_%s'%(args.angle_dist_func, k), dpi=300) -print 'Saved comparison plots in:' -print folder_plot +print('Saved comparison plots in:') +print(folder_plot) -print 'In ipython, you may call EOG() to view the results if EOG is installed.' +print('In ipython, you may call EOG() to view the results if EOG is installed.') EOG = lambda : os.system('eog %s/*%s* &' % (folder_plot, args.angle_dist_func)) #~ #pl.show() diff --git a/testing/tests_buildup/003_update_reference_matfiles.py b/testing/tests_buildup/003_update_reference_matfiles.py index 08743a8e..32715fb2 100644 --- a/testing/tests_buildup/003_update_reference_matfiles.py +++ b/testing/tests_buildup/003_update_reference_matfiles.py @@ -5,7 +5,7 @@ if sys.version_info.major != 2: raw_input = input -if raw_input('Continue replace all reference files? y/n ') not in ('y', 'yes'): +if input('Continue replace all reference files? y/n ') not in ('y', 'yes'): sys.exit() all_sim_folders = [ @@ -42,7 +42,7 @@ if os.path.isfile(ref_file): os.remove(ref_file) shutil.copy(mat_file, ref_file) - print('%s replaced by %s' % (ref_file, mat_file)) + print(('%s replaced by %s' % (ref_file, mat_file))) # OLD STUFF: #for folder in all_sim_folders: diff --git a/testing/tests_modules/000_test_photoemission.py b/testing/tests_modules/000_test_photoemission.py index d1cb9b1f..5dc59654 100644 --- a/testing/tests_modules/000_test_photoemission.py +++ b/testing/tests_modules/000_test_photoemission.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import argparse diff --git a/testing/tests_modules/001_test_multipole.py b/testing/tests_modules/001_test_multipole.py index e6e6035c..bf8cf6e0 100644 --- a/testing/tests_modules/001_test_multipole.py +++ b/testing/tests_modules/001_test_multipole.py @@ -1,4 +1,4 @@ -from __future__ import division + import sys import os import math diff --git a/testing/tests_modules/003_test_Boris_quad_compar.py b/testing/tests_modules/003_test_Boris_quad_compar.py index c97d183a..3d0055be 100644 --- a/testing/tests_modules/003_test_Boris_quad_compar.py +++ b/testing/tests_modules/003_test_Boris_quad_compar.py @@ -160,7 +160,7 @@ for ii in range(N_steps): if np.mod(ii, 10000) == 0: - print float(ii) / float(N_steps) + print(float(ii) / float(N_steps)) #print ii x_lisB.append(MP_eB.x_mp.copy()) y_lisB.append(MP_eB.y_mp.copy()) diff --git a/testing/tests_modules/007_test_ECLOUD_sey_curves.py b/testing/tests_modules/007_test_ECLOUD_sey_curves.py index 54711f0b..fc341173 100644 --- a/testing/tests_modules/007_test_ECLOUD_sey_curves.py +++ b/testing/tests_modules/007_test_ECLOUD_sey_curves.py @@ -35,12 +35,12 @@ def del_true_ECLOUD(energy, cos_theta, del_max, s=1.35, E_max=332.): def extract_sey_curves(n_rep, E_impact_eV_test, cos_theta_test, charge, mass): deltas = {} - for etype in sey_mod.event_types.keys(): + for etype in list(sey_mod.event_types.keys()): etype_name = sey_mod.event_types[etype] deltas[etype_name] = np.zeros((len(cos_theta_test), len(E_impact_eV_test))) print('Extracting SEY curves...') for i_ct, ct in enumerate(cos_theta_test): - print('%d/%d' % (i_ct + 1, len(cos_theta_test))) + print(('%d/%d' % (i_ct + 1, len(cos_theta_test)))) for i_ene, Ene in enumerate(E_impact_eV_test): nel_impact = np.ones(n_rep) @@ -65,7 +65,7 @@ def extract_sey_curves(n_rep, E_impact_eV_test, cos_theta_test, charge, mass): nel_mp_th=1, flag_seg=True) - for etype in sey_mod.event_types.keys(): + for etype in list(sey_mod.event_types.keys()): etype_name = sey_mod.event_types[etype] thisdelta = deltas[etype_name] thisdelta[i_ct, i_ene] = np.sum( diff --git a/testing/tests_modules/010_test_Furman_Pivi_sey_curves.py b/testing/tests_modules/010_test_Furman_Pivi_sey_curves.py index c3820616..1649f5db 100644 --- a/testing/tests_modules/010_test_Furman_Pivi_sey_curves.py +++ b/testing/tests_modules/010_test_Furman_Pivi_sey_curves.py @@ -174,12 +174,12 @@ def del_true_ECLOUD(energy, del_max, s=1.35, E_max=332., costheta=1.): def extract_sey_curves(n_rep, E_impact_eV_test, cos_theta_test, charge, mass): deltas = {} - for etype in sey_mod.event_types.keys(): + for etype in list(sey_mod.event_types.keys()): etype_name = sey_mod.event_types[etype] deltas[etype_name] = np.zeros((len(cos_theta_test), len(E_impact_eV_test))) print('Extracting SEY curves...') for i_ct, ct in enumerate(cos_theta_test): - print('%d/%d' % (i_ct + 1, len(cos_theta_test))) + print(('%d/%d' % (i_ct + 1, len(cos_theta_test)))) for i_ene, Ene in enumerate(E_impact_eV_test): nel_impact = np.ones(n_rep) @@ -204,7 +204,7 @@ def extract_sey_curves(n_rep, E_impact_eV_test, cos_theta_test, charge, mass): nel_mp_th=1, flag_seg=True) - for etype in sey_mod.event_types.keys(): + for etype in list(sey_mod.event_types.keys()): etype_name = sey_mod.event_types[etype] thisdelta = deltas[etype_name] thisdelta[i_ct, i_ene] = np.sum( diff --git a/testing/tests_modules/010b_test_Furman_Pivi_sey_curves.py b/testing/tests_modules/010b_test_Furman_Pivi_sey_curves.py index 3bfbe1dd..2138afc9 100644 --- a/testing/tests_modules/010b_test_Furman_Pivi_sey_curves.py +++ b/testing/tests_modules/010b_test_Furman_Pivi_sey_curves.py @@ -137,12 +137,12 @@ def del_true_ECLOUD(energy, del_max, s=1.35, E_max=332.): def extract_sey_curves(n_rep, E_impact_eV_test, cos_theta_test, charge, mass): deltas = {} - for etype in sey_mod.event_types.keys(): + for etype in list(sey_mod.event_types.keys()): etype_name = sey_mod.event_types[etype] deltas[etype_name] = np.zeros((len(cos_theta_test), len(E_impact_eV_test))) print('Extracting SEY curves...') for i_ct, ct in enumerate(cos_theta_test): - print('%d/%d' % (i_ct + 1, len(cos_theta_test))) + print(('%d/%d' % (i_ct + 1, len(cos_theta_test)))) for i_ene, Ene in enumerate(E_impact_eV_test): nel_impact = np.ones(n_rep) @@ -167,7 +167,7 @@ def extract_sey_curves(n_rep, E_impact_eV_test, cos_theta_test, charge, mass): nel_mp_th=1, flag_seg=True) - for etype in sey_mod.event_types.keys(): + for etype in list(sey_mod.event_types.keys()): etype_name = sey_mod.event_types[etype] thisdelta = deltas[etype_name] thisdelta[i_ct, i_ene] = np.sum( diff --git a/testing/tests_multicloud/000_run_simulation.py b/testing/tests_multicloud/000_run_simulation.py index a9034769..5a3be4a0 100644 --- a/testing/tests_multicloud/000_run_simulation.py +++ b/testing/tests_multicloud/000_run_simulation.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time diff --git a/testing/tests_multicloud/001_comparison_against_reference_multispecies.py b/testing/tests_multicloud/001_comparison_against_reference_multispecies.py index de2b38e1..3f698791 100644 --- a/testing/tests_multicloud/001_comparison_against_reference_multispecies.py +++ b/testing/tests_multicloud/001_comparison_against_reference_multispecies.py @@ -38,8 +38,8 @@ try: os.mkdir(folder_plot) except OSError as err: - print 'Folder not created due to exception:' - print err + print('Folder not created due to exception:') + print(err) myfontsz = 10 @@ -55,8 +55,8 @@ dict_curr_list.append(mlm.myloadmat(curr_folder + '/Pyecltest_angle%s_%s.mat' % (args.angle_dist_func, cloud_name))) # load dictionary of the current simulation -out_var_ref = dict_ref.keys() # returns the list of keys -out_var_curr = dict_curr_list[0].keys() +out_var_ref = list(dict_ref.keys()) # returns the list of keys +out_var_curr = list(dict_curr_list[0].keys()) out_var_ref.sort() # sort the keys in alphabetical order out_var_curr.sort() @@ -66,14 +66,14 @@ var_no_sum_list = ['En_g_hist', 'lam_t_array', 'N_mp_corrected_pass', 'N_mp_impact_pass', 'N_mp_ref_pass', 'sey_test_cos_theta', 'sey_test_del_elast_mat', 'sey_test_del_true_mat', 'sey_test_E_impact_eV', 't', 't_En_hist', 't_hist', 't_sc_video', 'xg_hist', 'xg_hist_cos_angle', 'U_sc_eV'] -print'Curr Variables are:' +print('Curr Variables are:') for variab in out_var_curr: - print variab, dict_curr_list[0][variab].shape + print(variab, dict_curr_list[0][variab].shape) for ii, k in enumerate(out_var_curr): if '__' in k or k == 'el_dens_at_probes': - print('Skipped %s' % k) + print(('Skipped %s' % k)) continue if len(dict_curr_list[0][k].shape) == 1: # var is a vector! @@ -96,10 +96,10 @@ if (k in out_var_ref) and (dict_ref[k].shape != ()): pl.plot(dict_ref[k], 'r', label='ref_sim') - print ii, k, 'ref_sim' + print(ii, k, 'ref_sim') else: - print '%s not in reference'%k + print('%s not in reference'%k) pl.legend(prop={'size': myfontsz}, bbox_to_anchor=(1, 1), loc='best') ms.sciy() @@ -127,7 +127,7 @@ cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() ms.sciy() - print ii, k, 'curr_sim' + print(ii, k, 'curr_sim') try: ind_in_mat = n_pass @@ -179,9 +179,9 @@ gs2.tight_layout(fig, rect=[0.45, 0, 1, 1], pad=1.08, h_pad=0.5) except IOError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) except IndexError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) if (k in out_var_ref) and (dict_ref[k].shape != ()): @@ -194,7 +194,7 @@ cbar.formatter.set_powerlimits((0, 0)) cbar.update_ticks() ms.sciy() - print ii, k, 'ref_sim' + print(ii, k, 'ref_sim') try: @@ -220,12 +220,12 @@ gs2.tight_layout(fig, rect=[0.45, 0, 1, 1], pad=1.08, h_pad=1.5) except IOError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) except IndexError as goterror: - print 'Skipped. Got:', goterror + print('Skipped. Got:', goterror) else: - print '%s not in reference'%k + print('%s not in reference'%k) gs1.tight_layout(fig, rect=[0, 0, 0.45, 1], pad=1.08) top = 0.9 @@ -236,10 +236,10 @@ pl.savefig(folder_plot + '/angle%s_%s'%(args.angle_dist_func, k), dpi=300) -print 'Saved comparison plots in:' -print folder_plot +print('Saved comparison plots in:') +print(folder_plot) -print 'In ipython, you may call EOG() to view the results if EOG is installed.' +print('In ipython, you may call EOG() to view the results if EOG is installed.') EOG = lambda : os.system('eog %s/*%s*' % (folder_plot, args.angle_dist_func)) # pl.show() diff --git a/testing/tests_multicloud/002_run_simulation_crossion.py b/testing/tests_multicloud/002_run_simulation_crossion.py index ff99141f..ac8e8004 100644 --- a/testing/tests_multicloud/002_run_simulation_crossion.py +++ b/testing/tests_multicloud/002_run_simulation_crossion.py @@ -1,4 +1,4 @@ -from __future__ import division, print_function + import sys import os import time