Skip to content

Commit

Permalink
Python 3 migration of PyHEADTAIL v1.13.5
Browse files Browse the repository at this point in the history
  • Loading branch information
lmether committed Nov 28, 2019
1 parent e05caf2 commit c24bf3b
Show file tree
Hide file tree
Showing 70 changed files with 217 additions and 235 deletions.
2 changes: 1 addition & 1 deletion PyHEADTAIL/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from ._version import __version__
dirty = False

print ('PyHEADTAIL v' + __version__)
print(('PyHEADTAIL v' + __version__))
if dirty:
print ('(dirty git work tree)')
print ('\n')
Expand Down
6 changes: 2 additions & 4 deletions PyHEADTAIL/aperture/aperture.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
Michael Schenk
'''

from __future__ import division


import numpy as np
from abc import ABCMeta, abstractmethod
Expand All @@ -23,15 +23,13 @@ def make_int32(array):
return array.astype(np.int32)


class Aperture(Element):
class Aperture(Element, metaclass=ABCMeta):
'''Abstract base class for Aperture elements. An aperture is
generally defined as a condition on the phase space coordinates.
Particles not fulfilling this condition are tagged as lost and
are removed from the beam directly after.
'''

__metaclass__ = ABCMeta

@clean_slices
def track(self, beam):
'''Tag particles not passing through the aperture as lost. If
Expand Down
4 changes: 2 additions & 2 deletions PyHEADTAIL/cobra_functions/curve_tools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import division


import numpy as np
from scipy.optimize import brentq
Expand All @@ -20,4 +20,4 @@ def extrema(x, y=None):
zix = np.where(np.abs(np.diff(np.sign(np.diff(x)))) == 2)[0]
return zix
if not y:
print zix
print(zix)
2 changes: 1 addition & 1 deletion PyHEADTAIL/feedback/transverse_damper.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
@copyright CERN
'''

from __future__ import division


import numpy as np
from scipy.special import k0
Expand Down
2 changes: 1 addition & 1 deletion PyHEADTAIL/feedback/widebandfeedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
@copyright CERN
'''

from __future__ import division


import numpy as np
from scipy.special import k0
Expand Down
2 changes: 1 addition & 1 deletion PyHEADTAIL/field_maps/Transverse_Efield_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def track(self, beam):

slices = beam.get_slices(self.slicer)

for sid in xrange(slices.n_slices-1, -1, -1):
for sid in range(slices.n_slices-1, -1, -1):

# select particles in the slice
pid = slices.particle_indices_of_slice(sid)
Expand Down
10 changes: 5 additions & 5 deletions PyHEADTAIL/field_maps/field_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
@date: 13.06.2017
'''

from __future__ import division, print_function


from scipy.constants import c

Expand Down Expand Up @@ -82,7 +82,7 @@ def __init__(self, length, mesh, fields, wrt_beam_centroid=False,
poissonsolver=None,
gradient=lambda *args, **kwargs: None,
mesh=mesh)
self.fields = map(pm.ensure_same_device, fields)
self.fields = list(map(pm.ensure_same_device, fields))
self.wrt_beam_centroid = wrt_beam_centroid

def track(self, beam):
Expand All @@ -94,7 +94,7 @@ def track(self, beam):
beam.y - my,
beam.z - mz] # zip will cut to #fields

mesh_fields_and_mp_coords = zip(self.fields, mp_coords)
mesh_fields_and_mp_coords = list(zip(self.fields, mp_coords))

# electric fields at each particle position in lab frame [V/m]
part_fields = self.pypic.field_to_particles(*mesh_fields_and_mp_coords)
Expand Down Expand Up @@ -149,7 +149,7 @@ def __init__(self, slicer, *args, **kwargs):
# require 2D!
assert self.pypic.mesh.dimension == 2, \
'mesh needs to be two-dimensional!'
assert all(map(lambda f: f.ndim == 2, self.fields)), \
assert all([f.ndim == 2 for f in self.fields]), \
'transverse field components need to be two-dimensional arrays!'
#

Expand All @@ -167,7 +167,7 @@ def track(self, beam):
mp_coords = [beam.x - mx,
beam.y - my,
beam.z] # zip will cut to #fields
mesh_fields_and_mp_coords = zip(self.fields, mp_coords)
mesh_fields_and_mp_coords = list(zip(self.fields, mp_coords))

# electric fields at each particle position in lab frame [V/m]
part_fields = self.pypic.field_to_particles(*mesh_fields_and_mp_coords)
Expand Down
4 changes: 2 additions & 2 deletions PyHEADTAIL/general/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def deprecated_wrapper(*args, **kwargs):
'PyHEADTAIL release!'.format(name),
category=DeprecationWarning, stacklevel=2)
warnings.simplefilter('default', DeprecationWarning)
print message
print(message)
return func(*args, **kwargs)
return deprecated_wrapper
return deprecated_decorator
Expand All @@ -41,7 +41,7 @@ def memoize(function):
@wraps(function)
def evaluate(*args):
signature = (args)
if not store.has_key(signature):
if signature not in store:
store[signature] = function(*args)
return store[signature]
return evaluate
Expand Down
3 changes: 1 addition & 2 deletions PyHEADTAIL/general/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,11 @@ def warns(self, output):
self._warningprinter.prints("*** PyHEADTAIL WARNING! " + output)


class Element(Printing):
class Element(Printing, metaclass=ABCMeta):
'''
Abstract element as part of the tracking layout. Guarantees
to fulfil its tracking contract via the method track(beam).
'''
__metaclass__ = ABCMeta

@abstractmethod
def track(self, beam):
Expand Down
4 changes: 2 additions & 2 deletions PyHEADTAIL/general/pmath.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,8 +331,8 @@ def update_active_dict(new_dict):
if not hasattr(update_active_dict, 'active_dict'):
update_active_dict.active_dict = new_dict
# delete all old implementations/references from globals()
for key in globals().keys():
if key in update_active_dict.active_dict.keys():
for key in list(globals().keys()):
if key in list(update_active_dict.active_dict.keys()):
del globals()[key]
# add the new active dict to the globals()
globals().update(new_dict)
Expand Down
3 changes: 1 addition & 2 deletions PyHEADTAIL/general/printers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from abc import ABCMeta, abstractmethod


class Printer(object):
class Printer(object, metaclass=ABCMeta):
'''
A generic printer knows where to redirect text for print.
Use Printer.prints(output) to print the output instead of
Expand All @@ -22,7 +22,6 @@ class Printer(object):
a file or use different streams for errors, warnings and content
related output etc.
'''
__metaclass__ = ABCMeta

@abstractmethod
def prints(self, output):
Expand Down
4 changes: 2 additions & 2 deletions PyHEADTAIL/gpu/gpu_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@
atexit.register(skcuda.misc.shutdown)

n_streams = 4
streams = [drv.Stream() for i in xrange(n_streams)]
streams = [drv.Stream() for i in range(n_streams)]
stream_pool = cycle(streams)

stream_emittance = [drv.Stream() for i in xrange(6)]
stream_emittance = [drv.Stream() for i in range(6)]


def dummy_1(gpuarr, stream=None):
Expand Down
18 changes: 9 additions & 9 deletions PyHEADTAIL/gpu/gpu_wrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
Use in dispatch of general/pmath
All functions assume GPU arrays as arguments!
'''
from __future__ import division

