Skip to content

Commit ab851fe

Browse files
committed
Python 3 migration of PyPARIS 2.4.1
1 parent 4d1ec92 commit ab851fe

File tree

12 files changed

+51
-51
lines changed

12 files changed

+51
-51
lines changed

communication_helpers.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
def combine_float_buffers(list_of_buffers):
88
N_buffers = len(list_of_buffers)
9-
len_buffers = np.array(map(lambda seq: float(len(seq)), list_of_buffers))
9+
len_buffers = np.array([float(len(seq)) for seq in list_of_buffers])
1010
return np.array(np.concatenate([np.array([float(N_buffers)]), len_buffers]+list_of_buffers),dtype=np.float64)
1111

1212
def split_float_buffers(megabuffer):
@@ -19,7 +19,7 @@ def split_float_buffers(megabuffer):
1919
i_mbuf += N_buffers
2020

2121
list_of_buffers = []
22-
for i_buf in xrange(N_buffers):
22+
for i_buf in range(N_buffers):
2323
lenbuf = int(len_buffers[i_buf])
2424
list_of_buffers.append(megabuffer[i_mbuf:i_mbuf+lenbuf])
2525
i_mbuf += lenbuf
@@ -31,12 +31,12 @@ def split_float_buffers(megabuffer):
3131

3232

3333
def list_of_strings_2_buffer(strlist):
34-
data = ''.join(map(lambda s:s+';', strlist))+'\nendbuf\n'
35-
buf_to_send = np.atleast_1d(np.int_(np.array(map(ord, list(data)))))
34+
data = ''.join([s+';' for s in strlist])+'\nendbuf\n'
35+
buf_to_send = np.atleast_1d(np.int_(np.array(list(map(ord, list(data))))))
3636
return buf_to_send
3737

3838
def buffer_2_list_of_strings(buf):
39-
str_received = ''.join(map(unichr, list(buf)))
39+
str_received = ''.join(map(chr, list(buf)))
4040
strlist = list(map(str, str_received.split('\nendbuf\n')[0].split(';')))[:-1]
4141
return strlist
4242

@@ -73,7 +73,7 @@ def beam_2_buffer(beam, mode='pickle', verbose=False):
7373
# Beam data buffer
7474
if mode=='json':
7575
sinfo_str = json.dumps(sinfo)
76-
sinfo_int = np.array(map(ord, sinfo_str), dtype=np.int)
76+
sinfo_int = np.array(list(map(ord, sinfo_str)), dtype=np.int)
7777
sinfo_float_buf = sinfo_int.astype(np.float, casting='safe')
7878
elif mode=='pickle':
7979
pss = pickle.dumps(sinfo, protocol=2)
@@ -100,10 +100,10 @@ def beam_2_buffer(beam, mode='pickle', verbose=False):
100100
np.array([float(len(sinfo_float_buf))]),sinfo_float_buf)), dtype=np.float64)
101101

102102
if verbose:
103-
print('mode=%s'%mode)
104-
print('beam.macroparticlenumber:%d'%beam.macroparticlenumber)
105-
print('len(buf):%d'%len(buf))
106-
print('len(sinfo_float_buf):%d'%len(sinfo_float_buf))
103+
print(('mode=%s'%mode))
104+
print(('beam.macroparticlenumber:%d'%beam.macroparticlenumber))
105+
print(('len(buf):%d'%len(buf)))
106+
print(('len(sinfo_float_buf):%d'%len(sinfo_float_buf)))
107107

108108
return buf
109109

@@ -175,7 +175,7 @@ def buffer_2_beam(buf, mode='pickle'):
175175

176176
if mode=='json':
177177
si_int = slice_info_buf.astype(np.int)
178-
si_str = ''.join(map(unichr, list(si_int)))
178+
si_str = ''.join(map(chr, list(si_int)))
179179
beam.slice_info = json.loads(si_str)
180180
elif mode=='pickle':
181181
# Get length in bytes

