diff --git a/PyHEADTAIL/__init__.py b/PyHEADTAIL/__init__.py index a7d66ed1..42c14d1b 100644 --- a/PyHEADTAIL/__init__.py +++ b/PyHEADTAIL/__init__.py @@ -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') diff --git a/PyHEADTAIL/aperture/aperture.py b/PyHEADTAIL/aperture/aperture.py index 3e245124..d6584567 100644 --- a/PyHEADTAIL/aperture/aperture.py +++ b/PyHEADTAIL/aperture/aperture.py @@ -10,7 +10,7 @@ Michael Schenk ''' -from __future__ import division + import numpy as np from abc import ABCMeta, abstractmethod @@ -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 diff --git a/PyHEADTAIL/cobra_functions/curve_tools.py b/PyHEADTAIL/cobra_functions/curve_tools.py index 0acbecb6..8ab2f906 100644 --- a/PyHEADTAIL/cobra_functions/curve_tools.py +++ b/PyHEADTAIL/cobra_functions/curve_tools.py @@ -1,4 +1,4 @@ -from __future__ import division + import numpy as np from scipy.optimize import brentq @@ -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) diff --git a/PyHEADTAIL/feedback/transverse_damper.py b/PyHEADTAIL/feedback/transverse_damper.py index 2403a9e9..7ebbd80c 100644 --- a/PyHEADTAIL/feedback/transverse_damper.py +++ b/PyHEADTAIL/feedback/transverse_damper.py @@ -4,7 +4,7 @@ @copyright CERN ''' -from __future__ import division + import numpy as np from scipy.special import k0 diff --git a/PyHEADTAIL/feedback/widebandfeedback.py b/PyHEADTAIL/feedback/widebandfeedback.py index 1a548965..92f7489c 100644 --- a/PyHEADTAIL/feedback/widebandfeedback.py +++ b/PyHEADTAIL/feedback/widebandfeedback.py @@ -4,7 +4,7 @@ @copyright CERN ''' -from __future__ import division + import numpy as np from scipy.special import k0 diff --git a/PyHEADTAIL/field_maps/Transverse_Efield_map.py b/PyHEADTAIL/field_maps/Transverse_Efield_map.py index 6dcf90fd..883bfd7b 100644 --- a/PyHEADTAIL/field_maps/Transverse_Efield_map.py +++ b/PyHEADTAIL/field_maps/Transverse_Efield_map.py @@ -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) diff --git a/PyHEADTAIL/field_maps/field_map.py b/PyHEADTAIL/field_maps/field_map.py index 29a9d45b..7df4a9dc 100644 --- a/PyHEADTAIL/field_maps/field_map.py +++ b/PyHEADTAIL/field_maps/field_map.py @@ -15,7 +15,7 @@ @date: 13.06.2017 ''' -from __future__ import division, print_function + from scipy.constants import c @@ -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): @@ -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) @@ -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!' # @@ -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) diff --git a/PyHEADTAIL/general/decorators.py b/PyHEADTAIL/general/decorators.py index f38c5605..348062a1 100644 --- a/PyHEADTAIL/general/decorators.py +++ b/PyHEADTAIL/general/decorators.py @@ -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 @@ -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 diff --git a/PyHEADTAIL/general/element.py b/PyHEADTAIL/general/element.py index 348fc846..a9e277bf 100644 --- a/PyHEADTAIL/general/element.py +++ b/PyHEADTAIL/general/element.py @@ -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): diff --git a/PyHEADTAIL/general/pmath.py b/PyHEADTAIL/general/pmath.py index 9fa9a080..66cd4277 100644 --- a/PyHEADTAIL/general/pmath.py +++ b/PyHEADTAIL/general/pmath.py @@ -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) diff --git a/PyHEADTAIL/general/printers.py b/PyHEADTAIL/general/printers.py index 4406a385..9c942be9 100644 --- a/PyHEADTAIL/general/printers.py +++ b/PyHEADTAIL/general/printers.py @@ -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 @@ -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): diff --git a/PyHEADTAIL/gpu/gpu_utils.py b/PyHEADTAIL/gpu/gpu_utils.py index f5a40ca7..3e777599 100644 --- a/PyHEADTAIL/gpu/gpu_utils.py +++ b/PyHEADTAIL/gpu/gpu_utils.py @@ -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): diff --git a/PyHEADTAIL/gpu/gpu_wrap.py b/PyHEADTAIL/gpu/gpu_wrap.py index 7bd17527..d1dbc165 100644 --- a/PyHEADTAIL/gpu/gpu_wrap.py +++ b/PyHEADTAIL/gpu/gpu_wrap.py @@ -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: @@ -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): @@ -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 @@ -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 diff --git a/PyHEADTAIL/gpu/particles.py b/PyHEADTAIL/gpu/particles.py index 2c1a1720..761ed010 100644 --- a/PyHEADTAIL/gpu/particles.py +++ b/PyHEADTAIL/gpu/particles.py @@ -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 diff --git a/PyHEADTAIL/gpu/slicing.py b/PyHEADTAIL/gpu/slicing.py index 312a66bb..bad257ac 100644 --- a/PyHEADTAIL/gpu/slicing.py +++ b/PyHEADTAIL/gpu/slicing.py @@ -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__)) + '/' diff --git a/PyHEADTAIL/gpu/wrapper.py b/PyHEADTAIL/gpu/wrapper.py index c86c1c24..7ea566c1 100644 --- a/PyHEADTAIL/gpu/wrapper.py +++ b/PyHEADTAIL/gpu/wrapper.py @@ -1,4 +1,4 @@ -from __future__ import division + from pycuda.elementwise import ElementwiseKernel from PyHEADTAIL.trackers import wrapper as def_wrapper diff --git a/PyHEADTAIL/impedances/wake_kicks.py b/PyHEADTAIL/impedances/wake_kicks.py index c8a8fae3..729761d1 100644 --- a/PyHEADTAIL/impedances/wake_kicks.py +++ b/PyHEADTAIL/impedances/wake_kicks.py @@ -7,7 +7,7 @@ @copyright CERN """ -from __future__ import division + import numpy as np from scipy.constants import c @@ -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 @@ -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 diff --git a/PyHEADTAIL/impedances/wakes.py b/PyHEADTAIL/impedances/wakes.py index 377064e9..15dea93a 100644 --- a/PyHEADTAIL/impedances/wakes.py +++ b/PyHEADTAIL/impedances/wakes.py @@ -20,7 +20,7 @@ @copyright CERN """ -from __future__ import division + import numpy as np from collections import deque @@ -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 @@ -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)) @@ -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): @@ -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' + diff --git a/PyHEADTAIL/machines/synchrotron.py b/PyHEADTAIL/machines/synchrotron.py index e20d7875..fb996366 100644 --- a/PyHEADTAIL/machines/synchrotron.py +++ b/PyHEADTAIL/machines/synchrotron.py @@ -1,4 +1,4 @@ -from __future__ import division + import numpy as np from scipy.constants import c @@ -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 diff --git a/PyHEADTAIL/monitors/monitors.py b/PyHEADTAIL/monitors/monitors.py index 5ccae79c..b703a860 100644 --- a/PyHEADTAIL/monitors/monitors.py +++ b/PyHEADTAIL/monitors/monitors.py @@ -6,7 +6,7 @@ @copyright CERN """ -from __future__ import division + import h5py as hp import numpy as np @@ -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 @@ -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 = {} @@ -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) diff --git a/PyHEADTAIL/multipoles/multipoles.py b/PyHEADTAIL/multipoles/multipoles.py index 014de196..6eac3064 100644 --- a/PyHEADTAIL/multipoles/multipoles.py +++ b/PyHEADTAIL/multipoles/multipoles.py @@ -111,7 +111,7 @@ def ctaylor(x, y, kn, ks): '''Efficient Horner scheme.''' dpx = kn[-1] dpy = ks[-1] - nn = range(1, len(kn) + 1) + nn = list(range(1, len(kn) + 1)) for n, kkn, kks in list(zip(nn, kn, ks))[-2::-1]: dpxi = (dpx*x - dpy*y) / float(n) dpyi = (dpx*y + dpy*x) / float(n) diff --git a/PyHEADTAIL/particles/generators.py b/PyHEADTAIL/particles/generators.py index ff910142..1b3dd5be 100644 --- a/PyHEADTAIL/particles/generators.py +++ b/PyHEADTAIL/particles/generators.py @@ -4,7 +4,7 @@ @brief module for generating & matching particle distributions ''' -from __future__ import division + import numpy as np from scipy.constants import e, c @@ -149,9 +149,9 @@ def _transverse_linear_matcher(beam, direction): try: space_coords += dispersion * getattr(beam, 'dp') except KeyError: - print ('Dispersion in the transverse phase space depends on' + + print(('Dispersion in the transverse phase space depends on' + 'dp, however no longitudinal phase space was specified. '+ - 'No matching performed') + 'No matching performed')) setattr(beam, direction[0], space_coords) setattr(beam, direction[1], momentum_coords) diff --git a/PyHEADTAIL/particles/particles.py b/PyHEADTAIL/particles/particles.py index 48139fb2..fcf5e6b3 100644 --- a/PyHEADTAIL/particles/particles.py +++ b/PyHEADTAIL/particles/particles.py @@ -174,7 +174,7 @@ def extract_slices(self, slicer, include_non_sliced='if_any', *args, **kwargs): self_coords_n_momenta_dict = self.get_coords_n_momenta_dict() slice_object_list = [] - for i_sl in xrange(slices.n_slices): + for i_sl in range(slices.n_slices): ix = slices.particle_indices_of_slice(i_sl) macroparticlenumber = len(ix) @@ -183,7 +183,7 @@ def extract_slices(self, slicer, include_non_sliced='if_any', *args, **kwargs): particlenumber_per_mp=self.particlenumber_per_mp, charge=self.charge, mass=self.mass, circumference=self.circumference, gamma=self.gamma, coords_n_momenta_dict={}) - for coord in self_coords_n_momenta_dict.keys(): + for coord in list(self_coords_n_momenta_dict.keys()): slice_object.update({coord: self_coords_n_momenta_dict[coord][ix]}) slice_object.id[:] = self.id[ix] @@ -202,7 +202,7 @@ def extract_slices(self, slicer, include_non_sliced='if_any', *args, **kwargs): slice_object = Particles(macroparticlenumber=len(ix), particlenumber_per_mp=self.particlenumber_per_mp, charge=self.charge, mass=self.mass, circumference=self.circumference, gamma=self.gamma, coords_n_momenta_dict={}) - for coord in self_coords_n_momenta_dict.keys(): + for coord in list(self_coords_n_momenta_dict.keys()): slice_object.update({coord: self_coords_n_momenta_dict[coord][ix]}) slice_object.id[:] = self.id[ix] slice_object.slice_info = 'unsliced' @@ -224,12 +224,12 @@ def update(self, coords_n_momenta_dict): Attention: overwrites existing coordinate / momentum attributes. ''' if any(len(v) != self.macroparticlenumber for v in - coords_n_momenta_dict.values()): + list(coords_n_momenta_dict.values())): raise ValueError("lengths of given phase space coordinate arrays" + " do not coincide with self.macroparticlenumber.") - for coord, array in coords_n_momenta_dict.items(): + for coord, array in list(coords_n_momenta_dict.items()): setattr(self, coord, array.copy()) - self.coords_n_momenta.update(coords_n_momenta_dict.keys()) + self.coords_n_momenta.update(list(coords_n_momenta_dict.keys())) def add(self, coords_n_momenta_dict): '''Add the coordinates and momenta with their according arrays @@ -238,7 +238,7 @@ def add(self, coords_n_momenta_dict): coordinate or momentum attributes to be overwritten. ''' if any(s in self.coords_n_momenta - for s in coords_n_momenta_dict.keys()): + for s in list(coords_n_momenta_dict.keys())): raise ValueError("One or more of the specified coordinates or" + " momenta already exist and cannot be added." + " Use self.update(...) for this purpose.") @@ -277,7 +277,7 @@ def __add__(self, other): mass=self.mass, circumference=self.circumference, gamma=self.gamma, coords_n_momenta_dict={}) - for coord in self_coords_n_momenta_dict.keys(): + for coord in list(self_coords_n_momenta_dict.keys()): #setattr(result, coord, np.concatenate((self_coords_n_momenta_dict[coord].copy(), other_coords_n_momenta_dict[coord].copy()))) result.update({coord: np.concatenate((self_coords_n_momenta_dict[coord].copy(), other_coords_n_momenta_dict[coord].copy()))}) @@ -292,7 +292,7 @@ def __radd__(self, other): particlenumber_per_mp=self.particlenumber_per_mp, charge=self.charge, mass=self.mass, circumference=self.circumference, gamma=self.gamma, coords_n_momenta_dict={}) - for coord in self_coords_n_momenta_dict.keys(): + for coord in list(self_coords_n_momenta_dict.keys()): #setattr(result, coord, np.concatenate((self_coords_n_momenta_dict[coord].copy(), other_coords_n_momenta_dict[coord].copy()))) result.update({coord: self_coords_n_momenta_dict[coord].copy()}) result.id = self.id.copy() diff --git a/PyHEADTAIL/particles/rfbucket_matching.py b/PyHEADTAIL/particles/rfbucket_matching.py index 12ec5b61..559c9ee8 100644 --- a/PyHEADTAIL/particles/rfbucket_matching.py +++ b/PyHEADTAIL/particles/rfbucket_matching.py @@ -4,7 +4,7 @@ @brief module for matching longitudinal particle distributions to an RFBucket instance ''' -from __future__ import division, print_function + import numpy as np from scipy.optimize import brentq, newton diff --git a/PyHEADTAIL/particles/slicing.py b/PyHEADTAIL/particles/slicing.py index 439af6b2..d36f131f 100644 --- a/PyHEADTAIL/particles/slicing.py +++ b/PyHEADTAIL/particles/slicing.py @@ -9,7 +9,7 @@ @copyright CERN ''' -from __future__ import division + from abc import ABCMeta, abstractmethod import numpy as np @@ -105,7 +105,7 @@ def __init__(self, z_bins, slice_index_of_particle, mode, self._pidx_begin = None self._pidx_end = None - for p_name, p_value in beam_parameters.iteritems(): + for p_name, p_value in beam_parameters.items(): if hasattr(self, p_name): raise ValueError('SliceSet.' + p_name + ' already exists!' + 'Do not overwrite existing SliceSet ' + @@ -317,11 +317,10 @@ def convert_to_particles(self, slice_array, empty_particles=None): return pm.slice_to_particles(self, slice_array, empty_particles) -class Slicer(Printing): +class Slicer(Printing, metaclass=ABCMeta): '''Slicer class that controls longitudinal binning of a beam. Factory for SliceSet objects. ''' - __metaclass__ = ABCMeta @property def config(self): @@ -654,7 +653,7 @@ def compute_sliceset_kwargs(self, beam): # slices. Must be integer. Distribute remaining particles randomly # among slices with indices 'rand_slice_i'. n_part_within_cuts = n_part - n_cut_tail - n_cut_head - rand_slice_i = sample(range(self.n_slices), + rand_slice_i = sample(list(range(self.n_slices)), n_part_within_cuts % self.n_slices) n_part_per_slice = ((n_part_within_cuts // self.n_slices) @@ -673,7 +672,7 @@ def compute_sliceset_kwargs(self, beam): z_bins[0], z_bins[-1] = z_cut_tail, z_cut_head slice_index_of_particle_sorted = -np.ones(n_part, dtype=np.int32) - for i in xrange(self.n_slices): + for i in range(self.n_slices): start, end = first_indices[i], first_indices[i+1] slice_index_of_particle_sorted[start:end] = i diff --git a/PyHEADTAIL/radiation/radiation.py b/PyHEADTAIL/radiation/radiation.py index 754eae37..74395527 100644 --- a/PyHEADTAIL/radiation/radiation.py +++ b/PyHEADTAIL/radiation/radiation.py @@ -5,7 +5,7 @@ @copyright CERN """ -from __future__ import division + import numpy as np from scipy.constants import c diff --git a/PyHEADTAIL/rfq/rfq.py b/PyHEADTAIL/rfq/rfq.py index 7bb14c90..592e3a81 100644 --- a/PyHEADTAIL/rfq/rfq.py +++ b/PyHEADTAIL/rfq/rfq.py @@ -32,7 +32,7 @@ @copyright CERN """ -from __future__ import division + from abc import ABCMeta, abstractmethod from scipy.constants import c, e @@ -131,12 +131,11 @@ def detune(self, beam): return dQ_x, dQ_y -class RFQKick(object): +class RFQKick(object, metaclass=ABCMeta): """Python base class to describe the RFQ element in the localized kick model for both the transverse and the longitudinal coordinates. """ - __metaclass__ = ABCMeta @abstractmethod def track(self, beam): diff --git a/PyHEADTAIL/spacecharge/pypic_factory.py b/PyHEADTAIL/spacecharge/pypic_factory.py index 40f207e5..e799d1f9 100644 --- a/PyHEADTAIL/spacecharge/pypic_factory.py +++ b/PyHEADTAIL/spacecharge/pypic_factory.py @@ -9,7 +9,7 @@ @date: 18.01.2016 ''' -from __future__ import division + import numpy as np @@ -105,9 +105,9 @@ def create_mesh(mesh_origin, mesh_distances, mesh_size, raise ValueError('All arguments for the mesh need to have as ' 'many entries as the mesh should have dimensions!') mesh_class = getattr(meshing, 'RectMesh{dim}D'.format(dim=dim)) - return mesh_class(map(ensure_cpu, mesh_origin), - map(ensure_cpu, mesh_distances), - map(ensure_cpu, mesh_size), + return mesh_class(list(map(ensure_cpu, mesh_origin)), + list(map(ensure_cpu, mesh_distances)), + list(map(ensure_cpu, mesh_size)), mathlib=pm) diff --git a/PyHEADTAIL/spacecharge/pypic_spacecharge.py b/PyHEADTAIL/spacecharge/pypic_spacecharge.py index 95539992..1b1205c2 100644 --- a/PyHEADTAIL/spacecharge/pypic_spacecharge.py +++ b/PyHEADTAIL/spacecharge/pypic_spacecharge.py @@ -9,7 +9,7 @@ @date: 18.01.2016 ''' -from __future__ import division, print_function + import numpy as np from scipy.constants import c @@ -429,11 +429,11 @@ def __init__(self, slicer, length, beam=None, sigma_x=None, sigma_y=None, # calculate Bassetti-Erskine formula on either CPU or GPU: ## prepare arguments for the proper device: - xg, yg = map(pm.ensure_same_device, np.meshgrid( + xg, yg = list(map(pm.ensure_same_device, np.meshgrid( np.linspace(mesh.x0, mesh.x0 + mesh.dx*mesh.nx, mesh.nx), np.linspace(mesh.y0, mesh.y0 + mesh.dy*mesh.ny, mesh.ny) - )) - sigma_x, sigma_y = map(pm.ensure_same_device, [sigma_x, sigma_y]) + ))) + sigma_x, sigma_y = list(map(pm.ensure_same_device, [sigma_x, sigma_y])) ## compute fields be_sc = TransverseGaussianSpaceCharge(None, None) fields_beamframe = be_sc.get_efieldn(xg, yg, 0, 0, sigma_x, sigma_y) diff --git a/PyHEADTAIL/spacecharge/spacecharge.py b/PyHEADTAIL/spacecharge/spacecharge.py index a6fadb82..7a68e618 100644 --- a/PyHEADTAIL/spacecharge/spacecharge.py +++ b/PyHEADTAIL/spacecharge/spacecharge.py @@ -3,7 +3,7 @@ @date: 17/04/2015 ''' -from __future__ import division + import numpy as np from scipy.constants import c, epsilon_0, pi diff --git a/PyHEADTAIL/spacecharge/transverse_spacecharge.py b/PyHEADTAIL/spacecharge/transverse_spacecharge.py index 702e1a54..4d8dc630 100644 --- a/PyHEADTAIL/spacecharge/transverse_spacecharge.py +++ b/PyHEADTAIL/spacecharge/transverse_spacecharge.py @@ -1,4 +1,4 @@ -from __future__ import division + import numpy as np from scipy.constants import c @@ -42,7 +42,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) diff --git a/PyHEADTAIL/testing/development/tracking_model.py b/PyHEADTAIL/testing/development/tracking_model.py index a7d36263..d217a0c4 100644 --- a/PyHEADTAIL/testing/development/tracking_model.py +++ b/PyHEADTAIL/testing/development/tracking_model.py @@ -5,11 +5,10 @@ from PyHEADTAIL.general.utils import ListProxy -class KineticElement(object): +class KineticElement(object, metaclass=ABCMeta): """Documentation for KineticElement """ - __metaclass__ = ABCMeta def __init__(self, gamma, mass): self.gamma = gamma @@ -53,11 +52,10 @@ def p0(self, value): np.sqrt(value**2+self.mass**2*c**2)) -class TrackingElement(object): +class TrackingElement(object, metaclass=ABCMeta): """Documentation for TrackingElement """ - __metaclass__ = ABCMeta def __init__(self, args): super(TrackingElement, self).__init__() @@ -68,11 +66,10 @@ def track(self, arg): pass -class Detuner(object): +class Detuner(object, metaclass=ABCMeta): """Documentation for Detuner """ - __metaclass__ = ABCMeta def __init__(self, args): super(Detuner, self).__init__() diff --git a/PyHEADTAIL/testing/script-tests/CLIC_DR.py b/PyHEADTAIL/testing/script-tests/CLIC_DR.py index 9ddf4ca7..c2a41434 100644 --- a/PyHEADTAIL/testing/script-tests/CLIC_DR.py +++ b/PyHEADTAIL/testing/script-tests/CLIC_DR.py @@ -36,7 +36,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(): 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"') n_segments = kwargs['n_segments'] circumference = 427.5 @@ -54,7 +54,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): s = None elif 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"') n_segments = None circumference = None @@ -90,7 +90,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): 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/PyHEADTAIL/testing/script-tests/LHC.py b/PyHEADTAIL/testing/script-tests/LHC.py index 433ca33f..063223f0 100644 --- a/PyHEADTAIL/testing/script-tests/LHC.py +++ b/PyHEADTAIL/testing/script-tests/LHC.py @@ -42,7 +42,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'] @@ -61,7 +61,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 @@ -100,7 +100,7 @@ def __init__(self, machine_configuration=None, optics_mode='smooth', **kwargs): pp.i_octupole_defocusing = None pp.octupole_knob = None - 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/PyHEADTAIL/testing/script-tests/test_radiation_damping_time_and_equilibrum_values.py b/PyHEADTAIL/testing/script-tests/test_radiation_damping_time_and_equilibrum_values.py index 3d75374d..a74ba1df 100644 --- a/PyHEADTAIL/testing/script-tests/test_radiation_damping_time_and_equilibrum_values.py +++ b/PyHEADTAIL/testing/script-tests/test_radiation_damping_time_and_equilibrum_values.py @@ -57,8 +57,8 @@ mean_dp = [] sx, sy, sz, sdp = [], [], [], [] epsx, epsy, epsz = [], [], [] -for i_turn in xrange(n_turns): - print 'Turn %d/%d'%(i_turn, n_turns) +for i_turn in range(n_turns): + print('Turn %d/%d'%(i_turn, n_turns)) machine.track(bunch) beam_x.append(bunch.mean_x()) diff --git a/PyHEADTAIL/testing/script-tests/test_radiation_energy_loss.py b/PyHEADTAIL/testing/script-tests/test_radiation_energy_loss.py index 070b9563..5d788a53 100644 --- a/PyHEADTAIL/testing/script-tests/test_radiation_energy_loss.py +++ b/PyHEADTAIL/testing/script-tests/test_radiation_energy_loss.py @@ -41,6 +41,6 @@ SynchrotronRadiationLongitudinal.track(bunch) dp_after = bunch.mean_dp() -print 'Energy loss\nEvaluated :%.6e [eV]\nExpected :%.6e [eV]\nERROR :%.2f'%((dp_before-dp_after)*machine.p0*c/np.abs(machine.charge), - E_loss_eV,(E_loss_eV-((dp_before-dp_after)*machine.p0*c/np.abs(machine.charge)))*100/E_loss_eV)+'%' +print('Energy loss\nEvaluated :%.6e [eV]\nExpected :%.6e [eV]\nERROR :%.2f'%((dp_before-dp_after)*machine.p0*c/np.abs(machine.charge), + E_loss_eV,(E_loss_eV-((dp_before-dp_after)*machine.p0*c/np.abs(machine.charge)))*100/E_loss_eV)+'%') diff --git a/PyHEADTAIL/testing/script-tests/test_radiation_with_non_linear_bucket.py b/PyHEADTAIL/testing/script-tests/test_radiation_with_non_linear_bucket.py index 98cf3214..9d8359b6 100644 --- a/PyHEADTAIL/testing/script-tests/test_radiation_with_non_linear_bucket.py +++ b/PyHEADTAIL/testing/script-tests/test_radiation_with_non_linear_bucket.py @@ -1,4 +1,4 @@ -from __future__ import division + import matplotlib.pyplot as plt import numpy as np @@ -29,7 +29,7 @@ # =========================== phi_s = np.arcsin(E_loss_eV/machine.longitudinal_map.voltages[0]) z_s = (machine.circumference)*phi_s/(2*np.pi*machine.longitudinal_map.harmonics[0]) -print z_s +print(z_s) # BEAM # ==== @@ -58,7 +58,7 @@ plt.close() plt.ion() -print '--> Begin tracking...' +print('--> Begin tracking...') fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2, 2, figsize=(14,10)) @@ -79,7 +79,7 @@ for i in range(n_turns): machine.track(bunch) - print 'Turn %d/%d'%(i, n_turns) + print('Turn %d/%d'%(i, n_turns)) sigma_x[i] = bunch.sigma_x() mean_x[i] = bunch.mean_x() epsn_x[i] = bunch.epsn_x() @@ -156,5 +156,5 @@ #print 'sigma_dp = ',sigma_dp #print 'sigma_z = ',sigma_z -print '--> Done.' +print('--> Done.') diff --git a/PyHEADTAIL/testing/script-tests/test_synchrotron_LHC.py b/PyHEADTAIL/testing/script-tests/test_synchrotron_LHC.py index 620f2e48..065c928b 100644 --- a/PyHEADTAIL/testing/script-tests/test_synchrotron_LHC.py +++ b/PyHEADTAIL/testing/script-tests/test_synchrotron_LHC.py @@ -27,10 +27,10 @@ machine = LHC(machine_configuration='Injection', optics_mode = 'non-smooth', V_RF=10e6, **optics) -print 'Create bunch for optics...' +print('Create bunch for optics...') bunch = machine.generate_6D_Gaussian_bunch_matched( macroparticlenumber_optics, intensity, epsn_x, epsn_y, sigma_z=sigma_z) -print 'Done.' +print('Done.') bunch.x += 10. bunch.y += 20. @@ -44,7 +44,7 @@ beam_alpha_y = [] beam_beta_y = [] for i_ele, m in enumerate(machine.one_turn_map): - print 'Element %d/%d'%(i_ele, len(machine.one_turn_map)) + print('Element %d/%d'%(i_ele, len(machine.one_turn_map))) beam_alpha_x.append(bunch.alpha_Twiss_x()) beam_beta_x.append(bunch.beta_Twiss_x()) beam_alpha_y.append(bunch.alpha_Twiss_y()) @@ -91,8 +91,8 @@ beam_z = [] sx, sy, sz = [], [], [] epsx, epsy, epsz = [], [], [] -for i_turn in xrange(n_turns): - print 'Turn %d/%d'%(i_turn, n_turns) +for i_turn in range(n_turns): + print('Turn %d/%d'%(i_turn, n_turns)) machine.track(bunch) beam_x.append(bunch.mean_x()) @@ -160,16 +160,16 @@ #~ plt.plot(optics['s'][:],optics['beta_x'][:], '-o') LHC_with_octupole_injection = LHC(machine_configuration='Injection', n_segments=5, octupole_knob = -1.5) -print '450GeV:' -print 'i_octupole_focusing =',LHC_with_octupole_injection.i_octupole_focusing -print 'i_octupole_defocusing =',LHC_with_octupole_injection.i_octupole_defocusing -print 'in the machine we get 19.557' -print ' ' +print('450GeV:') +print('i_octupole_focusing =',LHC_with_octupole_injection.i_octupole_focusing) +print('i_octupole_defocusing =',LHC_with_octupole_injection.i_octupole_defocusing) +print('in the machine we get 19.557') +print(' ') LHC_with_octupole_flattop = LHC(machine_configuration='Injection', n_segments=5, p0=6.5e12*e/c, octupole_knob = -2.9) -print '6.5TeV:' -print 'i_octupole_focusing =',LHC_with_octupole_flattop.i_octupole_focusing -print 'i_octupole_defocusing =',LHC_with_octupole_flattop.i_octupole_defocusing -print 'in the machine we get 546.146' +print('6.5TeV:') +print('i_octupole_focusing =',LHC_with_octupole_flattop.i_octupole_focusing) +print('i_octupole_defocusing =',LHC_with_octupole_flattop.i_octupole_defocusing) +print('in the machine we get 546.146') plt.show() diff --git a/PyHEADTAIL/testing/script-tests/test_synchrotron_electrons_CLIC_DR.py b/PyHEADTAIL/testing/script-tests/test_synchrotron_electrons_CLIC_DR.py index fc86203e..385ba413 100644 --- a/PyHEADTAIL/testing/script-tests/test_synchrotron_electrons_CLIC_DR.py +++ b/PyHEADTAIL/testing/script-tests/test_synchrotron_electrons_CLIC_DR.py @@ -19,10 +19,10 @@ machine = CLIC_DR(machine_configuration='3TeV', n_segments=29, charge=-e) -print 'Create bunch for optics...' +print('Create bunch for optics...') bunch = machine.generate_6D_Gaussian_bunch_matched( macroparticlenumber_optics, intensity, epsn_x, epsn_y, sigma_z=sigma_z) -print 'Done.' +print('Done.') bunch.x += 10. bunch.y += 20. @@ -36,7 +36,7 @@ beam_alpha_y = [] beam_beta_y = [] for i_ele, m in enumerate(machine.one_turn_map): - print 'Element %d/%d'%(i_ele, len(machine.one_turn_map)) + print('Element %d/%d'%(i_ele, len(machine.one_turn_map))) beam_alpha_x.append(bunch.alpha_Twiss_x()) beam_beta_x.append(bunch.beta_Twiss_x()) beam_alpha_y.append(bunch.alpha_Twiss_y()) @@ -83,8 +83,8 @@ beam_z = [] sx, sy, sz = [], [], [] epsx, epsy, epsz = [], [], [] -for i_turn in xrange(n_turns): - print 'Turn %d/%d'%(i_turn, n_turns) +for i_turn in range(n_turns): + print('Turn %d/%d'%(i_turn, n_turns)) machine.track(bunch) beam_x.append(bunch.mean_x()) diff --git a/PyHEADTAIL/testing/unittests/PyCERNmachines/CERNmachines.py b/PyHEADTAIL/testing/unittests/PyCERNmachines/CERNmachines.py index 5bef0e04..527dfd68 100644 --- a/PyHEADTAIL/testing/unittests/PyCERNmachines/CERNmachines.py +++ b/PyHEADTAIL/testing/unittests/PyCERNmachines/CERNmachines.py @@ -1,20 +1,20 @@ -from __future__ import division + import numpy as np from scipy.constants import c, e, m_p -from machines import Synchrotron -from SPS import SPSOctupoles +from .machines import Synchrotron +from .SPS import SPSOctupoles class PSB(Synchrotron): def __init__(self, *args, **kwargs): - if 'n_segments' not in kwargs.keys(): + if 'n_segments' not in list(kwargs.keys()): raise ValueError('Number of segments must be specified') - if 'machine_configuration' not in kwargs.keys(): + if 'machine_configuration' not in list(kwargs.keys()): raise ValueError('machine_configuration must be specified') self.n_segments = kwargs['n_segments'] @@ -201,10 +201,10 @@ class SPS(Synchrotron): def __init__(self, *args, **kwargs): - if 'n_segments' not in kwargs.keys(): + if 'n_segments' not in list(kwargs.keys()): raise ValueError('Number of segments must be specified') - if 'machine_configuration' not in kwargs.keys(): + if 'machine_configuration' not in list(kwargs.keys()): raise ValueError('machine_configuration must be specified') if 'octupole_settings_dict' not in kwargs: @@ -325,13 +325,13 @@ def __init__(self, *args, **kwargs): self.machine_configuration) for k in ['app_x', 'app_y', 'app_xy']: - if k in kwargs.keys(): + if k in list(kwargs.keys()): kwargs[k] += getattr(self, k) super(SPS, self).__init__(*args, **kwargs) def add_effect_of_octupoles(self, kwargs, optics): - if 'octupole_settings_dict' in kwargs.keys(): + if 'octupole_settings_dict' in list(kwargs.keys()): octupoles = SPSOctupoles.SPSOctupoles(optics) KLOF = kwargs['octupole_settings_dict']['KLOF'] KLOD = kwargs['octupole_settings_dict']['KLOD'] @@ -342,10 +342,10 @@ class LHC(Synchrotron): def __init__(self, *args, **kwargs): - if 'n_segments' not in kwargs.keys(): + if 'n_segments' not in list(kwargs.keys()): raise ValueError('Number of segments must be specified') - if 'machine_configuration' not in kwargs.keys(): + if 'machine_configuration' not in list(kwargs.keys()): raise ValueError('machine_configuration must be specified') self.n_segments = kwargs['n_segments'] @@ -465,7 +465,7 @@ def __init__(self, *args, **kwargs): i_focusing = kwargs.pop('i_focusing', False) i_defocusing = kwargs.pop('i_defocusing', False) if i_focusing or i_defocusing is True: - print ('\n--> Powering LHC octupoles to {:g} A.\n'.format(i_focusing)) + print(('\n--> Powering LHC octupoles to {:g} A.\n'.format(i_focusing))) self.app_x, self.app_y, self.app_xy = self.get_anharmonicities_from_octupole_currents_LHC( i_focusing, i_defocusing) @@ -519,10 +519,10 @@ class HLLHC(Synchrotron): def __init__(self, *args, **kwargs): - if 'n_segments' not in kwargs.keys(): + if 'n_segments' not in list(kwargs.keys()): raise ValueError('Number of segments must be specified') - if 'machine_configuration' not in kwargs.keys(): + if 'machine_configuration' not in list(kwargs.keys()): raise ValueError('machine_configuration must be specified') self.n_segments = kwargs['n_segments'] @@ -573,7 +573,7 @@ def __init__(self, *args, **kwargs): i_focusing = kwargs.pop('i_focusing', False) i_defocusing = kwargs.pop('i_defocusing', False) if i_focusing or i_defocusing is True: - print ('\n--> Powering LHC octupoles to {:g} A.\n'.format(i_focusing)) + print(('\n--> Powering LHC octupoles to {:g} A.\n'.format(i_focusing))) self.app_x, self.app_y, self.app_xy = self.get_anharmonicities_from_octupole_currents_LHC( i_focusing, i_defocusing) diff --git a/PyHEADTAIL/testing/unittests/PyCERNmachines/machines.py b/PyHEADTAIL/testing/unittests/PyCERNmachines/machines.py index f8965594..1ede881b 100644 --- a/PyHEADTAIL/testing/unittests/PyCERNmachines/machines.py +++ b/PyHEADTAIL/testing/unittests/PyCERNmachines/machines.py @@ -1,4 +1,4 @@ -from __future__ import division + import numpy as np from scipy.constants import c, e, m_p @@ -38,7 +38,7 @@ def __init__(self, *args, **kwargs): if self.longitudinal_focusing not in ['linear', 'non-linear']: raise ValueError('longitudinal_focusing not recognized!!!') - for attr in kwargs.keys(): + for attr in list(kwargs.keys()): if kwargs[attr] is not None: self.prints('Synchrotron init. From kwargs: %s = %s' % (attr, repr(kwargs[attr]))) diff --git a/PyHEADTAIL/testing/unittests/autoruntests/MonitorTest.py b/PyHEADTAIL/testing/unittests/autoruntests/MonitorTest.py index c0a5622c..1dcec83b 100644 --- a/PyHEADTAIL/testing/unittests/autoruntests/MonitorTest.py +++ b/PyHEADTAIL/testing/unittests/autoruntests/MonitorTest.py @@ -23,7 +23,7 @@ def read_all_data(bfile, sfile, pfile): n_turns = len(bdata['mean_x']) _ = np.empty(n_turns) - for key in bdata.keys(): + for key in list(bdata.keys()): _[:] = bdata[key][:] # Slicedata @@ -32,23 +32,23 @@ def read_all_data(bfile, sfile, pfile): n_turns = len(sbdata['mean_x']) _ = np.empty(n_turns) - for key in sbdata.keys(): + for key in list(sbdata.keys()): _[:] = sbdata[key][:] n_slices, n_turns = sdata['mean_x'].shape _ = np.empty((n_slices, n_turns)) - for key in sdata.keys(): + for key in list(sdata.keys()): _[:,:] = sdata[key][:,:] # Particledata pdata = particledata['Step#0'] n_particles = len(pdata['x']) - n_steps = len(particledata.keys()) + n_steps = len(list(particledata.keys())) _ = np.empty(n_particles) - for i in xrange(n_steps): + for i in range(n_steps): step = 'Step#%d' % i - for key in particledata[step].keys(): + for key in list(particledata[step].keys()): _[:] = particledata[step][key][:] bunchdata.close() @@ -163,7 +163,7 @@ def generate_bunch(n_macroparticles, alpha_x, alpha_y, beta_x, beta_y, alpha_0, arrays_dict = {} map_ = trans_map - for i in xrange(n_turns): + for i in range(n_turns): for m_ in map_: m_.track(bunch) bunch_monitor.dump(bunch) diff --git a/PyHEADTAIL/testing/unittests/autoruntests/SlicingTest.py b/PyHEADTAIL/testing/unittests/autoruntests/SlicingTest.py index 98b6743d..07e9da7a 100644 --- a/PyHEADTAIL/testing/unittests/autoruntests/SlicingTest.py +++ b/PyHEADTAIL/testing/unittests/autoruntests/SlicingTest.py @@ -16,7 +16,7 @@ def test_particle_indices_of_slice(bunch, slice_set): if everything works correctly. ''' all_pass = True - for i in xrange(slice_set.n_slices): + for i in range(slice_set.n_slices): pix_slice = slice_set.particle_indices_of_slice(i) six_pix = slice_set.slice_index_of_particle[pix_slice] if (six_pix != i).any(): @@ -235,7 +235,7 @@ def clean_bunch(bunch): beam_parameters = slicer.extract_beam_parameters(bunch) - for p_name, p_value in beam_parameters.iteritems(): + for p_name, p_value in beam_parameters.items(): pass # In[14]: diff --git a/PyHEADTAIL/testing/unittests/autoruntests/TransverseTrackingTest.py b/PyHEADTAIL/testing/unittests/autoruntests/TransverseTrackingTest.py index 1e47ee9f..1d892a77 100644 --- a/PyHEADTAIL/testing/unittests/autoruntests/TransverseTrackingTest.py +++ b/PyHEADTAIL/testing/unittests/autoruntests/TransverseTrackingTest.py @@ -19,7 +19,7 @@ def track_n_save(bunch, map_): mean_y = np.empty(n_turns) sigma_z = np.empty(n_turns) - for i in xrange(n_turns): + for i in range(n_turns): mean_x[i] = bunch.mean_x() mean_y[i] = bunch.mean_y() sigma_z[i] = bunch.sigma_z() @@ -241,7 +241,7 @@ def gimme(D_x=None, D_y=None, *args, **kwargs): x_i_wD = np.zeros((n_segments*n_turns, n_macroparticles)) y_i_wD = np.zeros((n_segments*n_turns, n_macroparticles)) - for j in xrange(n_segments*n_turns): + for j in range(n_segments*n_turns): x_i_wD[j,:] = bunch_wD.x y_i_wD[j,:] = bunch_wD.y trans_map_wD[j%n_segments].track(bunch_wD) @@ -253,7 +253,7 @@ def gimme(D_x=None, D_y=None, *args, **kwargs): x_i_woD = np.zeros((n_segments*n_turns, n_macroparticles)) y_i_woD = np.zeros((n_segments*n_turns, n_macroparticles)) dp_i_woD = np.zeros((n_segments*n_turns, n_macroparticles)) - for j in xrange(n_segments*n_turns): + for j in range(n_segments*n_turns): x_i_woD[j,:] = bunch_woD.x y_i_woD[j,:] = bunch_woD.y dp_i_woD[j,:] = bunch_woD.dp diff --git a/PyHEADTAIL/testing/unittests/autoruntests/WakeTest.py b/PyHEADTAIL/testing/unittests/autoruntests/WakeTest.py index 7c6eb330..926bc896 100644 --- a/PyHEADTAIL/testing/unittests/autoruntests/WakeTest.py +++ b/PyHEADTAIL/testing/unittests/autoruntests/WakeTest.py @@ -26,7 +26,7 @@ def track_n_save(bunch, map_): mean_y = np.empty(n_turns) sigma_z = np.empty(n_turns) - for i in xrange(n_turns): + for i in range(n_turns): mean_x[i] = bunch.mean_x() mean_y[i] = bunch.mean_y() sigma_z[i] = bunch.sigma_z() @@ -72,7 +72,7 @@ def track_n_show(bunch, slicer, map_woWakes, wake_field): xp_diff = np.zeros(n_macroparticles) - for i in xrange(n_turns): + for i in range(n_turns): for m_ in map_woWakes: m_.track(bunch) diff --git a/PyHEADTAIL/testing/unittests/test_aperture.py b/PyHEADTAIL/testing/unittests/test_aperture.py index 5f358931..a7c015a7 100644 --- a/PyHEADTAIL/testing/unittests/test_aperture.py +++ b/PyHEADTAIL/testing/unittests/test_aperture.py @@ -2,7 +2,7 @@ @date: 12/03/2015 @author: Stefan Hegglin ''' -from __future__ import division + import unittest import numpy as np diff --git a/PyHEADTAIL/testing/unittests/test_cobra.py b/PyHEADTAIL/testing/unittests/test_cobra.py index b2f9d270..3d9bc3f6 100644 --- a/PyHEADTAIL/testing/unittests/test_cobra.py +++ b/PyHEADTAIL/testing/unittests/test_cobra.py @@ -2,7 +2,7 @@ @date: 15/04/2015 @author: Stefan Hegglin ''' -from __future__ import division + import unittest import numpy as np diff --git a/PyHEADTAIL/testing/unittests/test_dispatch.py b/PyHEADTAIL/testing/unittests/test_dispatch.py index 7cd2dfb5..9640846e 100644 --- a/PyHEADTAIL/testing/unittests/test_dispatch.py +++ b/PyHEADTAIL/testing/unittests/test_dispatch.py @@ -2,7 +2,7 @@ @date: 30/09/2015 @author: Stefan Hegglin ''' -from __future__ import division + import unittest import numpy as np @@ -27,9 +27,9 @@ class TestDispatch(unittest.TestCase): '''Test Class for the function dispatch functionality in general.pmath''' def setUp(self): - self.available_CPU = pm._CPU_numpy_func_dict.keys() + self.available_CPU = list(pm._CPU_numpy_func_dict.keys()) if has_pycuda: - self.available_GPU = pm._GPU_func_dict.keys() + self.available_GPU = list(pm._GPU_func_dict.keys()) def test_set_CPU(self): pm.update_active_dict(pm._CPU_numpy_func_dict) diff --git a/PyHEADTAIL/testing/unittests/test_generators.py b/PyHEADTAIL/testing/unittests/test_generators.py index cff7141e..bfaf3db1 100644 --- a/PyHEADTAIL/testing/unittests/test_generators.py +++ b/PyHEADTAIL/testing/unittests/test_generators.py @@ -3,7 +3,7 @@ @author: Stefan Hegglin Tests for generator ''' -from __future__ import division + import unittest import numpy as np @@ -70,7 +70,7 @@ def test_update_beam_with_new_coords(self): self.assertEqual(self.beam.dp.size, self.nparticles, 'Updating the beam with new coordinates leads to' + 'faulty coordinates') - for n in xrange(self.nparticles): + for n in range(self.nparticles): self.assertAlmostEqual(x_copy[n], self.beam.x[n], msg='Updating the beam with new coordinates invalidates' + 'existing coordinates') diff --git a/PyHEADTAIL/testing/unittests/test_gpu_interface.py b/PyHEADTAIL/testing/unittests/test_gpu_interface.py index 477288eb..f66c9abe 100644 --- a/PyHEADTAIL/testing/unittests/test_gpu_interface.py +++ b/PyHEADTAIL/testing/unittests/test_gpu_interface.py @@ -2,7 +2,7 @@ @date: 30/09/2015 @author: Stefan Hegglin ''' -from __future__ import division + import os import unittest @@ -398,7 +398,7 @@ def _monitor_cpu_gpu(self, monitor1, monitor2, bunch1, bunch2): ''' params_to_check = ['mean_x', 'sigma_dp', 'macroparticlenumber', 'n_macroparticles_per_slice'] - for i in xrange(monitor2.n_steps): + for i in range(monitor2.n_steps): bunch2.x += 1 bunch2.xp -= 0.1 bunch2.dp *= 0.97 @@ -406,14 +406,14 @@ def _monitor_cpu_gpu(self, monitor1, monitor2, bunch1, bunch2): res1 = self.read_h5_file(monitor2.filename + '.h5', params_to_check) with GPU(bunch1) as device: - for i in xrange(monitor1.n_steps): + for i in range(monitor1.n_steps): bunch1.x += 1 bunch1.xp -= 0.1 bunch1.dp *= 0.97 monitor1.dump(bunch1) res2 = self.read_h5_file(monitor1.filename + '.h5', params_to_check) - for i in xrange(len(res1)): + for i in range(len(res1)): self.assertTrue(np.allclose(res1[i],res2[i]), msg='.h5 file generated by monitor of CPU/GPU differ' + str(params_to_check)) @@ -427,12 +427,12 @@ def _track_cpu_gpu(self, list_of_maps, bunch1, bunch2, nturns=1): ''' # GPU with GPU(bunch1) as device: - for n in xrange(nturns): + for n in range(nturns): for m in list_of_maps: m.track(bunch1) # CPU - for n in xrange(nturns): + for n in range(nturns): for m in list_of_maps: m.track(bunch2) #print bunch1.x diff --git a/PyHEADTAIL/testing/unittests/test_itest_autorun.py b/PyHEADTAIL/testing/unittests/test_itest_autorun.py index 83fc30b8..d289b8a4 100644 --- a/PyHEADTAIL/testing/unittests/test_itest_autorun.py +++ b/PyHEADTAIL/testing/unittests/test_itest_autorun.py @@ -3,7 +3,7 @@ @author: Stefan Hegglin ''' -from __future__ import division + import unittest @@ -38,7 +38,7 @@ def test_aperturenlossestest(self): ''' try: at.run() - except Exception, err: + except Exception as err: self.fail('ApertureNLossesTest threw an exception:\n' + str(err)) def test_detunerstest(self): @@ -47,7 +47,7 @@ def test_detunerstest(self): ''' try: dt.run() - except Exception, err: + except Exception as err: self.fail('DetunersTest threw an exception:\n' + str(err)) def test_monitortest(self): @@ -56,7 +56,7 @@ def test_monitortest(self): ''' try: mt.run() - except Exception, err: + except Exception as err: self.fail('MonitorTest threw an exception:\n' + str(err)) def test_rfqtest(self): @@ -65,7 +65,7 @@ def test_rfqtest(self): ''' try: rt.run() - except Exception, err: + except Exception as err: self.fail('RFQTest threw an exception:\n' + str(err)) def test_slicingtest(self): @@ -74,7 +74,7 @@ def test_slicingtest(self): ''' try: st.run() - except Exception, err: + except Exception as err: self.fail('SlicingTest threw an exception:\n' + str(err)) def test_transversetrackingtest(self): @@ -83,7 +83,7 @@ def test_transversetrackingtest(self): ''' try: ttt.run() - except Exception, err: + except Exception as err: self.fail('TransverseTrackingTest threw an exception:\n' + str(err)) @@ -93,7 +93,7 @@ def test_waketest(self): ''' try: wt.run() - except Exception, err: + except Exception as err: self.fail('WakeTest threw an exception:\n' + str(err)) diff --git a/PyHEADTAIL/testing/unittests/test_listproxy.py b/PyHEADTAIL/testing/unittests/test_listproxy.py index 3f7d8e4a..c3bbda8d 100644 --- a/PyHEADTAIL/testing/unittests/test_listproxy.py +++ b/PyHEADTAIL/testing/unittests/test_listproxy.py @@ -3,7 +3,7 @@ @author: Stefan Hegglin ''' -from __future__ import division + import unittest diff --git a/PyHEADTAIL/testing/unittests/test_longitudinal_tracking.py b/PyHEADTAIL/testing/unittests/test_longitudinal_tracking.py index 3254ee96..3be9e5fe 100644 --- a/PyHEADTAIL/testing/unittests/test_longitudinal_tracking.py +++ b/PyHEADTAIL/testing/unittests/test_longitudinal_tracking.py @@ -2,7 +2,7 @@ @date: 16/03/2015 @author: Stefan Hegglin ''' -from __future__ import division + import unittest import numpy as np diff --git a/PyHEADTAIL/testing/unittests/test_monitor.py b/PyHEADTAIL/testing/unittests/test_monitor.py index 4e6e38ef..6d8d528c 100644 --- a/PyHEADTAIL/testing/unittests/test_monitor.py +++ b/PyHEADTAIL/testing/unittests/test_monitor.py @@ -2,7 +2,7 @@ @date: 24/11/2015 @author: Stefan Hegglin ''' -from __future__ import division + import h5py as hp import os @@ -41,7 +41,7 @@ def test_bunchmonitor(self): to check pattern when accessing 'mean_x', 'macrop' ''' mock = self.generate_mock_bunch() - for i in xrange(self.n_turns): + for i in range(self.n_turns): self.bunch_monitor.dump(mock) bunchdata = hp.File(self.bunch_fn + '.h5') b = bunchdata['Bunch'] @@ -60,7 +60,7 @@ def test_slicemonitor(self): slicer=mock_slicer, buffer_size=11, write_buffer_every=9, slice_stats_to_store=['propertyA'], bunch_stats_to_store=['mean_x', 'macrop']) - for i in xrange(self.n_turns): + for i in range(self.n_turns): slice_monitor.dump(mock_bunch) s = hp.File(self.s_fn + '.h5') sd = s['Slices'] @@ -68,8 +68,8 @@ def test_slicemonitor(self): self.assertTrue(np.allclose(sb['mean_x'], np.arange(start=1, stop=self.n_turns+0.5))) self.assertTrue(np.allclose(sb['macrop'], 99*np.ones(self.n_turns))) - for k in xrange(nslices): - for j in xrange(self.n_turns): + for k in range(nslices): + for j in range(self.n_turns): self.assertTrue(np.allclose(sd['propertyA'][k,j], k + (j+1)*1000), 'Slices part of SliceMonitor wrong') @@ -85,7 +85,7 @@ def test_cellmonitor(self): beta_z=np.abs(0.003 * bunch.circumference / (2*np.pi*0.004)), write_buffer_every=9, ) - for i in xrange(self.n_turns): + for i in range(self.n_turns): cell_monitor.dump(bunch) s = hp.File(self.s_fn + '.h5') sc = s['Cells'] diff --git a/PyHEADTAIL/testing/unittests/test_particles.py b/PyHEADTAIL/testing/unittests/test_particles.py index ef440ddc..3c19abe4 100644 --- a/PyHEADTAIL/testing/unittests/test_particles.py +++ b/PyHEADTAIL/testing/unittests/test_particles.py @@ -3,7 +3,7 @@ @author: Stefan Hegglin, Adrian Oeftiger ''' -from __future__ import division + import unittest import numpy as np @@ -200,7 +200,7 @@ def test_sort_particles(self): old[attr] = getattr(bunch, attr).copy() bunch.sort_for('z') new_idx = bunch.id - 1 - for attr, oldarray in old.iteritems(): + for attr, oldarray in old.items(): self.assertTrue(np.all(oldarray[new_idx] == getattr(bunch, attr)), msg="beam.sort_for('z') should reorder all beam " "particle arrays, but beam." + str(attr) + " is " diff --git a/PyHEADTAIL/testing/unittests/test_slicing.py b/PyHEADTAIL/testing/unittests/test_slicing.py index b126a3b4..17f0225b 100644 --- a/PyHEADTAIL/testing/unittests/test_slicing.py +++ b/PyHEADTAIL/testing/unittests/test_slicing.py @@ -3,7 +3,7 @@ @author: Stefan Hegglin ''' -from __future__ import division + import unittest import numpy as np @@ -96,10 +96,10 @@ def test_unif_charge_slicer(self): 'slices in UniformChargeSlicer don\'t have' + 'the same number of macroparticles in them') else : - print('test_unif_charge_slicer() not run because ' + + print(('test_unif_charge_slicer() not run because ' + 'uniform charge distribution is impossible ' + '(nparticles[' + str(self.macroparticlenumber) + - '] % nslices[' + str(self.nslices) + '] != 0)') + '] % nslices[' + str(self.nslices) + '] != 0)')) def test_sliceset_macroparticles(self): '''Tests whether the sum of all particles per slice @@ -131,7 +131,7 @@ def test_emittance_no_dispersion(self): bunch = self.create_bunch_with_params(1, 42, 0., 20) slice_set = self.basic_slicer.slice(bunch) self.basic_slicer.add_statistics(slice_set, bunch, True) - for n in xrange(self.nslices): + for n in range(self.nslices): self.assertAlmostEqual(slice_set.epsn_x[n], slice_set.eff_epsn_x[n], places=4, diff --git a/PyHEADTAIL/testing/unittests/test_slicing_gpu.py b/PyHEADTAIL/testing/unittests/test_slicing_gpu.py index 963d50bd..9d0c958e 100644 --- a/PyHEADTAIL/testing/unittests/test_slicing_gpu.py +++ b/PyHEADTAIL/testing/unittests/test_slicing_gpu.py @@ -3,7 +3,7 @@ @author: Adrian Oeftiger ''' -from __future__ import division + import unittest import numpy as np diff --git a/PyHEADTAIL/testing/unittests/test_transverse_tracking.py b/PyHEADTAIL/testing/unittests/test_transverse_tracking.py index eb50ac0d..a9f03fa3 100644 --- a/PyHEADTAIL/testing/unittests/test_transverse_tracking.py +++ b/PyHEADTAIL/testing/unittests/test_transverse_tracking.py @@ -3,7 +3,7 @@ @author: Stefan Hegglin ''' -from __future__ import division + import unittest import numpy as np diff --git a/PyHEADTAIL/testing/unittests/testsuite.py b/PyHEADTAIL/testing/unittests/testsuite.py index 27401770..231368e5 100644 --- a/PyHEADTAIL/testing/unittests/testsuite.py +++ b/PyHEADTAIL/testing/unittests/testsuite.py @@ -12,7 +12,7 @@ import pycuda.autoinit except ImportError: has_pycuda = False - print 'No PyCUDA installation found.' + print('No PyCUDA installation found.') from test_slicing import TestSlicing diff --git a/PyHEADTAIL/trackers/detuners.py b/PyHEADTAIL/trackers/detuners.py index 8031d3d5..c5d4fad1 100644 --- a/PyHEADTAIL/trackers/detuners.py +++ b/PyHEADTAIL/trackers/detuners.py @@ -20,7 +20,7 @@ an incoherent detuning. @copyright CERN """ -from __future__ import division + import numpy as np from math import factorial @@ -31,7 +31,7 @@ # from collections import Iterable -class SegmentDetuner(object): +class SegmentDetuner(object, metaclass=ABCMeta): """Abstract base class for detuning elements and effects defined only for a segment of the accelerator ring (NB. The segment can also be given by the full circumference). @@ -39,7 +39,6 @@ class SegmentDetuner(object): implement the detune(beam) method to describe the change in phase advance for each particle of the beam. """ - __metaclass__ = ABCMeta @abstractmethod def detune(self, beam): @@ -81,7 +80,7 @@ def _make_calc_detuning(Qp): slower for low order polynomials. """ order = len(Qp) - coeffs = [ Qp[i] / float(factorial(i+1)) for i in xrange(order) ] + coeffs = [ Qp[i] / float(factorial(i+1)) for i in range(order) ] if order == 1: def calc_detuning(dp): @@ -152,7 +151,7 @@ def detune(self, beam): return dQ_x, dQ_y -class DetunerCollection(object): +class DetunerCollection(object, metaclass=ABCMeta): """Abstract base class for a collection of SegmentDetuner objects (see above). A detuner collection object defines the detuning for one complete turn around the accelerator ring for the given @@ -177,7 +176,6 @@ class DetunerCollection(object): be accessed via square brackets [i] where i is the index of the segment. """ - __metaclass__ = ABCMeta @abstractmethod def generate_segment_detuner(self, dmu_x, dmu_y, **kwargs): diff --git a/PyHEADTAIL/trackers/libTPSA.py b/PyHEADTAIL/trackers/libTPSA.py index 60ceae02..0efbbbc1 100644 --- a/PyHEADTAIL/trackers/libTPSA.py +++ b/PyHEADTAIL/trackers/libTPSA.py @@ -12,7 +12,7 @@ Functions such as sin, cos, exp, log etc are envisaged to be implemented in a later version. ''' -from __future__ import division + import numpy as np diff --git a/PyHEADTAIL/trackers/libintegrators.py b/PyHEADTAIL/trackers/libintegrators.py index 6645f8b0..667193d0 100644 --- a/PyHEADTAIL/trackers/libintegrators.py +++ b/PyHEADTAIL/trackers/libintegrators.py @@ -9,10 +9,10 @@ of a given integration method -- it may be used generically for any integration method with the described signature. ''' -from __future__ import division + import numpy as np -import libTPSA +from . import libTPSA def is_symple(integrator): '''returns whether the given integrator is symplectic w.r.t. to a certain diff --git a/PyHEADTAIL/trackers/longitudinal_tracking.py b/PyHEADTAIL/trackers/longitudinal_tracking.py index 2beace93..34cf256e 100644 --- a/PyHEADTAIL/trackers/longitudinal_tracking.py +++ b/PyHEADTAIL/trackers/longitudinal_tracking.py @@ -4,7 +4,7 @@ @copyright CERN ''' -from __future__ import division + import numpy as np from types import MethodType @@ -26,7 +26,7 @@ # currently: only Velocity Verlet algorithm hard coded in RFSystems -class LongitudinalMap(Element): +class LongitudinalMap(Element, metaclass=ABCMeta): """ A longitudinal map represents a longitudinal dynamical element (e.g. a kick or a drift...), i.e. an abstraction of a cavity @@ -44,7 +44,6 @@ class LongitudinalMap(Element): \Delta w / w0 = \sum_j \eta_j * \delta^(i + 1) (for the revolution frequency w) """ - __metaclass__ = ABCMeta def __init__(self, alpha_array, *args, **kwargs): """ @@ -72,7 +71,7 @@ def eta(self, dp, gamma): and with signature (alpha_array, gamma). """ eta = 0 - for i in xrange(len(self.alpha_array)): # order = len - 1 + for i in range(len(self.alpha_array)): # order = len - 1 eta_func = getattr(self, '_eta' + str(i)) eta_i = eta_func(self.alpha_array, gamma) eta += eta_i * (dp ** i) @@ -254,7 +253,7 @@ def track_without_dispersion(self, beam): # return phi_rel -class LongitudinalOneTurnMap(LongitudinalMap): +class LongitudinalOneTurnMap(LongitudinalMap, metaclass=ABCMeta): """ A longitudinal one turn map tracks over a complete turn. Any inheriting classes guarantee to provide a self.track(beam) @@ -264,8 +263,6 @@ class LongitudinalOneTurnMap(LongitudinalMap): LongitudinalMap objects. """ - __metaclass__ = ABCMeta - def __init__(self, alpha_array, circumference, *args, **kwargs): """LongitudinalOneTurnMap objects know their circumference.""" super(LongitudinalOneTurnMap, self).__init__( diff --git a/PyHEADTAIL/trackers/rf_bucket.py b/PyHEADTAIL/trackers/rf_bucket.py index 12548d41..750561b4 100644 --- a/PyHEADTAIL/trackers/rf_bucket.py +++ b/PyHEADTAIL/trackers/rf_bucket.py @@ -1,6 +1,6 @@ """.. copyright:: CERN""" -from __future__ import division + import numpy as np from scipy.constants import c @@ -12,6 +12,7 @@ zero_crossings as cvt_zero_crossings) from PyHEADTAIL.general.decorators import deprecated from PyHEADTAIL.general.element import Printing +from functools import reduce def attach_clean_buckets(rf_parameter_changing_method, rfsystems_instance): @@ -405,7 +406,7 @@ def vf(z): coefficient = np.abs(self.charge)/self.circumference focusing_potential = reduce(lambda x, y: x+y, [ self.R/h[i] * V[i] * np.cos(h[i]*z/self.R + dphi[i]) - for i in xrange(len(V))]) + for i in range(len(V))]) return coefficient * focusing_potential if not acceleration: diff --git a/PyHEADTAIL/trackers/transverse_tracking.py b/PyHEADTAIL/trackers/transverse_tracking.py index b73477b0..23363119 100644 --- a/PyHEADTAIL/trackers/transverse_tracking.py +++ b/PyHEADTAIL/trackers/transverse_tracking.py @@ -5,7 +5,7 @@ @copyright CERN """ -from __future__ import division + import numpy as np @@ -304,7 +304,7 @@ def _generate_segment_maps(self): dmu_x = dQ_x / pm.atleast_1d(self.accQ_x)[-1] dmu_y = dQ_y / pm.atleast_1d(self.accQ_y)[-1] - for seg in xrange(n_segments): + for seg in range(n_segments): s0 = seg % n_segments s1 = (seg + 1) % n_segments diff --git a/PyHEADTAIL/trackers/wrapper.py b/PyHEADTAIL/trackers/wrapper.py index 8503eec8..b9e47242 100644 --- a/PyHEADTAIL/trackers/wrapper.py +++ b/PyHEADTAIL/trackers/wrapper.py @@ -1,4 +1,4 @@ -from __future__ import division + import numpy as np diff --git a/generate_python3 b/generate_python3 index 96d3f241..5003d7d3 100755 --- a/generate_python3 +++ b/generate_python3 @@ -5,5 +5,5 @@ rm ../python3/PyHEADTAIL/*.so 2to3 --output-dir=../python3/PyHEADTAIL -W -n ../PyHEADTAIL > 2to3.out -rm -rf ../python3/PyHEADTAIL/.git +#rm -rf ../python3/PyHEADTAIL/.git diff --git a/prepush.py b/prepush.py index a7066490..9a9abf29 100755 --- a/prepush.py +++ b/prepush.py @@ -36,20 +36,20 @@ def test_all(): ["git", "rev-parse", "--abbrev-ref", "HEAD"]).rstrip() if branch == 'master' or branch == 'develop': - print ('\n' + 'X' * 66) + print(('\n' + 'X' * 66)) print ('You are trying to push to the master or develop branch.') print ('Checking unit tests first...') - print ('X' * 66 + '\n') + print(('X' * 66 + '\n')) res = test_all() if res == 0: - print ('\n' + 'X' * 66) + print(('\n' + 'X' * 66)) print ('Passed unit tests, proceeding.') - print ('X' * 66 + '\n') + print(('X' * 66 + '\n')) else: - print ('\n' + 'X' * 66) + print(('\n' + 'X' * 66)) print ('Failed unit tests, fix them before comitting. Aborting.') - print ('X' * 66 + '\n') + print(('X' * 66 + '\n')) sys.exit(res) else: # if not on develop or master: continue diff --git a/release.py b/release.py index ee90a9c5..66cdec40 100755 --- a/release.py +++ b/release.py @@ -61,7 +61,7 @@ def bumpversion(version, part): parts = version.split('.') # only integers stored: assert all(p.isdigit() for p in parts) - major, minor, patch = map(int, parts) + major, minor, patch = list(map(int, parts)) if part == 'major': version = '{0}.0.0'.format(major + 1) elif part == 'minor': @@ -100,8 +100,8 @@ def which_part_increases(last_version, new_version): new_parts = new_version.split('.') # only integers stored: assert all(p.isdigit() for p in last_parts + new_parts) - lmajor, lminor, lpatch = map(int, last_parts) - nmajor, nminor, npatch = map(int, new_parts) + lmajor, lminor, lpatch = list(map(int, last_parts)) + nmajor, nminor, npatch = list(map(int, new_parts)) if lmajor + 1 == nmajor and nminor == 0 and npatch == 0: return 'major' elif lmajor == nmajor and lminor + 1 == nminor and npatch == 0: @@ -144,8 +144,8 @@ def establish_new_version(version_location): assert subprocess.call(["git", "add", vpath]) == 0 assert subprocess.call( ["git", "commit", "-m", "release-script: bumping version file."]) == 0 - print ('*** The new release version has been bumped: PyHEADTAIL v' - + release_version) + print(('*** The new release version has been bumped: PyHEADTAIL v' + + release_version)) return release_version def ensure_hub_is_installed(): @@ -189,7 +189,7 @@ def check_or_setup_github_OAuth_token(): ' (Get the security token via github\'s website, cf.' '\n*** https://help.github.com/articles/creating-a-personal-access-' 'token-for-the-command-line/ )\n') - token = input('--> Please enter your github OAuth security token:\n') + token = eval(input('--> Please enter your github OAuth security token:\n')) os.environ['GITHUB_TOKEN'] = token def ensure_gitpulls_is_installed(): @@ -427,7 +427,7 @@ def release_pip(): # ALGORITHM FOR RELEASE PROCESS: if __name__ == '__main__': - print ('*** Current working directory:\n' + os.getcwd() + '\n') + print(('*** Current working directory:\n' + os.getcwd() + '\n')) ensure_hub_is_installed() # are we on a release branch already? diff --git a/setup.py b/setup.py index 34173101..38d0c7c8 100755 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ "may have to install with the following line:\n\n" "$ CC=gcc-4.9 ./install\n" "(or any equivalent version of gcc)") - raw_input('Hit any key to continue...') + input('Hit any key to continue...') args = sys.argv[1:]