import numpy as np
import os
import gpu_utils
from . import gpu_utils
import math
from functools import wraps
try:
Expand Down Expand Up @@ -226,7 +226,7 @@ def sign(array, out=None, stream=None):
'else notclose[i] = 0;',
name='allclose_kernel'
)
np_allclose_defaults = np.allclose.func_defaults # (rtol, atol, equal_nan)
np_allclose_defaults = np.allclose.__defaults__ # (rtol, atol, equal_nan)
@wraps(np.allclose)
def allclose(a, b, rtol=np_allclose_defaults[0],
atol=np_allclose_defaults[1], out=None, stream=None):
Expand Down Expand Up @@ -565,9 +565,9 @@ def argsort(to_sort):
elif dtype.itemsize == 4 and dtype.kind is 'i':
thrust.get_sort_perm_int(to_sort.copy(), permutation)
else:
print to_sort.dtype
print to_sort.dtype.itemsize
print to_sort.dtype.kind
print(to_sort.dtype)
print(to_sort.dtype.itemsize)
print(to_sort.dtype.kind)
raise TypeError('Currently only float64 and int32 types can be sorted')
return permutation

Expand Down Expand Up @@ -603,9 +603,9 @@ def apply_permutation(array, permutation):
elif dtype.itemsize == 4 and dtype.kind is 'i':
thrust.apply_sort_perm_int(array, tmp, permutation)
else:
print array.dtype
print array.dtype.itemsize
print array.dtype.kind
print(array.dtype)
print(array.dtype.itemsize)
print(array.dtype.kind)
raise TypeError('Currently only float64 and int32 types can be sorted')
return tmp

Expand Down
2 changes: 1 addition & 1 deletion PyHEADTAIL/gpu/particles.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# default classes imports from modules as assigned in gpu/__init__.py
import numpy as np
import thrust_interface as thrust
from . import thrust_interface as thrust
from pycuda import gpuarray