gen_multibunch_beam.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def gen_matched_multibunch_beam(machine, n_macroparticles_per_bunch, filling_pat
2323
list_genbunches = []
2424
for i_slot, inten_slot in enumerate(filling_pattern):
2525
if inten_slot>0:
26-
print('Generating bunch at slot %d/%d'%(i_slot, len(filling_pattern)))
26+
print(('Generating bunch at slot %d/%d'%(i_slot, len(filling_pattern))))
2727
bunch = generate_bunch(n_macroparticles_per_bunch, inten_slot*bunch_intensity, epsn_x, epsn_y, sigma_z=sigma_z)
2828
bunch.z -= b_spac_buckets*bucket_length_m*i_slot
2929
list_genbunches.append(bunch)
@@ -63,13 +63,13 @@ def load_multibunch_beam(dirname, reset_i_turns=True):
6363
import PyPARIS.myfilemanager as mfm
6464
import PyPARIS.communication_helpers as ch
6565

66-
print('Loading the beam from %s'%dirname)
66+
print(('Loading the beam from %s'%dirname))
6767

6868
bzero = ch.buffer_2_beam(mfm.dict_of_arrays_and_scalar_from_h5(
6969
dirname+'/bunch0.h5')['bunchbuffer'])
7070
N_bunches_tot_beam = bzero.slice_info['N_bunches_tot_beam']
7171
list_bunches = [bzero]
72-
for ibun in xrange(1, N_bunches_tot_beam):
72+
for ibun in range(1, N_bunches_tot_beam):
7373
list_bunches.append(ch.buffer_2_beam(
7474
mfm.dict_of_arrays_and_scalar_from_h5(
7575
dirname+'/bunch%d.h5'%ibun)['bunchbuffer']))
@@ -89,7 +89,7 @@ def save_bunch_to_folder(bunch, dirname):
8989
os.makedirs(dirname)
9090
buf = ch.beam_2_buffer(bunch)
9191
bpath = dirname+'/bunch%d.h5'%bunch.slice_info['i_bunch']
92-
print('Saving: ' + bpath)
92+
print(('Saving: ' + bpath))
9393
mfm.dict_to_h5(dict_save={'bunchbuffer':buf},
9494
filename=bpath)
9595

generate_python3

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ rm -rf ../python3/PyPARIS
33
cp -r ../PyPARIS ../python3/PyPARIS
44
rm ../python3/PyPARIS/*.so
55
2to3 --output-dir=../python3/PyPARIS -W -n ../PyPARIS
6-
rm -rf ../python3/PyPARIS/.git
6+
# rm -rf ../python3/PyPARIS/.git

multiprocexec.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def todo(sim_module_string, pid, N_proc, queue_list,
112112

113113
sim_module_string = sys.argv[3].split('=')[-1]
114114

115-
queue_list = [mp.Queue() for _ in xrange(N_proc)]
115+
queue_list = [mp.Queue() for _ in range(N_proc)]
116116

117117
mutex = mp.Semaphore(1)
118118
barrier = mp.Semaphore(0)
@@ -121,7 +121,7 @@ def todo(sim_module_string, pid, N_proc, queue_list,
121121
cnt = mp.Value('i', 0)
122122

123123
proc_list = []
124-
for pid in xrange(N_proc):
124+
for pid in range(N_proc):
125125
proc_list.append(mp.Process(target=todo,
126126
args=(sim_module_string, pid, N_proc, queue_list,
127127
mutex, barrier, turnstile, turnstile2, cnt, multiturn)))

myfilemanager.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
class obj_from_dict:
55
def __init__(self, dictto):
6-
for kk in dictto.keys():
6+
for kk in list(dictto.keys()):
77
setattr(self, kk, dictto[kk])
88

99

@@ -18,7 +18,7 @@ def myloadmat(filename, squeeze = True):
1818
import scipy.io as sio
1919
dict_var=sio.loadmat(filename)
2020
if squeeze:
21-
for kk in dict_var.keys():
21+
for kk in list(dict_var.keys()):
2222
try:
2323
dict_var[kk]=np.squeeze(dict_var[kk])
2424
except:
@@ -32,7 +32,7 @@ def dict_of_arrays_and_scalar_from_h5(filename):
3232
import h5py
3333
with h5py.File(filename, 'r') as fid:
3434
f_dict = {}
35-
for kk in fid.keys():
35+
for kk in list(fid.keys()):
3636
f_dict[kk] = np.array(fid[kk]).copy()
3737
if f_dict[kk].shape == ():
3838
f_dict[kk] = f_dict[kk].tolist()
@@ -47,7 +47,7 @@ def monitorh5_to_dict(filename, key= 'Bunch'):
4747
with h5py.File(filename, 'r') as monitor_ev:
4848
monitor = monitor_ev[key]
4949
monitor_dict = {}
50-
for kk in monitor.keys():
50+
for kk in list(monitor.keys()):
5151
monitor_dict[kk] = np.array(monitor[kk]).copy()
5252

5353
return monitor_dict
@@ -58,15 +58,15 @@ def monitorh5_to_obj(filename, key= 'Bunch'):
5858

5959
def monitorh5list_to_dict(filename_list, key='Bunch', flag_transpose=False, permissive=False):
6060
monitor_dict = monitorh5_to_dict(filename_list[0], key=key)
61-
for i_file in xrange(1, len(filename_list)):
62-
print('Loading '+filename_list[i_file])
61+
for i_file in range(1, len(filename_list)):
62+
print(('Loading '+filename_list[i_file]))
6363
try:
6464
monitor_dict_curr = monitorh5_to_dict(filename_list[i_file], key=key)
6565
if flag_transpose:
66-
for kk in monitor_dict.keys():
66+
for kk in list(monitor_dict.keys()):
6767
monitor_dict[kk] = np.array(list(monitor_dict[kk].T)+list(monitor_dict_curr[kk].T)).T
6868
else:
69-
for kk in monitor_dict.keys():
69+
for kk in list(monitor_dict.keys()):
7070
monitor_dict[kk] = np.array(list(monitor_dict[kk])+list(monitor_dict_curr[kk]))
7171
except IOError as err:
7272
print('Got:')
@@ -83,7 +83,7 @@ def monitorh5list_to_obj(filename_list, key= 'Bunch', flag_transpose=False, perm
8383
def dict_to_h5(dict_save, filename, compression=None, compression_opts=None):
8484
import h5py
8585
with h5py.File(filename, 'w') as fid:
86-
for kk in dict_save.keys():
86+
for kk in list(dict_save.keys()):
8787
fid.create_dataset(kk, data=dict_save[kk],
8888
compression=compression, compression_opts=compression_opts)
8989

ring_of_CPUs.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import numpy as np
22

3-
import communication_helpers as ch
3+
from . import communication_helpers as ch
44

55
logfilename = 'pyparislog.txt'
66
def print2logandstdo(message, mode='a+'):
7-
print message
7+
print(message)
88
with open(logfilename, mode) as fid:
99
fid.writelines([message+'\n'])
1010

@@ -111,7 +111,7 @@ def run(self):
111111
orders_from_master = []
112112
list_of_buffers_to_send = []
113113

114-
for _ in xrange(self.N_pieces_per_transfer):
114+
for _ in range(self.N_pieces_per_transfer):
115115
# pop a piece
116116
try:
117117
piece_to_send = self.pieces_to_be_treated.pop() # pop starts for the last slices
@@ -128,7 +128,7 @@ def run(self):
128128
raise ValueError('Float buffer is too small!')
129129
self.comm.Sendrecv(sendbuf, dest=0, sendtag=0,
130130
recvbuf=self.buf_float, source=self.master_id-1, recvtag=self.myid)
131-
list_received_pieces = map(self.sim_content.buffer_to_piece, ch.split_float_buffers(self.buf_float))
131+
list_received_pieces = list(map(self.sim_content.buffer_to_piece, ch.split_float_buffers(self.buf_float)))
132132

133133
# treat received pieces
134134
for piece_received in list_received_pieces:
@@ -187,15 +187,15 @@ def run(self):
187187
raise ValueError('Float buffer is too small!')
188188
self.comm.Sendrecv(sendbuf, dest=self.right, sendtag=self.right,
189189
recvbuf=self.buf_float, source=self.left, recvtag=self.myid)
190-
list_received_pieces = map(self.sim_content.buffer_to_piece, ch.split_float_buffers(self.buf_float))
190+
list_received_pieces = list(map(self.sim_content.buffer_to_piece, ch.split_float_buffers(self.buf_float)))
191191

192192
# treat received piece
193193
for piece_received in list_received_pieces:
194194
if piece_received is not None:
195195
self.sim_content.treat_piece(piece_received) #the elements of the list are being mutated
196196

197197
# prepare for next iteration
198-
list_of_buffers_to_send = map(self.sim_content.piece_to_buffer, list_received_pieces)
198+
list_of_buffers_to_send = list(map(self.sim_content.piece_to_buffer, list_received_pieces))
199199

200200
# receive orders from the master
201201
self.comm.Bcast(self.buf_int, self.master_id)
@@ -218,11 +218,11 @@ def run(self):
218218

219219
class SingleCoreComminicator(object):
220220
def __init__(self):
221-
print '\n\n\n'
222-
print '****************************************'
223-
print '*** Using single core MPI simulator! ***'
224-
print '****************************************'
225-
print '\n\n\n'
221+
print('\n\n\n')
222+
print('****************************************')
223+
print('*** Using single core MPI simulator! ***')
224+
print('****************************************')
225+
print('\n\n\n')
226226

227227
def Get_size(self):
228228
return 1

ring_of_CPUs_multiturn.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
import sys, os
44
import socket
55

6-
from ring_of_CPUs import SingleCoreComminicator
6+
from .ring_of_CPUs import SingleCoreComminicator
77

8-
import communication_helpers as ch
8+
from . import communication_helpers as ch
99
from collections import deque
1010

1111
logfilename = 'pyparislog.txt'
1212
def print2logandstdo(message, mode='a+'):
13-
print message
13+
print(message)
1414
with open(logfilename, mode) as fid:
1515
fid.writelines([message+'\n'])
1616

@@ -252,7 +252,7 @@ def run(self):
252252
slice_group.append(None)
253253
else:
254254
# Buffer to slice
255-
slice_group = map(self.sim_content.buffer_to_piece, list_received_buffers)
255+
slice_group = list(map(self.sim_content.buffer_to_piece, list_received_buffers))
256256

257257

258258

@@ -295,7 +295,7 @@ def run(self):
295295
list_of_buffers_to_send = [self.sim_content.piece_to_buffer(bunch_to_be_sent)]
296296
else:
297297
# Slice to buffer
298-
list_of_buffers_to_send = map(self.sim_content.piece_to_buffer, slice_group)
298+
list_of_buffers_to_send = list(map(self.sim_content.piece_to_buffer, slice_group))
299299

300300

301301
########################

slicing_tool.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,12 @@ def slice_a_bunch(this_bunch, z_cut, n_slices):
7272
mass=this_bunch.mass, circumference=this_bunch.circumference,
7373
gamma=this_bunch.gamma,
7474
coords_n_momenta_dict=this_bunch.get_coords_n_momenta_dict())
75-
copy_this_bunch.slice_info = {kk:this_bunch.slice_info[kk] for kk in this_bunch.slice_info.keys()}
75+
copy_this_bunch.slice_info = {kk:this_bunch.slice_info[kk] for kk in list(this_bunch.slice_info.keys())}
7676

7777
list_slices_this_bunch = [copy_this_bunch]
7878

7979
for i_sl, ss in enumerate(list_slices_this_bunch[::-1]): # I want slice 0 to be at the head
80-
ss.slice_info['info_parent_bunch'] = {kk: this_bunch.slice_info[kk] for kk in this_bunch.slice_info.keys()}
80+
ss.slice_info['info_parent_bunch'] = {kk: this_bunch.slice_info[kk] for kk in list(this_bunch.slice_info.keys())}
8181
ss.slice_info['i_slice'] = i_sl
8282
ss.slice_info['N_slices_tot_bunch'] = len(list_slices_this_bunch)
8383

test_multibunch/000_test_beam_generation/006_test_genbeam_slice_buffer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@
9898
# check bunch merge
9999
list_bunches_rec = []
100100
for ibun, lbun in enumerate(list_bunch_buffers):
101-
list_sl = map(ch.buffer_2_beam, lbun)
101+
list_sl = list(map(ch.buffer_2_beam, lbun))
102102
list_bunches_rec.append(st.merge_slices_into_bunch(list_sl))
103103

104104
fig2 = plt.figure(2, figsize=(8, 6*1.3))

test_multibunch/000_test_beam_generation/machines_for_testing.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs):
5252

5353

5454
if pp.optics_mode=='smooth':
55-
if 's' in kwargs.keys(): raise ValueError('s vector cannot be provided if optics_mode = "smooth"')
55+
if 's' in list(kwargs.keys()): raise ValueError('s vector cannot be provided if optics_mode = "smooth"')
5656

5757
pp.n_segments = kwargs['n_segments']
5858
pp.circumference = 1100*2*np.pi
@@ -65,7 +65,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs):
6565
pp.s = None
6666

6767
elif pp.optics_mode=='non-smooth':
68-
if 'n_segments' in kwargs.keys(): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"')
68+
if 'n_segments' in list(kwargs.keys()): raise ValueError('n_segments cannot be provided if optics_mode = "non-smooth"')
6969
pp.n_segments = None
7070
pp.circumference = None
7171

@@ -100,7 +100,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs):
100100
pp.app_y = 0
101101
pp.app_xy = 0
102102

103-
for attr in kwargs.keys():
103+
for attr in list(kwargs.keys()):
104104
if kwargs[attr] is not None:
105105
if type(kwargs[attr]) is list or type(kwargs[attr]) is np.ndarray:
106106
str2print = '[%s ...]'%repr(kwargs[attr][0])

0 commit comments

Comments
 (0)