from PyHEADTAIL.gpu.oldinit import def_particles
Expand Down
2 changes: 1 addition & 1 deletion PyHEADTAIL/gpu/slicing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
@authors: Adrian Oeftiger
@date: 30/07/2015
'''
from __future__ import division


import os
where = os.path.dirname(os.path.abspath(__file__)) + '/'
Expand Down
2 changes: 1 addition & 1 deletion PyHEADTAIL/gpu/wrapper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import division


from pycuda.elementwise import ElementwiseKernel
from PyHEADTAIL.trackers import wrapper as def_wrapper
Expand Down
6 changes: 2 additions & 4 deletions PyHEADTAIL/impedances/wake_kicks.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
@copyright CERN
"""

from __future__ import division


import numpy as np
from scipy.constants import c
Expand All @@ -16,7 +16,7 @@
from PyHEADTAIL.general import pmath as pm
from PyHEADTAIL.general.element import Printing

class WakeKick(Printing):
class WakeKick(Printing, metaclass=ABCMeta):
"""Abstract base class for wake kick classes, like e.g. the
DipoleWakeKickX.
Provides the basic and universal methods to calculate the strength
Expand All @@ -30,8 +30,6 @@ class WakeKick(Printing):
the WakeKick class.
"""

__metaclass__ = ABCMeta

def __init__(self, wake_function, slicer, n_turns_wake,
*args, **kwargs):
"""Universal constructor for WakeKick objects. The slicer_mode
Expand Down
11 changes: 5 additions & 6 deletions PyHEADTAIL/impedances/wakes.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
@copyright CERN
"""

from __future__ import division


import numpy as np
from collections import deque
Expand Down Expand Up @@ -69,7 +69,7 @@ def check_wake_sampling(bunch, slicer, wakes, beta=1, wake_column=None, bins=Fal
lgd += ['Bin edges']
ax2.legend(lgd)

print '\n--> Resulting number of slices: {:g}'.format(len(ss))
print('\n--> Resulting number of slices: {:g}'.format(len(ss)))

return ax1

Expand Down Expand Up @@ -132,7 +132,7 @@ def track(self, bunch):
WakeKick instances. """

# Update ages of stored SliceSet instances.
for i in xrange(len(self.slice_set_age_deque)):
for i in range(len(self.slice_set_age_deque)):
self.slice_set_age_deque[i] += (
bunch.circumference / (bunch.beta * c))

Expand All @@ -147,10 +147,9 @@ def track(self, bunch):

''' WakeSource classes. '''

class WakeSource(Printing):
class WakeSource(Printing, metaclass=ABCMeta):
""" Abstract base class for wake sources, such as WakeTable,
Resonator or ResistiveWall. """
__metaclass__ = ABCMeta

@abstractmethod
def get_wake_kicks(self, slicer_mode):
Expand Down Expand Up @@ -287,7 +286,7 @@ def get_wake_kicks(self, slicer):
def _is_provided(self, wake_component):
""" Check whether wake_component is a valid name and available
in wake table data. Return 'True' if yes and 'False' if no. """
if wake_component in self.wake_table.keys():
if wake_component in list(self.wake_table.keys()):
return True
else:
# self.warns(wake_component + ' \n' +
Expand Down
4 changes: 2 additions & 2 deletions PyHEADTAIL/machines/synchrotron.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import division


import numpy as np
from scipy.constants import c
Expand Down Expand Up @@ -268,7 +268,7 @@ def _construct_transverse_map(
self.transverse_map.n_segments = len(s)-1

if name is None:
self.transverse_map.name = ['P_%d' % ip for ip in xrange(len(s)-1)]
self.transverse_map.name = ['P_%d' % ip for ip in range(len(s)-1)]
self.transverse_map.name.append('end_ring')
else:
self.transverse_map.name = name
Expand Down
10 changes: 4 additions & 6 deletions PyHEADTAIL/monitors/monitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@copyright CERN
"""

from __future__ import division


import h5py as hp
import numpy as np
Expand All @@ -22,13 +22,11 @@
# from .. import cobra_functions.stats.calc_cell_stats as calc_cell_stats


class Monitor(Printing):
class Monitor(Printing, metaclass=ABCMeta):
""" Abstract base class for monitors. A monitor can request
statistics data such as mean value and standard deviation and store
the results in an HDF5 file. """

__metaclass__ = ABCMeta

@abstractmethod
def dump(bunch):
""" Write particle data given by bunch (instance of Particles
Expand Down Expand Up @@ -445,7 +443,7 @@ def _write_data_to_file(self, bunch, arrays_dict):
h5file = hp.File(self.filename + '.h5part', 'a')
h5group = h5file.create_group('Step#' + str(self.i_steps))
dims = (bunch.macroparticlenumber // self.stride,)
dims = bunch.get_coords_n_momenta_dict().values()[0][::self.stride].shape # more robust implementation
dims = list(bunch.get_coords_n_momenta_dict().values())[0][::self.stride].shape # more robust implementation

# resorting_indices = np.argsort(bunch.id)[::self.stride]
all_quantities = {}
Expand All @@ -462,7 +460,7 @@ def _write_data_to_file(self, bunch, arrays_dict):
if arrays_dict is not None:
all_quantities.update(arrays_dict)

for quant in all_quantities.keys():
for quant in list(all_quantities.keys()):
quant_values = all_quantities[quant]
h5group.create_dataset(quant, shape=dims, compression='gzip',
compression_opts=9, dtype=quant_values.dtype)
Expand Down
Loading

0 comments on commit c24bf3b

Please sign in to comment.