diff --git a/docs/iris/example_code/General/custom_file_loading.py b/docs/iris/example_code/General/custom_file_loading.py index 6b4c077102..8220a2f56e 100644 --- a/docs/iris/example_code/General/custom_file_loading.py +++ b/docs/iris/example_code/General/custom_file_loading.py @@ -65,7 +65,7 @@ def load_NAME_III(filename): # loading a file gives a generator of lines which can be progressed using the next() method. # This will come in handy as we wish to progress through the file line by line. - file_handle = file(filename) + file_handle = open(filename) # define a dictionary which can hold the header metadata about this file headers = {} diff --git a/docs/iris/example_code/Meteorology/COP_maps.py b/docs/iris/example_code/Meteorology/COP_maps.py index f681fe4c7e..40fc4aba2b 100644 --- a/docs/iris/example_code/Meteorology/COP_maps.py +++ b/docs/iris/example_code/Meteorology/COP_maps.py @@ -18,8 +18,9 @@ """ +from six.moves import zip + import os.path -import itertools import matplotlib.pyplot as plt import numpy as np @@ -65,7 +66,8 @@ def main(): # Iterate over each latitude longitude slice for both e1 and a1b scenarios simultaneously - for e1_slice, a1b_slice in itertools.izip(e1.slices(['latitude', 'longitude']), a1b.slices(['latitude', 'longitude'])): + for e1_slice, a1b_slice in zip(e1.slices(['latitude', 'longitude']), + a1b.slices(['latitude', 'longitude'])): time_coord = a1b_slice.coord('time') diff --git a/docs/iris/src/sphinxext/generate_package_rst.py b/docs/iris/src/sphinxext/generate_package_rst.py index bc6309cf5c..64363fb898 100644 --- a/docs/iris/src/sphinxext/generate_package_rst.py +++ b/docs/iris/src/sphinxext/generate_package_rst.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import filter import os import sys diff --git a/docs/iris/src/userguide/regridding_plots/regridded_to_global_area_weighted.py b/docs/iris/src/userguide/regridding_plots/regridded_to_global_area_weighted.py index 2e6b6a8356..944cf8022e 100644 --- a/docs/iris/src/userguide/regridding_plots/regridded_to_global_area_weighted.py +++ b/docs/iris/src/userguide/regridding_plots/regridded_to_global_area_weighted.py @@ -1,5 +1,6 @@ from __future__ import (absolute_import, division, print_function) +from six.moves import zip import iris import iris.analysis diff --git a/lib/iris/__init__.py b/lib/iris/__init__.py index 22cebbeb89..b9f3c0452c 100644 --- a/lib/iris/__init__.py +++ b/lib/iris/__init__.py @@ -369,7 +369,7 @@ def load_cubes(uris, constraints=None, callback=None): collection = _load_collection(uris, constraints, callback).merged() # Make sure we have exactly one merged cube per constraint - bad_pairs = filter(lambda pair: len(pair) != 1, collection.pairs) + bad_pairs = [pair for pair in collection.pairs if len(pair) != 1] if bad_pairs: fmt = ' {} -> {} cubes' bits = [fmt.format(pair.constraint, len(pair)) for pair in bad_pairs] diff --git a/lib/iris/_concatenate.py b/lib/iris/_concatenate.py index 62c4016e34..fb0a8137b8 100644 --- a/lib/iris/_concatenate.py +++ b/lib/iris/_concatenate.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip from collections import defaultdict, namedtuple diff --git a/lib/iris/_constraints.py b/lib/iris/_constraints.py index 46765276f4..3d9c1f6881 100644 --- a/lib/iris/_constraints.py +++ b/lib/iris/_constraints.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip import collections import operator diff --git a/lib/iris/_merge.py b/lib/iris/_merge.py index b39dcb3e9f..fd3931bb61 100644 --- a/lib/iris/_merge.py +++ b/lib/iris/_merge.py @@ -23,6 +23,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import map, range, zip from collections import namedtuple, OrderedDict from copy import deepcopy @@ -1171,7 +1172,7 @@ def merge(self, unique=True): self._report_duplicate(nd_indexes, group_by_nd_index) # Generate group-depth merged cubes from the source-cubes. - for level in xrange(group_depth): + for level in range(group_depth): # Stack up all the data from all of the relevant source # cubes in a single biggus ArrayStack. # If it turns out that all the source cubes already had diff --git a/lib/iris/analysis/__init__.py b/lib/iris/analysis/__init__.py index 55ec7baad9..8cc4ac759d 100644 --- a/lib/iris/analysis/__init__.py +++ b/lib/iris/analysis/__init__.py @@ -47,6 +47,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, range, zip import collections @@ -92,8 +93,8 @@ def _first_coord_w_cube(self): as (cube, coord). """ - return filter(lambda cube_coord: cube_coord[1] is not None, - zip(self.cubes, self.coords))[0] + return next(filter(lambda cube_coord: cube_coord[1] is not None, + zip(self.cubes, self.coords))) def __repr__(self): # No exact repr, so a helpful string is given instead @@ -1074,7 +1075,7 @@ def interp_order(length): column_peaks.append(column[0]) continue - tck = scipy.interpolate.splrep(range(column.size), column, k=k) + tck = scipy.interpolate.splrep(np.arange(column.size), column, k=k) npoints = column.size * 100 points = np.linspace(0, column.size - 1, npoints) spline = scipy.interpolate.splev(points, tck) diff --git a/lib/iris/analysis/_interpolation.py b/lib/iris/analysis/_interpolation.py index eeab4fd5ba..ac8270b946 100644 --- a/lib/iris/analysis/_interpolation.py +++ b/lib/iris/analysis/_interpolation.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """A collection of helpers for interpolation.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip from collections import namedtuple from itertools import product @@ -500,7 +501,7 @@ def _points(self, sample_points, data, data_dims=None): instance of the interpolated data. """ - dims = range(self._src_cube.ndim) + dims = list(range(self._src_cube.ndim)) data_dims = data_dims or dims if len(data_dims) != data.ndim: @@ -514,7 +515,7 @@ def _points(self, sample_points, data, data_dims=None): raise NotImplementedError(msg) # Broadcast the data into the shape of the original cube. - if data_dims != range(self._src_cube.ndim): + if data_dims != list(range(self._src_cube.ndim)): strides = list(data.strides) for dim in range(self._src_cube.ndim): if dim not in data_dims: diff --git a/lib/iris/analysis/_scipy_interpolate.py b/lib/iris/analysis/_scipy_interpolate.py index 5bd663a7aa..560a30cfee 100644 --- a/lib/iris/analysis/_scipy_interpolate.py +++ b/lib/iris/analysis/_scipy_interpolate.py @@ -1,5 +1,6 @@ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip import numpy as np @@ -22,7 +23,7 @@ def _ndim_coords_from_arrays(points, ndim=None): points = points[0] if isinstance(points, tuple): p = np.broadcast_arrays(*points) - for j in xrange(1, len(p)): + for j in range(1, len(p)): if p[j].shape != p[0].shape: raise ValueError( "coordinate arrays do not have the same shape") diff --git a/lib/iris/analysis/calculus.py b/lib/iris/analysis/calculus.py index 96a12895c4..99931f5479 100644 --- a/lib/iris/analysis/calculus.py +++ b/lib/iris/analysis/calculus.py @@ -22,6 +22,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, zip import re import warnings diff --git a/lib/iris/analysis/cartography.py b/lib/iris/analysis/cartography.py index a7447907ba..09409fc8ba 100644 --- a/lib/iris/analysis/cartography.py +++ b/lib/iris/analysis/cartography.py @@ -20,9 +20,9 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip import copy -import itertools import warnings import numpy as np @@ -108,10 +108,10 @@ def rotate_pole(lons, lats, pole_lon, pole_lat): def _get_lat_lon_coords(cube): - lat_coords = filter(lambda coord: "latitude" in coord.name(), - cube.coords()) - lon_coords = filter(lambda coord: "longitude" in coord.name(), - cube.coords()) + lat_coords = [coord for coord in cube.coords() + if "latitude" in coord.name()] + lon_coords = [coord for coord in cube.coords() + if "longitude" in coord.name()] if len(lat_coords) > 1 or len(lon_coords) > 1: raise ValueError( "Calling _get_lat_lon_coords() with multiple lat or lon coords" @@ -372,7 +372,7 @@ def area_weights(cube, normalize=False): # Now we create an array of weights for each cell. This process will # handle adding the required extra dimensions and also take care of # the order of dimensions. - broadcast_dims = filter(lambda x: x is not None, (lat_dim, lon_dim)) + broadcast_dims = [x for x in (lat_dim, lon_dim) if x is not None] wshape = [] for idim, dim in zip((0, 1), (lat_dim, lon_dim)): if dim is not None: @@ -421,8 +421,8 @@ def cosine_latitude_weights(cube): """ # Find all latitude coordinates, we want one and only one. - lat_coords = filter(lambda coord: "latitude" in coord.name(), - cube.coords()) + lat_coords = [coord for coord in cube.coords() + if "latitude" in coord.name()] if len(lat_coords) > 1: raise ValueError("Multiple latitude coords are currently disallowed.") try: @@ -455,7 +455,7 @@ def cosine_latitude_weights(cube): # Create weights for each grid point. This operation handles adding extra # dimensions and also the order of the dimensions. - broadcast_dims = filter(lambda x: x is not None, lat_dims) + broadcast_dims = [x for x in lat_dims if x is not None] wshape = [] for idim, dim in enumerate(lat_dims): if dim is not None: @@ -641,7 +641,7 @@ def project(cube, target_proj, nx=None, ny=None): # Step through cube data, regrid onto desired projection and insert results # in new_data array - for index, ll_slice in itertools.izip(index_it, slice_it): + for index, ll_slice in zip(index_it, slice_it): # Regrid source data onto target grid index = list(index) index[xdim] = slice(None, None) diff --git a/lib/iris/analysis/geometry.py b/lib/iris/analysis/geometry.py index 90306a8d69..277d4309f4 100644 --- a/lib/iris/analysis/geometry.py +++ b/lib/iris/analysis/geometry.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -23,6 +23,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range import warnings diff --git a/lib/iris/analysis/interpolate.py b/lib/iris/analysis/interpolate.py index 3246e179f8..dc2d458fe1 100644 --- a/lib/iris/analysis/interpolate.py +++ b/lib/iris/analysis/interpolate.py @@ -22,6 +22,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import map, range, zip import collections import warnings @@ -58,7 +59,7 @@ def _cartesian_sample_points(sample_points, sample_point_coord_names): # Find lat and lon coord indices i_lat = i_lon = None - i_non_latlon = range(len(sample_point_coord_names)) + i_non_latlon = list(range(len(sample_point_coord_names))) for i, name in enumerate(sample_point_coord_names): if "latitude" in name: i_lat = i @@ -730,7 +731,7 @@ def __call__(self, requested_x): r = self._interpolator(requested_x[ok]) # Reshape the properly formed array to put the interpolator.axis last i.e. dims 0, 1, 2 -> 0, 2, 1 if axis = 1 - axes = range(r.ndim) + axes = list(range(r.ndim)) del axes[self._interpolator.axis] axes.append(self._interpolator.axis) @@ -748,7 +749,7 @@ def __call__(self, requested_x): grad = (self.y[..., -1:] - self.y[..., -2:-1]) / (self.x[-1] - self.x[-2]) result[interpolator_result_index] = self.y[..., -1:] + (requested_x[gt] - self.x[-1]) * grad - axes = range(len(interpolator_result_index)) + axes = list(range(len(interpolator_result_index))) axes.insert(self._interpolator.axis, axes.pop(axes[-1])) result = result.transpose(axes) diff --git a/lib/iris/analysis/maths.py b/lib/iris/analysis/maths.py index f5bee3f647..972298ff4d 100644 --- a/lib/iris/analysis/maths.py +++ b/lib/iris/analysis/maths.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter import warnings import math diff --git a/lib/iris/analysis/trajectory.py b/lib/iris/analysis/trajectory.py index 53bab652e1..7bb9e88e8a 100644 --- a/lib/iris/analysis/trajectory.py +++ b/lib/iris/analysis/trajectory.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range import math @@ -76,7 +77,8 @@ def __init__(self, waypoints, sample_count=10): self.sample_count = sample_count # create line segments from the waypoints - segments = [_Segment(self.waypoints[i], self.waypoints[i+1]) for i in range(len(self.waypoints) - 1)] + segments = [_Segment(self.waypoints[i], self.waypoints[i+1]) + for i in range(len(self.waypoints) - 1)] # calculate our total length self.length = sum([seg.length for seg in segments]) diff --git a/lib/iris/aux_factory.py b/lib/iris/aux_factory.py index 5afc7acede..a9364ca0df 100644 --- a/lib/iris/aux_factory.py +++ b/lib/iris/aux_factory.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import map, range, zip from abc import ABCMeta, abstractmethod, abstractproperty import warnings @@ -288,7 +289,7 @@ def _nd_points(coord, dims, ndim): sorted_pairs = sorted(enumerate(dims), key=lambda pair: pair[1]) transpose_order = [pair[0] for pair in sorted_pairs] points = coord._points - if dims and transpose_order != range(len(dims)): + if dims and transpose_order != list(range(len(dims))): points = points.transpose(transpose_order) # Expand dimensionality to be consistent with the Cube. @@ -322,7 +323,7 @@ def _remap(self, dependency_dims, derived_dims): # no transpose is needed. if derived_dims: keys = tuple(slice(None) if dim in derived_dims else 0 for - dim in xrange(ndim)) + dim in range(ndim)) nd_points = nd_points[keys] else: # If no coord, treat value as zero. diff --git a/lib/iris/coord_categorisation.py b/lib/iris/coord_categorisation.py index 1ee08706b0..4592327aa6 100644 --- a/lib/iris/coord_categorisation.py +++ b/lib/iris/coord_categorisation.py @@ -28,6 +28,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range import calendar import collections @@ -216,7 +217,7 @@ def _months_in_season(season): # Can't match the season, raise an error. raise ValueError('unrecognised season: {!s}'.format(season)) m1 = m0 + len(season) - return map(lambda month: (month % 12) + 1, range(m0, m1)) + return [(month % 12) + 1 for month in range(m0, m1)] def _validate_seasons(seasons): @@ -233,13 +234,13 @@ def _validate_seasons(seasons): for season in seasons: c.update(_months_in_season(season)) # Make a list of months that are not present... - not_present = [calendar.month_abbr[month] for month in xrange(1, 13) + not_present = [calendar.month_abbr[month] for month in range(1, 13) if month not in c] if not_present: raise ValueError('some months do not appear in any season: ' '{!s}'.format(', '.join(not_present))) # Make a list of months that appear multiple times... - multi_present = [calendar.month_abbr[month] for month in xrange(1, 13) + multi_present = [calendar.month_abbr[month] for month in range(1, 13) if c[month] > 1] if multi_present: raise ValueError('some months appear in more than one season: ' @@ -258,8 +259,9 @@ def _month_year_adjusts(seasons): month_year_adjusts = [None, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for season in seasons: months = _months_in_season(season) - for month in filter(lambda m: m > months[-1], months): - month_year_adjusts[month] = 1 + for month in months: + if month > months[-1]: + month_year_adjusts[month] = 1 return month_year_adjusts diff --git a/lib/iris/coords.py b/lib/iris/coords.py index ac3c87a1ad..a40b9ff7f7 100644 --- a/lib/iris/coords.py +++ b/lib/iris/coords.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, map, range from abc import ABCMeta, abstractproperty import collections @@ -800,7 +801,7 @@ def is_monotonic(self): return False if self.bounds is not None: - for b_index in xrange(self.nbounds): + for b_index in range(self.nbounds): if not iris.util.monotonic(self.bounds[..., b_index], strict=True): return False @@ -1449,7 +1450,7 @@ def bounds(self, bounds): if n_points > 1: directions = set() - for b_index in xrange(n_bounds): + for b_index in range(n_bounds): monotonic, direction = iris.util.monotonic( bounds[:, b_index], strict=True, return_direction=True) if not monotonic: @@ -1680,9 +1681,9 @@ def xml_element(self, doc): cellMethod_xml_element = doc.createElement('cellMethod') cellMethod_xml_element.setAttribute('method', self.method) - for coord_name, interval, comment in map(None, self.coord_names, - self.intervals, - self.comments): + for coord_name, interval, comment in izip_longest(self.coord_names, + self.intervals, + self.comments): coord_xml_element = doc.createElement('coord') if coord_name is not None: coord_xml_element.setAttribute('name', coord_name) @@ -1701,7 +1702,7 @@ def __init__(self, coord): self._coord = coord if coord.ndim != 1: raise iris.exceptions.CoordinateMultiDimError(coord) - self._indices = iter(xrange(coord.shape[0])) + self._indices = iter(range(coord.shape[0])) def next(self): # NB. When self._indices runs out it will raise StopIteration for us. diff --git a/lib/iris/cube.py b/lib/iris/cube.py index c50d3d3bf1..cfe809e114 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, map, range, zip from xml.dom.minidom import Document import collections @@ -743,8 +744,8 @@ def metadata(self, value): try: value = CubeMetadata(*value) except TypeError: - attr_check = lambda name: not hasattr(value, name) - missing_attrs = filter(attr_check, CubeMetadata._fields) + missing_attrs = [field for field in CubeMetadata._fields + if not hasattr(value, field)] if missing_attrs: raise TypeError('Invalid/incomplete metadata') for name in CubeMetadata._fields: @@ -1619,11 +1620,11 @@ def summary(self, shorten=False, name_padding=35): """ # Create a set to contain the axis names for each data dimension. - dim_names = [set() for dim in xrange(len(self.shape))] + dim_names = [set() for dim in range(len(self.shape))] # Add the dim_coord names that participate in the associated data # dimensions. - for dim in xrange(len(self.shape)): + for dim in range(len(self.shape)): dim_coords = self.coords(contains_dimension=dim, dim_coords=True) if dim_coords: dim_names[dim].add(dim_coords[0].name()) @@ -1736,7 +1737,7 @@ def vector_summary(vector_coords, cube_header, max_line_offset): # - WITH dimension markers. for index, coord in enumerate(vector_coords): dims = self.coord_dims(coord) - for dim in xrange(len(self.shape)): + for dim in range(len(self.shape)): width = alignment[dim] - len(vector_summary[index]) char = 'x' if dim in dims else '-' line = '{pad:{width}}{char}'.format(pad=' ', @@ -2475,14 +2476,14 @@ def transpose(self, new_order=None): def remap_dim_coord(coord_and_dim): coord, dim = coord_and_dim return coord, dim_mapping[dim] - self._dim_coords_and_dims = map(remap_dim_coord, - self._dim_coords_and_dims) + self._dim_coords_and_dims = list(map(remap_dim_coord, + self._dim_coords_and_dims)) def remap_aux_coord(coord_and_dims): coord, dims = coord_and_dims return coord, tuple(dim_mapping[dim] for dim in dims) - self._aux_coords_and_dims = map(remap_aux_coord, - self._aux_coords_and_dims) + self._aux_coords_and_dims = list(map(remap_aux_coord, + self._aux_coords_and_dims)) def xml(self, checksum=False, order=True, byteorder=True): """ @@ -2865,8 +2866,8 @@ def collapsed(self, coords, aggregator, **kwargs): if (isinstance(aggregator, iris.analysis.WeightedAggregator) and not aggregator.uses_weighting(**kwargs)): msg = "Collapsing spatial coordinate {!r} without weighting" - lat_match = filter(lambda coord: 'latitude' in coord.name(), - coords) + lat_match = [coord for coord in coords + if 'latitude' in coord.name()] if lat_match: for coord in lat_match: warnings.warn(msg.format(coord.name())) @@ -3077,8 +3078,9 @@ def aggregated_by(self, coords, aggregator, **kwargs): # Determine the other coordinates that share the same group-by # coordinate dimension. - shared_coords = filter(lambda coord_: coord_ not in groupby_coords, - self.coords(dimensions=dimension_to_groupby)) + shared_coords = list(filter( + lambda coord_: coord_ not in groupby_coords, + self.coords(dimensions=dimension_to_groupby))) # Create the aggregation group-by instance. groupby = iris.analysis._Groupby(groupby_coords, shared_coords) @@ -3548,7 +3550,7 @@ def next(self): cube = self._cube[tuple(index_list)] if self._ordered: - if any(self._mod_requested_dims != range(len(cube.shape))): + if any(self._mod_requested_dims != list(range(len(cube.shape)))): cube.transpose(self._mod_requested_dims) return cube diff --git a/lib/iris/experimental/animate.py b/lib/iris/experimental/animate.py index 8992d05008..42344288a0 100644 --- a/lib/iris/experimental/animate.py +++ b/lib/iris/experimental/animate.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range import warnings @@ -119,7 +120,7 @@ def update_animation_iris(i, cubes, vmin, vmax, coords): vmax = kwargs.pop('vmax', max([cc.data.max() for cc in cubes])) update = update_animation_iris - frames = xrange(len(cubes)) + frames = range(len(cubes)) return animation.FuncAnimation(fig, update, frames=frames, diff --git a/lib/iris/experimental/fieldsfile.py b/lib/iris/experimental/fieldsfile.py index 663e3668d2..8b282f8ae5 100644 --- a/lib/iris/experimental/fieldsfile.py +++ b/lib/iris/experimental/fieldsfile.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, range, zip from iris.coords import DimCoord from iris.cube import CubeList diff --git a/lib/iris/experimental/regrid.py b/lib/iris/experimental/regrid.py index ef949ffcd1..5db46cf1a2 100644 --- a/lib/iris/experimental/regrid.py +++ b/lib/iris/experimental/regrid.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip from collections import namedtuple import copy diff --git a/lib/iris/experimental/regrid_conservative.py b/lib/iris/experimental/regrid_conservative.py index 7407cd3a16..4aac938433 100644 --- a/lib/iris/experimental/regrid_conservative.py +++ b/lib/iris/experimental/regrid_conservative.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import ESMF via iris.proxy, just so we can build the docs with no ESMF. import iris.proxy @@ -219,8 +220,8 @@ def _valid_units(coord): fullcube_data = np.ma.zeros(dst_shape) # Iterate 2d slices over all possible indices of the 'other' dimensions - all_other_dims = filter(lambda i_dim: i_dim not in src_dims_xy, - xrange(source_cube.ndim)) + all_other_dims = [i_dim for i_dim in range(source_cube.ndim) + if i_dim not in src_dims_xy] all_combinations_of_other_inds = np.ndindex(*dst_shape[all_other_dims]) for other_indices in all_combinations_of_other_inds: # Construct a tuple of slices to address the 2d xy field diff --git a/lib/iris/experimental/um.py b/lib/iris/experimental/um.py index 199a53b08c..55573dff10 100644 --- a/lib/iris/experimental/um.py +++ b/lib/iris/experimental/um.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip from contextlib import contextmanager import os diff --git a/lib/iris/fileformats/_pyke_rules/fc_rules_cf.krb b/lib/iris/fileformats/_pyke_rules/fc_rules_cf.krb index 662d52ac84..0b6d1c4701 100644 --- a/lib/iris/fileformats/_pyke_rules/fc_rules_cf.krb +++ b/lib/iris/fileformats/_pyke_rules/fc_rules_cf.krb @@ -1188,7 +1188,8 @@ fc_extras # Determine the name of the dimension/s shared between the CF-netCDF data variable # and the coordinate being built. - common_dims = filter(lambda dim: dim in cf_var.dimensions, cf_coord_var.dimensions) + common_dims = [dim for dim in cf_coord_var.dimensions + if dim in cf_var.dimensions] data_dims = None if common_dims: # Calculate the offset of each common dimension. @@ -1281,7 +1282,8 @@ fc_extras # Determine the name of the dimension/s shared between the CF-netCDF data variable # and the coordinate being built. - common_dims = filter(lambda dim: dim in cf_var.dimensions, cf_coord_var.dimensions) + common_dims = [dim for dim in cf_coord_var.dimensions + if dim in cf_var.dimensions] data_dims = None if common_dims: # Calculate the offset of each common dimension. diff --git a/lib/iris/fileformats/_structured_array_identification.py b/lib/iris/fileformats/_structured_array_identification.py index 197b97d322..f3302097fe 100644 --- a/lib/iris/fileformats/_structured_array_identification.py +++ b/lib/iris/fileformats/_structured_array_identification.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -28,7 +28,7 @@ >>> import numpy as np >>> orig_x, orig_y = np.arange(2), np.arange(3) - >>> x, y = np.meshgrid(range(2), range(3)) + >>> x, y = np.meshgrid(orig_x, orig_y) >>> # Remove the dimensional structure from the arrays. >>> x, y = x.flatten(), y.flatten() @@ -55,6 +55,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range from collections import namedtuple diff --git a/lib/iris/fileformats/ff.py b/lib/iris/fileformats/ff.py index 589e7c4470..525870339a 100644 --- a/lib/iris/fileformats/ff.py +++ b/lib/iris/fileformats/ff.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range import os import warnings diff --git a/lib/iris/fileformats/name_loaders.py b/lib/iris/fileformats/name_loaders.py index 1ba0332d0e..ff29e36df0 100644 --- a/lib/iris/fileformats/name_loaders.py +++ b/lib/iris/fileformats/name_loaders.py @@ -17,10 +17,10 @@ """NAME file format loading functions.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip import collections import datetime -from itertools import izip import re import warnings @@ -844,7 +844,7 @@ def load_NAMEIII_trajectory(filename): # Every column up to Z becomes a coordinate. coords = [] - for name, values in izip(headings[:z_column+1], columns[:z_column+1]): + for name, values in zip(headings[:z_column+1], columns[:z_column+1]): values = np.array(values) if np.all(np.array(values) == values[0]): values = [values[0]] @@ -883,7 +883,7 @@ def load_NAMEIII_trajectory(filename): coords.append(coord) # Every numerical column after the Z becomes a cube. - for name, values in izip(headings[z_column+1:], columns[z_column+1:]): + for name, values in zip(headings[z_column+1:], columns[z_column+1:]): try: float(values[0]) except ValueError: diff --git a/lib/iris/fileformats/netcdf.py b/lib/iris/fileformats/netcdf.py index 9d431a7f35..65fa52e0e5 100644 --- a/lib/iris/fileformats/netcdf.py +++ b/lib/iris/fileformats/netcdf.py @@ -25,9 +25,9 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, range import collections -import itertools import os import os.path import string @@ -405,12 +405,12 @@ def _load_cube(engine, cf, cf_var, filename): attribute_predicate = lambda item: item[0] not in _CF_ATTRS for coord, cf_var_name in coordinates: - tmpvar = itertools.ifilter(attribute_predicate, - cf.cf_group[cf_var_name].cf_attrs_unused()) + tmpvar = filter(attribute_predicate, + cf.cf_group[cf_var_name].cf_attrs_unused()) for attr_name, attr_value in tmpvar: _set_attributes(coord.attributes, attr_name, attr_value) - tmpvar = itertools.ifilter(attribute_predicate, cf_var.cf_attrs_unused()) + tmpvar = filter(attribute_predicate, cf_var.cf_attrs_unused()) # Attach untouched attributes of the associated CF-netCDF data variable to # the cube. for attr_name, attr_value in tmpvar: @@ -1015,7 +1015,7 @@ def _get_dim_names(self, cube): """ dimension_names = [] - for dim in xrange(cube.ndim): + for dim in range(cube.ndim): coords = cube.coords(dimensions=dim, dim_coords=True) if coords: coord = coords[0] diff --git a/lib/iris/fileformats/pp.py b/lib/iris/fileformats/pp.py index c1968ea19b..6eff0d7629 100644 --- a/lib/iris/fileformats/pp.py +++ b/lib/iris/fileformats/pp.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip import abc import collections @@ -658,7 +659,7 @@ class _FlagMetaclass(type): NUM_BITS = 18 def __new__(cls, classname, bases, class_dict): - for i in xrange(cls.NUM_BITS): + for i in range(cls.NUM_BITS): value = 2 ** i name = 'flag{}'.format(value) class_dict[name] = property(_make_flag_getter(value), @@ -794,7 +795,7 @@ def __str__(self): def flags(self): warnings.warn('The `flags` attribute is deprecated - please use ' 'integer bitwise operators instead.') - return tuple(2 ** i for i in xrange(self.NUM_BITS) + return tuple(2 ** i for i in range(self.NUM_BITS) if self._value & 2 ** i) @@ -1132,7 +1133,7 @@ def __repr__(self): # With the attributes sorted the order will remain stable if extra attributes are added. public_attribute_names = list(attribute_priority_lookup.keys()) + list(EXTRA_DATA.values()) self_attrs = [(name, getattr(self, name, None)) for name in public_attribute_names] - self_attrs = filter(lambda pair: pair[1] is not None, self_attrs) + self_attrs = [pair for pair in self_attrs if pair[1] is not None] # Output any masked data as separate `data` and `mask` # components, to avoid the standard MaskedArray output diff --git a/lib/iris/fileformats/pp_rules.py b/lib/iris/fileformats/pp_rules.py index aa7c17e01b..970133413a 100644 --- a/lib/iris/fileformats/pp_rules.py +++ b/lib/iris/fileformats/pp_rules.py @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import range # Historically this was auto-generated from # SciTools/iris-code-generators:tools/gen_rules.py diff --git a/lib/iris/fileformats/rules.py b/lib/iris/fileformats/rules.py index a7c4b5a1af..4e37d78609 100644 --- a/lib/iris/fileformats/rules.py +++ b/lib/iris/fileformats/rules.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter import abc import collections @@ -704,7 +705,7 @@ def _ensure_aligned(regrid_cache, src_cube, target_cube): # ensure each target coord is either a scalar or maps to a # single, distinct dimension. target_dims = [target_cube.coord_dims(coord) for coord in target_coords] - target_dims = filter(None, target_dims) + target_dims = list(filter(None, target_dims)) unique_dims = set() for dims in target_dims: unique_dims.update(dims) diff --git a/lib/iris/io/__init__.py b/lib/iris/io/__init__.py index 291e4e1086..caa666a754 100644 --- a/lib/iris/io/__init__.py +++ b/lib/iris/io/__init__.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import map import glob import os.path diff --git a/lib/iris/iterate.py b/lib/iris/iterate.py index 762d246bc5..ffc0a2bebc 100644 --- a/lib/iris/iterate.py +++ b/lib/iris/iterate.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip import collections import itertools @@ -95,7 +96,7 @@ def izip(*cubes, **kwargs): # For each input cube, generate the union of all describing dimensions for # the resulting subcube. requested_dims_by_cube = [] - for coords, cube in itertools.izip(coords_by_cube, cubes): + for coords, cube in zip(coords_by_cube, cubes): requested_dims = set() for coord in coords: requested_dims.update(cube.coord_dims(coord)) @@ -115,10 +116,10 @@ def izip(*cubes, **kwargs): # dimensioned coordinates that will be iterated over (i.e exclude slice # coords). dimensioned_iter_coords_by_cube = [] - for requested_dims, cube in itertools.izip(requested_dims_by_cube, cubes): + for requested_dims, cube in zip(requested_dims_by_cube, cubes): dimensioned_iter_coords = set() # Loop over dimensioned coords in each cube. - for dim in xrange(len(cube.shape)): + for dim in range(len(cube.shape)): if dim not in requested_dims: dimensioned_iter_coords.update( cube.coords(contains_dimension=dim)) @@ -195,8 +196,7 @@ def __init__(self, cubes, requested_dims_by_cube, ordered, coords_by_cube): master_dimensioned_coord_list = [] master_dims_index = [] self._offsets_by_cube = [] - for requested_dims, cube in itertools.izip(requested_dims_by_cube, - cubes): + for requested_dims, cube in zip(requested_dims_by_cube, cubes): # Create a list of the shape of each cube, and set the dimensions # which have been requested to length 1. dims_index = list(cube.shape) @@ -204,7 +204,7 @@ def __init__(self, cubes, requested_dims_by_cube, ordered, coords_by_cube): dims_index[dim] = 1 offsets = [] # Loop over dimensions in each cube. - for i in xrange(len(cube.shape)): + for i in range(len(cube.shape)): # Obtain the coordinates for this dimension. cube_coords = cube.coords(dimensions=i) found = False @@ -247,7 +247,7 @@ def next(self): master_index_tuple = next(self._ndindex) subcubes = [] - for offsets, requested_dims, coords, cube in itertools.izip( + for offsets, requested_dims, coords, cube in zip( self._offsets_by_cube, self._requested_dims_by_cube, self._coords_by_cube, self._cubes): # Extract the index_list for each cube from the master index using @@ -265,7 +265,7 @@ def next(self): transpose_order = [] for coord in coords: transpose_order += sorted(subcube.coord_dims(coord)) - if transpose_order != range(subcube.ndim): + if transpose_order != list(range(subcube.ndim)): subcube.transpose(transpose_order) subcubes.append(subcube) diff --git a/lib/iris/palette.py b/lib/iris/palette.py index d6358bd156..dafddea6f6 100644 --- a/lib/iris/palette.py +++ b/lib/iris/palette.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter from functools import wraps import os diff --git a/lib/iris/plot.py b/lib/iris/plot.py index c1d58db482..b655fdc826 100644 --- a/lib/iris/plot.py +++ b/lib/iris/plot.py @@ -23,6 +23,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import map, zip import collections import datetime @@ -57,7 +58,7 @@ def _get_plot_defn_custom_coords_picked(cube, coords, mode, ndims=2): def as_coord(coord): coord = cube.coord(coord) return coord - coords = map(as_coord, coords) + coords = list(map(as_coord, coords)) # Check that we were given the right number of coordinates if len(coords) != ndims: @@ -69,7 +70,7 @@ def as_coord(coord): # Check which dimensions are spanned by each coordinate. get_span = lambda coord: set(cube.coord_dims(coord)) - spans = map(get_span, coords) + spans = list(map(get_span, coords)) for span, coord in zip(spans, coords): if not span: msg = 'The coordinate {!r} doesn\'t span a data dimension.' @@ -129,7 +130,7 @@ def _get_plot_defn(cube, mode, ndims=2): # When appropriate, restrict to 1D with bounds. if mode == iris.coords.BOUND_MODE: - coords = map(_valid_bound_coord, coords) + coords = list(map(_valid_bound_coord, coords)) def guess_axis(coord): axis = None @@ -141,9 +142,8 @@ def guess_axis(coord): for dim, coord in enumerate(coords): if coord is None: aux_coords = cube.coords(dimensions=dim) - aux_coords = filter(lambda coord: - isinstance(coord, iris.coords.DimCoord), - aux_coords) + aux_coords = [coord for coord in aux_coords + if isinstance(coord, iris.coords.DimCoord)] if aux_coords: key_func = lambda coord: coord._as_defn() aux_coords.sort(key=key_func) @@ -154,7 +154,7 @@ def guess_axis(coord): # along the Z axis. This results in a preference for using the # derived altitude over model_level_number or level_height. # Limit to Z axis to avoid preferring latitude over grid_latitude etc. - axes = map(guess_axis, coords) + axes = list(map(guess_axis, coords)) axis = 'Z' if axis in axes: for coord in cube.coords(dim_coords=False): diff --git a/lib/iris/tests/__init__.py b/lib/iris/tests/__init__.py index e6b34024f2..ee97ec79bc 100644 --- a/lib/iris/tests/__init__.py +++ b/lib/iris/tests/__init__.py @@ -31,6 +31,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import map import collections import contextlib @@ -288,7 +289,7 @@ def assertCDL(self, netcdf_filename, reference_filename=None, flags='-h'): elif isinstance(flags, basestring): flags = flags.split() else: - flags = map(str, flags) + flags = list(map(str, flags)) with open(cdl_filename, 'w') as cdl_file: subprocess.check_call(['ncdump'] + flags + [netcdf_filename], @@ -379,9 +380,11 @@ def assertCubeDataAlmostEqual(self, cube, reference_filename, *args, **kwargs): if isinstance(cube.data, ma.MaskedArray): # Avoid recording any non-initialised array data. data = cube.data.filled() - np.savez(file(reference_path, 'wb'), data=data, mask=cube.data.mask) + with open(reference_path, 'wb') as reference_file: + np.savez(reference_file, data=data, mask=cube.data.mask) else: - np.save(file(reference_path, 'wb'), cube.data) + with open(reference_path, 'wb') as reference_file: + np.save(weference_file, cube.data) def assertFilesEqual(self, test_filename, reference_filename): reference_path = get_result_path(reference_filename) diff --git a/lib/iris/tests/analysis/test_interpolate.py b/lib/iris/tests/analysis/test_interpolate.py index 2113e629d7..dd33a5dff4 100644 --- a/lib/iris/tests/analysis/test_interpolate.py +++ b/lib/iris/tests/analysis/test_interpolate.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -46,7 +46,7 @@ def _create_cube(self, longitudes): def test_symmetric(self): # Check we can interpolate from a Cube defined over [-180, 180). cube = self._create_cube([-180, -90, 0, 90]) - samples = [('longitude', range(-360, 720, 45))] + samples = [('longitude', np.arange(-360, 720, 45))] result = interpolate.linear(cube, samples, extrapolation_mode='nan') normalise_order(result) self.assertCMLApproxData(result, ('analysis', 'interpolation', @@ -56,7 +56,7 @@ def test_symmetric(self): def test_positive(self): # Check we can interpolate from a Cube defined over [0, 360). cube = self._create_cube([0, 90, 180, 270]) - samples = [('longitude', range(-360, 720, 45))] + samples = [('longitude', np.arange(-360, 720, 45))] result = interpolate.linear(cube, samples, extrapolation_mode='nan') normalise_order(result) self.assertCMLApproxData(result, ('analysis', 'interpolation', diff --git a/lib/iris/tests/experimental/regrid/test_regrid_area_weighted_rectilinear_src_and_grid.py b/lib/iris/tests/experimental/regrid/test_regrid_area_weighted_rectilinear_src_and_grid.py index 68b0453f32..7e88812686 100644 --- a/lib/iris/tests/experimental/regrid/test_regrid_area_weighted_rectilinear_src_and_grid.py +++ b/lib/iris/tests/experimental/regrid/test_regrid_area_weighted_rectilinear_src_and_grid.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised # before importing anything else. diff --git a/lib/iris/tests/experimental/test_animate.py b/lib/iris/tests/experimental/test_animate.py index a6cda843cf..6df5b2d8cf 100644 --- a/lib/iris/tests/experimental/test_animate.py +++ b/lib/iris/tests/experimental/test_animate.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -20,13 +20,12 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before # importing anything else import iris.tests as tests -import itertools - import numpy as np import iris @@ -75,7 +74,7 @@ def test_cube_animation(self): ani = [ani] # Extract frame data - for data in itertools.izip(*[a.new_saved_frame_seq() for a in ani]): + for data in zip(*[a.new_saved_frame_seq() for a in ani]): # Draw each frame for anim, d in zip(ani, data): anim._draw_next_frame(d, blit=False) diff --git a/lib/iris/tests/integration/concatenate/test_concatenate.py b/lib/iris/tests/integration/concatenate/test_concatenate.py index 7d9336a888..b158216126 100644 --- a/lib/iris/tests/integration/concatenate/test_concatenate.py +++ b/lib/iris/tests/integration/concatenate/test_concatenate.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised # before importing anything else. diff --git a/lib/iris/tests/integration/test_FieldsFileVariant.py b/lib/iris/tests/integration/test_FieldsFileVariant.py index e649c3de92..39d21e5d19 100644 --- a/lib/iris/tests/integration/test_FieldsFileVariant.py +++ b/lib/iris/tests/integration/test_FieldsFileVariant.py @@ -17,6 +17,7 @@ """Integration tests for loading UM FieldsFile variants.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -497,7 +498,7 @@ def test_create(self): ints[20] = 0 # LBPACK ints[21] = 2 # LBREL ints[38] = 1 # LBUSER(1) - reals = range(19) + reals = list(range(19)) src_data = np.arange(20, dtype='f4').reshape((4, 5)) ffv.fields = [Field2(ints, reals, src_data)] ffv.close() diff --git a/lib/iris/tests/results/cdm/str_repr/simple.__str__.txt b/lib/iris/tests/results/cdm/str_repr/simple.__str__.txt index 442f0928ab..b174d346d2 100644 --- a/lib/iris/tests/results/cdm/str_repr/simple.__str__.txt +++ b/lib/iris/tests/results/cdm/str_repr/simple.__str__.txt @@ -1,6 +1,6 @@ -thingness (foo: 11) +thingness (foo: 11) Dimension coordinates: - foo x + foo x Auxiliary coordinates: - This is a really, really, really long long_name that requires to be clipped... x - This is a short long_name x \ No newline at end of file + This is a really, really, really, really long long_name that must be clipped... x + This is a short long_name x \ No newline at end of file diff --git a/lib/iris/tests/stock.py b/lib/iris/tests/stock.py index 6418c1e7f5..0c22dd6a80 100644 --- a/lib/iris/tests/stock.py +++ b/lib/iris/tests/stock.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip import os.path diff --git a/lib/iris/tests/test_aggregate_by.py b/lib/iris/tests/test_aggregate_by.py index 67c2022f15..17e2f153ec 100644 --- a/lib/iris/tests/test_aggregate_by.py +++ b/lib/iris/tests/test_aggregate_by.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -63,7 +63,7 @@ def setUp(self): long_name='height', units='m') - model_level = iris.coords.DimCoord(range(z_points.size), + model_level = iris.coords.DimCoord(np.arange(z_points.size), standard_name='model_level_number') self.cube_single.add_aux_coord(self.coord_z_single, 0) @@ -94,7 +94,7 @@ def setUp(self): long_name='level', units='1') - model_level = iris.coords.DimCoord(range(z1_points.size), + model_level = iris.coords.DimCoord(np.arange(z1_points.size), standard_name='model_level_number') self.cube_multi.add_aux_coord(self.coord_z1_multi, 0) diff --git a/lib/iris/tests/test_analysis.py b/lib/iris/tests/test_analysis.py index b7ea785f91..38fbd3ffcf 100644 --- a/lib/iris/tests/test_analysis.py +++ b/lib/iris/tests/test_analysis.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -17,12 +17,11 @@ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests -import itertools - import cartopy.crs as ccrs import numpy as np import numpy.ma as ma @@ -1065,7 +1064,7 @@ def test_cartopy_projection(self): # Set up figure fig = plt.figure(figsize=(10, 10)) gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=3, hspace=1.5, wspace=0.5) - for subplot_spec, (name, target_proj) in itertools.izip(gs, projections.iteritems()): + for subplot_spec, (name, target_proj) in zip(gs, projections.iteritems()): # Set up axes and title ax = plt.subplot(subplot_spec, frameon=False, projection=target_proj) ax.set_title(name) diff --git a/lib/iris/tests/test_basic_maths.py b/lib/iris/tests/test_basic_maths.py index 408288d151..7fd3f100e4 100644 --- a/lib/iris/tests/test_basic_maths.py +++ b/lib/iris/tests/test_basic_maths.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -122,8 +122,10 @@ def test_minus_coord(self): xdim = a.ndim-1 ydim = a.ndim-2 - c_x = iris.coords.DimCoord(points=range(a.shape[xdim]), long_name='x_coord', units=self.cube.units) - c_y = iris.coords.AuxCoord(points=range(a.shape[ydim]), long_name='y_coord', units=self.cube.units) + c_x = iris.coords.DimCoord(points=np.arange(a.shape[xdim]), + long_name='x_coord', units=self.cube.units) + c_y = iris.coords.AuxCoord(points=np.arange(a.shape[ydim]), + long_name='y_coord', units=self.cube.units) self.assertCML(a, ('analysis', 'maths_original.cml')) @@ -152,8 +154,10 @@ def test_addition_coord(self): xdim = a.ndim-1 ydim = a.ndim-2 - c_x = iris.coords.DimCoord(points=range(a.shape[xdim]), long_name='x_coord', units=self.cube.units) - c_y = iris.coords.AuxCoord(points=range(a.shape[ydim]), long_name='y_coord', units=self.cube.units) + c_x = iris.coords.DimCoord(points=np.arange(a.shape[xdim]), + long_name='x_coord', units=self.cube.units) + c_y = iris.coords.AuxCoord(points=np.arange(a.shape[ydim]), + long_name='y_coord', units=self.cube.units) self.assertCML(a, ('analysis', 'maths_original.cml')) @@ -187,8 +191,12 @@ def test_addition_fail(self): xdim = a.ndim-1 ydim = a.ndim-2 - c_axis_length_fail = iris.coords.DimCoord(points=range(a.shape[ydim]), long_name='x_coord', units=self.cube.units) - c_unit_fail = iris.coords.AuxCoord(points=range(a.shape[xdim]), long_name='x_coord', units='volts') + c_axis_length_fail = iris.coords.DimCoord( + points=np.arange(a.shape[ydim]), + long_name='x_coord', + units=self.cube.units) + c_unit_fail = iris.coords.AuxCoord(points=np.arange(a.shape[xdim]), + long_name='x_coord', units='volts') self.assertRaises(ValueError, iris.analysis.maths.add, a, c_axis_length_fail) self.assertRaises(iris.exceptions.NotYetImplementedError, iris.analysis.maths.add, a, c_unit_fail) diff --git a/lib/iris/tests/test_cdm.py b/lib/iris/tests/test_cdm.py index 44aee5ae69..f4434d54de 100644 --- a/lib/iris/tests/test_cdm.py +++ b/lib/iris/tests/test_cdm.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -338,9 +338,13 @@ def test_cube_summary_cell_methods(self): def test_cube_summary_alignment(self): # Test the cube summary dimension alignment and coord name clipping cube = iris.tests.stock.simple_1d() - aux = iris.coords.AuxCoord(range(11), long_name='This is a really, really, really long long_name that requires to be clipped because it is too long') + aux = iris.coords.AuxCoord( + np.arange(11), + long_name='This is a really, really, really, really long ' + 'long_name that must be clipped because it is too long') cube.add_aux_coord(aux, 0) - aux = iris.coords.AuxCoord(range(11), long_name='This is a short long_name') + aux = iris.coords.AuxCoord(np.arange(11), + long_name='This is a short long_name') cube.add_aux_coord(aux, 0) self.assertString(str(cube), ('cdm', 'str_repr', 'simple.__str__.txt')) diff --git a/lib/iris/tests/test_constraints.py b/lib/iris/tests/test_constraints.py index 340f6e2875..94a817c2d4 100644 --- a/lib/iris/tests/test_constraints.py +++ b/lib/iris/tests/test_constraints.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests diff --git a/lib/iris/tests/test_coord_api.py b/lib/iris/tests/test_coord_api.py index c5432db811..8f5f89e8b6 100644 --- a/lib/iris/tests/test_coord_api.py +++ b/lib/iris/tests/test_coord_api.py @@ -17,6 +17,7 @@ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests @@ -275,32 +276,41 @@ def test_AuxCoord_str(self): class TestAuxCoordCreation(unittest.TestCase): def test_basic(self): - a = iris.coords.AuxCoord(range(10), 'air_temperature', units='kelvin') + a = iris.coords.AuxCoord(np.arange(10), 'air_temperature', + units='kelvin') result = "AuxCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), standard_name='air_temperature', units=Unit('kelvin'))" self.assertEqual(result, str(a)) - b = iris.coords.AuxCoord(range(10), attributes={'monty': 'python'}) + b = iris.coords.AuxCoord(list(range(10)), + attributes={'monty': 'python'}) result = "AuxCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), standard_name=None, units=Unit('1'), attributes={'monty': 'python'})" self.assertEqual(result, str(b)) def test_excluded_attributes(self): with self.assertRaises(ValueError): - iris.coords.AuxCoord(range(10), 'air_temperature', units='kelvin', attributes={'standard_name': 'whoopsy'}) + iris.coords.AuxCoord(np.arange(10), 'air_temperature', + units='kelvin', + attributes={'standard_name': 'whoopsy'}) - a = iris.coords.AuxCoord(range(10), 'air_temperature', units='kelvin') + a = iris.coords.AuxCoord(np.arange(10), 'air_temperature', + units='kelvin') with self.assertRaises(ValueError): a.attributes['standard_name'] = 'whoopsy' with self.assertRaises(ValueError): a.attributes.update({'standard_name': 'whoopsy'}) def test_coord_system(self): - a = iris.coords.AuxCoord(range(10), 'air_temperature', units='kelvin', coord_system=iris.coord_systems.GeogCS(6000)) + a = iris.coords.AuxCoord(np.arange(10), 'air_temperature', + units='kelvin', + coord_system=iris.coord_systems.GeogCS(6000)) result = "AuxCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), standard_name='air_temperature', units=Unit('kelvin'), "\ "coord_system=GeogCS(6000.0))" self.assertEqual(result, str(a)) def test_bounded(self): - a = iris.coords.AuxCoord(range(10), 'air_temperature', units='kelvin', bounds=np.arange(0, 20).reshape(10, 2)) + a = iris.coords.AuxCoord(np.arange(10), 'air_temperature', + units='kelvin', + bounds=np.arange(0, 20).reshape(10, 2)) result = ("AuxCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])" ", bounds=array([[ 0, 1],\n [ 2, 3],\n [ 4, 5],\n [ 6, 7],\n [ 8, 9],\n "\ "[10, 11],\n [12, 13],\n [14, 15],\n [16, 17],\n [18, 19]])" @@ -324,32 +334,41 @@ def test_AuxCoord_fromcoord(self): class TestDimCoordCreation(unittest.TestCase): def test_basic(self): - a = iris.coords.DimCoord(range(10), 'air_temperature', units='kelvin') + a = iris.coords.DimCoord(np.arange(10), 'air_temperature', + units='kelvin') result = "DimCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), standard_name='air_temperature', units=Unit('kelvin'))" self.assertEqual(result, str(a)) - b = iris.coords.DimCoord(range(10), attributes={'monty': 'python'}) + b = iris.coords.DimCoord(list(range(10)), + attributes={'monty': 'python'}) result = "DimCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), standard_name=None, units=Unit('1'), attributes={'monty': 'python'})" self.assertEqual(result, str(b)) def test_excluded_attributes(self): with self.assertRaises(ValueError): - iris.coords.DimCoord(range(10), 'air_temperature', units='kelvin', attributes={'standard_name': 'whoopsy'}) + iris.coords.DimCoord(np.arange(10), 'air_temperature', + units='kelvin', + attributes={'standard_name': 'whoopsy'}) - a = iris.coords.DimCoord(range(10), 'air_temperature', units='kelvin') + a = iris.coords.DimCoord(np.arange(10), 'air_temperature', + units='kelvin') with self.assertRaises(ValueError): a.attributes['standard_name'] = 'whoopsy' with self.assertRaises(ValueError): a.attributes.update({'standard_name': 'whoopsy'}) def test_coord_system(self): - a = iris.coords.DimCoord(range(10), 'air_temperature', units='kelvin', coord_system=iris.coord_systems.GeogCS(6000)) + a = iris.coords.DimCoord(np.arange(10), 'air_temperature', + units='kelvin', + coord_system=iris.coord_systems.GeogCS(6000)) result = "DimCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), standard_name='air_temperature', units=Unit('kelvin'), "\ "coord_system=GeogCS(6000.0))" self.assertEqual(result, str(a)) def test_bounded(self): - a = iris.coords.DimCoord(range(10), 'air_temperature', units='kelvin', bounds=np.arange(0, 20).reshape(10, 2)) + a = iris.coords.DimCoord(np.arange(10), 'air_temperature', + units='kelvin', + bounds=np.arange(0, 20).reshape(10, 2)) result = ("DimCoord(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])" ", bounds=array([[ 0, 1],\n [ 2, 3],\n [ 4, 5],\n [ 6, 7],\n [ 8, 9],\n "\ "[10, 11],\n [12, 13],\n [14, 15],\n [16, 17],\n [18, 19]])" @@ -388,7 +407,7 @@ def test_DimCoord_equality(self): self.assertNotEqual(b, d) def test_Dim_to_Aux(self): - a = iris.coords.DimCoord(range(10), standard_name='air_temperature', long_name='custom air temp', + a = iris.coords.DimCoord(np.arange(10), standard_name='air_temperature', long_name='custom air temp', units='kelvin', attributes={'monty': 'python'}, bounds=np.arange(20).reshape(10, 2), circular=True) b = iris.coords.AuxCoord.from_coord(a) @@ -545,7 +564,7 @@ def create_1d_coord(self, bounds=None, points=None, units='meter'): return coord def test_explicit(self): - orig_coord = self.create_1d_coord(points=range(10), + orig_coord = self.create_1d_coord(points=list(range(10)), bounds=[(b, b+1) for b in range(10)]) coord_expected = self.create_1d_coord(points=5, bounds=[(0, 10)]) @@ -611,7 +630,7 @@ def test_get_set_points_and_bounds(self): # set bounds from non-numpy pairs coord._points = None # reset the undelying shape of the coordinate - coord.points = range(3) + coord.points = list(range(3)) coord.bounds = [[123, 456], [234, 567], [345, 678]] self.assertEqual(coord.shape, (3, )) self.assertEqual(coord.bounds.shape, (3, 2)) diff --git a/lib/iris/tests/test_cube_to_pp.py b/lib/iris/tests/test_cube_to_pp.py index f67fd27e58..74af8d03d8 100644 --- a/lib/iris/tests/test_cube_to_pp.py +++ b/lib/iris/tests/test_cube_to_pp.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests diff --git a/lib/iris/tests/test_ff.py b/lib/iris/tests/test_ff.py index e9c5aca57f..8f0f8bb728 100644 --- a/lib/iris/tests/test_ff.py +++ b/lib/iris/tests/test_ff.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before # importing anything else diff --git a/lib/iris/tests/test_iterate.py b/lib/iris/tests/test_iterate.py index d25b3915bd..ade8cc8be5 100644 --- a/lib/iris/tests/test_iterate.py +++ b/lib/iris/tests/test_iterate.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -211,7 +212,7 @@ def test_izip_same_cube_no_coords(self): self.assertEqual(count, nslices) def test_izip_subcube_of_same(self): - for _ in xrange(3): + for _ in range(3): super_cube = self.cube_a # Random int to pick coord value to calc subcube k = random.randint(0, super_cube.shape[0]-1) @@ -253,7 +254,7 @@ def test_izip_same_dims(self): self.assertEqual(count, nslices) # Two coords nslices = self.cube_a.shape[0] - i_iterator = iter(xrange(self.cube_a.shape[0])) + i_iterator = iter(range(self.cube_a.shape[0])) count = 0 for slice_a, slice_b in iris.iterate.izip(self.cube_a, self.cube_b, coords=self.coord_names): diff --git a/lib/iris/tests/test_mapping.py b/lib/iris/tests/test_mapping.py index cb5092f129..35f19ef4f6 100644 --- a/lib/iris/tests/test_mapping.py +++ b/lib/iris/tests/test_mapping.py @@ -19,6 +19,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -156,7 +157,7 @@ class TestLowLevel(tests.GraphicsTest): def setUp(self): self.cube = iris.tests.stock.global_pp() self.few = 4 - self.few_levels = range(280, 300, 5) + self.few_levels = list(range(280, 300, 5)) self.many_levels = np.linspace( self.cube.data.min(), self.cube.data.max(), 40) diff --git a/lib/iris/tests/test_merge.py b/lib/iris/tests/test_merge.py index d2ea102a1a..02cea278bf 100644 --- a/lib/iris/tests/test_merge.py +++ b/lib/iris/tests/test_merge.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests diff --git a/lib/iris/tests/test_peak.py b/lib/iris/tests/test_peak.py index 53d18ce8d1..627bf241c9 100644 --- a/lib/iris/tests/test_peak.py +++ b/lib/iris/tests/test_peak.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -40,7 +40,7 @@ def test_peak_coord_length_1(self): def test_peak_coord_length_2(self): # Coordinate contains 2 points. - latitude = iris.coords.DimCoord(range(0, 2, 1), + latitude = iris.coords.DimCoord(np.arange(0, 2, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2]), @@ -54,7 +54,7 @@ def test_peak_coord_length_2(self): def test_peak_coord_length_3(self): # Coordinate contains 3 points. - latitude = iris.coords.DimCoord(range(0, 3, 1), + latitude = iris.coords.DimCoord(np.arange(0, 3, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2, 1]), @@ -68,7 +68,7 @@ def test_peak_coord_length_3(self): def test_peak_1d(self): # Collapse a 1d cube. - latitude = iris.coords.DimCoord(range(0, 11, 1), + latitude = iris.coords.DimCoord(np.arange(0, 11, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]), @@ -82,7 +82,7 @@ def test_peak_1d(self): def test_peak_duplicate_coords(self): # Collapse cube along 2 coordinates (both the same). - latitude = iris.coords.DimCoord(range(0, 4, 1), + latitude = iris.coords.DimCoord(np.arange(0, 4, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2, 3, 1]), @@ -101,10 +101,10 @@ def test_peak_duplicate_coords(self): def test_peak_2d(self): # Collapse a 2d cube. - longitude = iris.coords.DimCoord(range(0, 4, 1), + longitude = iris.coords.DimCoord(np.arange(0, 4, 1), standard_name='longitude', units='degrees') - latitude = iris.coords.DimCoord(range(0, 3, 1), + latitude = iris.coords.DimCoord(np.arange(0, 3, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([[1, 2, 3, 1], [4, 5, 7, 4], @@ -138,7 +138,7 @@ def test_peak_2d(self): def test_peak_without_peak_value(self): # No peak in column (values equal). - latitude = iris.coords.DimCoord(range(0, 4, 1), + latitude = iris.coords.DimCoord(np.arange(0, 4, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 1, 1, 1]), @@ -152,7 +152,7 @@ def test_peak_without_peak_value(self): def test_peak_with_nan(self): # Single nan in column. - latitude = iris.coords.DimCoord(range(0, 5, 1), + latitude = iris.coords.DimCoord(np.arange(0, 5, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 4, 2, 3, 1], dtype=np.float32), @@ -176,7 +176,7 @@ def test_peak_with_nan(self): def test_peak_with_mask(self): # Single value in column masked. - latitude = iris.coords.DimCoord(range(0, 5, 1), + latitude = iris.coords.DimCoord(np.arange(0, 5, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(ma.array([1, 4, 2, 3, 2], dtype=np.float32), @@ -203,7 +203,7 @@ def test_peak_with_mask(self): def test_peak_with_nan_and_mask(self): # Single nan in column with single value masked. - latitude = iris.coords.DimCoord(range(0, 5, 1), + latitude = iris.coords.DimCoord(np.arange(0, 5, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(ma.array([1, 4, 2, 3, 1], dtype=np.float32), @@ -230,7 +230,7 @@ def test_peak_with_nan_and_mask(self): def test_peak_against_max(self): # Cube with data that infers a peak value greater than the column max. - latitude = iris.coords.DimCoord(range(0, 7, 1), + latitude = iris.coords.DimCoord(np.arange(0, 7, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([0, 1, 3, 7, 7, 4, 2], diff --git a/lib/iris/tests/test_pickling.py b/lib/iris/tests/test_pickling.py index 0890689aa4..d31cca1292 100644 --- a/lib/iris/tests/test_pickling.py +++ b/lib/iris/tests/test_pickling.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests @@ -35,7 +36,7 @@ class TestPickle(tests.IrisTest): def pickle_then_unpickle(self, obj): """Returns a generator of ("cpickle protocol number", object) tuples.""" - for protocol in xrange(1 + cPickle.HIGHEST_PROTOCOL): + for protocol in range(1 + cPickle.HIGHEST_PROTOCOL): bio = io.BytesIO() cPickle.dump(obj, bio, protocol) diff --git a/lib/iris/tests/test_plot.py b/lib/iris/tests/test_plot.py index 4e8d2e5c43..bf554d27c4 100644 --- a/lib/iris/tests/test_plot.py +++ b/lib/iris/tests/test_plot.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -856,8 +857,10 @@ def test_yx_order(self): @tests.skip_plot class TestSymbols(tests.GraphicsTest): def test_cloud_cover(self): - iplt.symbols(range(10), [0] * 10, [iris.symbols.CLOUD_COVER[i] - for i in range(10)], 0.375) + iplt.symbols(list(range(10)), + [0] * 10, + [iris.symbols.CLOUD_COVER[i] for i in range(10)], + 0.375) iplt.plt.axis('off') self.check_graphic() diff --git a/lib/iris/tests/test_pp_module.py b/lib/iris/tests/test_pp_module.py index 3e25b00790..3e25cb839d 100644 --- a/lib/iris/tests/test_pp_module.py +++ b/lib/iris/tests/test_pp_module.py @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests diff --git a/lib/iris/tests/test_pp_to_cube.py b/lib/iris/tests/test_pp_to_cube.py index 617ed77c03..824da11721 100644 --- a/lib/iris/tests/test_pp_to_cube.py +++ b/lib/iris/tests/test_pp_to_cube.py @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests diff --git a/lib/iris/tests/test_rules.py b/lib/iris/tests/test_rules.py index f08d7b8932..0d4ad343bb 100644 --- a/lib/iris/tests/test_rules.py +++ b/lib/iris/tests/test_rules.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests diff --git a/lib/iris/tests/test_trajectory.py b/lib/iris/tests/test_trajectory.py index b5523baca2..217b4b1af1 100644 --- a/lib/iris/tests/test_trajectory.py +++ b/lib/iris/tests/test_trajectory.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2010 - 2014, Met Office +# (C) British Crown Copyright 2010 - 2015, Met Office # # This file is part of Iris. # @@ -16,6 +16,7 @@ # along with Iris. If not, see . from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before importing anything else import iris.tests as tests @@ -158,7 +159,7 @@ def test_tri_polar(self): cube.coord('depth').bounds = cube.coord('depth').bounds.astype(np.float32) # define a latitude trajectory (put coords in a different order to the cube, just to be awkward) - latitudes = range(-90, 90, 2) + latitudes = list(range(-90, 90, 2)) longitudes = [-90]*len(latitudes) sample_points = [('longitude', longitudes), ('latitude', latitudes)] diff --git a/lib/iris/tests/test_util.py b/lib/iris/tests/test_util.py index 7f3dcce344..c9d81da9bc 100644 --- a/lib/iris/tests/test_util.py +++ b/lib/iris/tests/test_util.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before # importing anything else diff --git a/lib/iris/tests/unit/analysis/area_weighted/test_AreaWeightedRegridder.py b/lib/iris/tests/unit/analysis/area_weighted/test_AreaWeightedRegridder.py index 43811963c1..542af58a45 100644 --- a/lib/iris/tests/unit/analysis/area_weighted/test_AreaWeightedRegridder.py +++ b/lib/iris/tests/unit/analysis/area_weighted/test_AreaWeightedRegridder.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -102,8 +102,8 @@ def test_invalid_low_mdtol(self): def test_mismatched_src_coord_systems(self): src = Cube(np.zeros((3, 4))) cs = GeogCS(6543210) - lat = DimCoord(range(3), 'latitude', coord_system=cs) - lon = DimCoord(range(4), 'longitude') + lat = DimCoord(np.arange(3), 'latitude', coord_system=cs) + lon = DimCoord(np.arange(4), 'longitude') src.add_dim_coord(lat, 0) src.add_dim_coord(lon, 1) target = mock.Mock() diff --git a/lib/iris/tests/unit/analysis/cartography/test_project.py b/lib/iris/tests/unit/analysis/cartography/test_project.py index ce6d6fc40c..3be2a9ba11 100644 --- a/lib/iris/tests/unit/analysis/cartography/test_project.py +++ b/lib/iris/tests/unit/analysis/cartography/test_project.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -34,10 +34,10 @@ def setUp(self): cs = iris.coord_systems.GeogCS(654321) self.cube = iris.cube.Cube(np.zeros(25).reshape(5, 5)) self.cube.add_dim_coord( - DimCoord(range(5), standard_name="latitude", units='degrees', + DimCoord(np.arange(5), standard_name="latitude", units='degrees', coord_system=cs), 0) self.cube.add_dim_coord( - DimCoord(range(5), standard_name="longitude", units='degrees', + DimCoord(np.arange(5), standard_name="longitude", units='degrees', coord_system=cs), 1) self.tcs = iris.coord_systems.GeogCS(600000) diff --git a/lib/iris/tests/unit/analysis/interpolate/test_linear.py b/lib/iris/tests/unit/analysis/interpolate/test_linear.py index 57dd2f2350..3c227673c5 100644 --- a/lib/iris/tests/unit/analysis/interpolate/test_linear.py +++ b/lib/iris/tests/unit/analysis/interpolate/test_linear.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -76,8 +76,8 @@ def test_mask_retention(self): class TestNDCoords(tests.IrisTest): def setUp(self): cube = stock.simple_3d_w_multidim_coords() - cube.add_dim_coord(iris.coords.DimCoord(range(3), 'longitude'), 1) - cube.add_dim_coord(iris.coords.DimCoord(range(4), 'latitude'), 2) + cube.add_dim_coord(iris.coords.DimCoord(np.arange(3), 'longitude'), 1) + cube.add_dim_coord(iris.coords.DimCoord(np.arange(4), 'latitude'), 2) cube.data = cube.data.astype(np.float32) self.cube = cube diff --git a/lib/iris/tests/unit/analysis/interpolation/test_RectilinearInterpolator.py b/lib/iris/tests/unit/analysis/interpolation/test_RectilinearInterpolator.py index a862a49f67..3230ea3c4a 100644 --- a/lib/iris/tests/unit/analysis/interpolation/test_RectilinearInterpolator.py +++ b/lib/iris/tests/unit/analysis/interpolation/test_RectilinearInterpolator.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -47,9 +47,9 @@ class ThreeDimCube(tests.IrisTest): def setUp(self): cube = stock.simple_3d_w_multidim_coords() - cube.add_aux_coord(iris.coords.DimCoord(range(2), 'height'), 0) - cube.add_dim_coord(iris.coords.DimCoord(range(3), 'latitude'), 1) - cube.add_dim_coord(iris.coords.DimCoord(range(4), 'longitude'), 2) + cube.add_aux_coord(iris.coords.DimCoord(np.arange(2), 'height'), 0) + cube.add_dim_coord(iris.coords.DimCoord(np.arange(3), 'latitude'), 1) + cube.add_dim_coord(iris.coords.DimCoord(np.arange(4), 'longitude'), 2) self.data = np.arange(24).reshape(2, 3, 4).astype(np.float32) cube.data = self.data self.cube = cube @@ -502,7 +502,8 @@ def interpolator(self, method=LINEAR): cube = iris.cube.Cube(data) time_coord = iris.coords.DimCoord(np.arange(0.0, 48.0, 12.0), 'time', units='hours since epoch') - height_coord = iris.coords.DimCoord(range(3), 'altitude', units='m') + height_coord = iris.coords.DimCoord(np.arange(3), 'altitude', + units='m') cube.add_dim_coord(time_coord, 0) cube.add_dim_coord(height_coord, 1) return RectilinearInterpolator(cube, ['time'], method, EXTRAPOLATE) diff --git a/lib/iris/tests/unit/analysis/maths/__init__.py b/lib/iris/tests/unit/analysis/maths/__init__.py index 7031832f0a..8d92f51278 100644 --- a/lib/iris/tests/unit/analysis/maths/__init__.py +++ b/lib/iris/tests/unit/analysis/maths/__init__.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for the :mod:`iris.analysis.maths` module.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range from abc import ABCMeta, abstractproperty diff --git a/lib/iris/tests/unit/analysis/regrid/test_RectilinearRegridder.py b/lib/iris/tests/unit/analysis/regrid/test_RectilinearRegridder.py index 396d9a4c3b..1eb4b2041f 100644 --- a/lib/iris/tests/unit/analysis/regrid/test_RectilinearRegridder.py +++ b/lib/iris/tests/unit/analysis/regrid/test_RectilinearRegridder.py @@ -17,6 +17,7 @@ """Unit tests for :class:`iris.analysis._regrid.RectilinearRegridder`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -617,9 +618,9 @@ def uk_cube(): data = np.arange(12, dtype=np.float32).reshape(3, 4) uk = Cube(data) cs = OSGB() - y_coord = DimCoord(range(3), 'projection_y_coordinate', units='m', + y_coord = DimCoord(np.arange(3), 'projection_y_coordinate', units='m', coord_system=cs) - x_coord = DimCoord(range(4), 'projection_x_coordinate', units='m', + x_coord = DimCoord(np.arange(4), 'projection_x_coordinate', units='m', coord_system=cs) uk.add_dim_coord(y_coord, 0) uk.add_dim_coord(x_coord, 1) diff --git a/lib/iris/tests/unit/analysis/test_PERCENTILE.py b/lib/iris/tests/unit/analysis/test_PERCENTILE.py index 9260ba80e4..8bce1d1987 100644 --- a/lib/iris/tests/unit/analysis/test_PERCENTILE.py +++ b/lib/iris/tests/unit/analysis/test_PERCENTILE.py @@ -17,6 +17,7 @@ """Unit tests for the :data:`iris.analysis.PERCENTILE` aggregator.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -92,7 +93,7 @@ def test_2d_multi(self): percent = np.array([10, 50, 90, 100]) actual = PERCENTILE.aggregate(data, axis=0, percent=percent) self.assertTupleEqual(actual.shape, (shape[-1], percent.size)) - expected = np.array(range(shape[-1]) * percent.size) + expected = np.tile(np.arange(shape[-1]), percent.size) expected = expected.reshape(percent.size, shape[-1]).T + 1 expected = expected + (percent / 10 - 1) self.assertArrayAlmostEqual(actual, expected) @@ -104,7 +105,7 @@ def test_masked_2d_multi(self): percent = np.array([10, 50, 70, 80]) actual = PERCENTILE.aggregate(data, axis=0, percent=percent) self.assertTupleEqual(actual.shape, (shape[-1], percent.size)) - expected = np.array(range(shape[-1]) * percent.size) + expected = np.tile(np.arange(shape[-1]), percent.size) expected = expected.reshape(percent.size, shape[-1]).T expected = expected + (percent / 10 * 2) self.assertArrayAlmostEqual(actual, expected) @@ -136,7 +137,7 @@ def test_mandatory_kwarg_no_shape(self): def test_mandatory_kwarg_shape(self): kwargs = dict(percent=(10, 20)) self.assertTupleEqual(PERCENTILE.aggregate_shape(**kwargs), (2,)) - kwargs = dict(percent=range(13)) + kwargs = dict(percent=list(range(13))) self.assertTupleEqual(PERCENTILE.aggregate_shape(**kwargs), (13,)) diff --git a/lib/iris/tests/unit/analysis/test_PercentileAggregator.py b/lib/iris/tests/unit/analysis/test_PercentileAggregator.py index 86fa1c7709..7e1d510258 100644 --- a/lib/iris/tests/unit/analysis/test_PercentileAggregator.py +++ b/lib/iris/tests/unit/analysis/test_PercentileAggregator.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -57,8 +58,8 @@ def setUp(self): self.cube_simple = Cube(data) self.cube_simple.add_dim_coord(self.coord_simple, 0) - self.coord_multi_0 = DimCoord(range(shape[0]), 'time') - self.coord_multi_1 = DimCoord(range(shape[1]), 'height') + self.coord_multi_0 = DimCoord(np.arange(shape[0]), 'time') + self.coord_multi_1 = DimCoord(np.arange(shape[1]), 'height') self.cube_multi = Cube(data.reshape(shape)) self.cube_multi.add_dim_coord(self.coord_multi_0, 0) self.cube_multi.add_dim_coord(self.coord_multi_1, 1) diff --git a/lib/iris/tests/unit/concatenate/test_concatenate.py b/lib/iris/tests/unit/concatenate/test_concatenate.py index 8d8a8ae0cc..76e2bd64d3 100644 --- a/lib/iris/tests/unit/concatenate/test_concatenate.py +++ b/lib/iris/tests/unit/concatenate/test_concatenate.py @@ -17,6 +17,7 @@ """Test function :func:`iris._concatenate.concatenate.py`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # import iris tests first so that some things can be initialised # before importing anything else. @@ -184,7 +185,7 @@ def _make_cube(self, points, bounds=None): data = np.arange(len(points) * nx).reshape(len(points), nx) cube = iris.cube.Cube(data, standard_name='air_temperature', units='K') lat = iris.coords.DimCoord(points, 'latitude', bounds=bounds) - lon = iris.coords.DimCoord(range(nx), 'longitude') + lon = iris.coords.DimCoord(np.arange(nx), 'longitude') cube.add_dim_coord(lat, 0) cube.add_dim_coord(lon, 1) return cube @@ -220,7 +221,7 @@ def build_lazy_cube(self, points, bounds=None, nx=4): data = biggus.NumpyArrayAdapter(data) cube = iris.cube.Cube(data, standard_name='air_temperature', units='K') lat = iris.coords.DimCoord(points, 'latitude', bounds=bounds) - lon = iris.coords.DimCoord(range(nx), 'longitude') + lon = iris.coords.DimCoord(np.arange(nx), 'longitude') cube.add_dim_coord(lat, 0) cube.add_dim_coord(lon, 1) return cube diff --git a/lib/iris/tests/unit/coord_categorisation/test_add_categorised_coord.py b/lib/iris/tests/unit/coord_categorisation/test_add_categorised_coord.py index f3c22bd9ff..98916ad1d5 100644 --- a/lib/iris/tests/unit/coord_categorisation/test_add_categorised_coord.py +++ b/lib/iris/tests/unit/coord_categorisation/test_add_categorised_coord.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Test function :func:`iris.coord_categorisation.add_categorised_coord`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -91,15 +92,16 @@ def test_string_vectorised(self): class Test_add_day_of_year(tests.IrisTest): def setUp(self): self.expected = { - 'standard': np.array(range(360, 367) + range(1, 4)), - 'gregorian': np.array(range(360, 367) + range(1, 4)), - 'proleptic_gregorian': np.array(range(360, 367) + range(1, 4)), - 'noleap': np.array(range(359, 366) + range(1, 4)), - 'julian': np.array(range(360, 367) + range(1, 4)), - 'all_leap': np.array(range(360, 367) + range(1, 4)), - '365_day': np.array(range(359, 366) + range(1, 4)), - '366_day': np.array(range(360, 367) + range(1, 4)), - '360_day': np.array(range(355, 361) + range(1, 5))} + 'standard': np.array(list(range(360, 367)) + list(range(1, 4))), + 'gregorian': np.array(list(range(360, 367)) + list(range(1, 4))), + 'proleptic_gregorian': np.array(list(range(360, 367)) + + list(range(1, 4))), + 'noleap': np.array(list(range(359, 366)) + list(range(1, 4))), + 'julian': np.array(list(range(360, 367)) + list(range(1, 4))), + 'all_leap': np.array(list(range(360, 367)) + list(range(1, 4))), + '365_day': np.array(list(range(359, 366)) + list(range(1, 4))), + '366_day': np.array(list(range(360, 367)) + list(range(1, 4))), + '360_day': np.array(list(range(355, 361)) + list(range(1, 5)))} def make_cube(self, calendar): n_times = 10 diff --git a/lib/iris/tests/unit/coords/test_Coord.py b/lib/iris/tests/unit/coords/test_Coord.py index 9a97a082b3..103f02846a 100644 --- a/lib/iris/tests/unit/coords/test_Coord.py +++ b/lib/iris/tests/unit/coords/test_Coord.py @@ -270,7 +270,7 @@ def test_different_array_attrs_incompatible(self): class Test_DimCoord_copy(tests.IrisTest): def test_writable_points(self): - coord1 = DimCoord(range(5), + coord1 = DimCoord(np.arange(5), bounds=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]) coord2 = coord1.copy() msg = 'destination is read-only' diff --git a/lib/iris/tests/unit/cube/test_Cube.py b/lib/iris/tests/unit/cube/test_Cube.py index a44684f8d3..09cf161b71 100644 --- a/lib/iris/tests/unit/cube/test_Cube.py +++ b/lib/iris/tests/unit/cube/test_Cube.py @@ -17,13 +17,12 @@ """Unit tests for the `iris.cube.Cube` class.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests -import itertools - import biggus import mock import numpy as np @@ -237,7 +236,7 @@ def test_lat_lon_weighted_aggregator(self): with mock.patch('warnings.warn') as warn: self.cube.collapsed(coords, aggregator) - coords = filter(lambda coord: 'latitude' in coord, coords) + coords = [coord for coord in coords if 'latitude' in coord] self._assert_warn_collapse_without_weight(coords, warn) def test_lat_lon_weighted_aggregator_with_weights(self): @@ -261,7 +260,7 @@ def test_lat_lon_weighted_aggregator_alt(self): with mock.patch('warnings.warn') as warn: self.cube.collapsed(coords, aggregator) - coords = filter(lambda coord: 'latitude' in coord, coords) + coords = [coord for coord in coords if 'latitude' in coord] self._assert_warn_collapse_without_weight(coords, warn) def test_no_lat_weighted_aggregator_mixed(self): @@ -416,7 +415,7 @@ class Test_slices_over(tests.IrisTest): def setUp(self): self.cube = stock.realistic_4d() # Define expected iterators for 1D and 2D test cases. - self.exp_iter_1d = xrange( + self.exp_iter_1d = range( len(self.cube.coord('model_level_number').points)) self.exp_iter_2d = np.ndindex(6, 70, 1, 1) # Define maximum number of interations for particularly long @@ -425,7 +424,7 @@ def setUp(self): def test_1d_slice_coord_given(self): res = self.cube.slices_over(self.cube.coord('model_level_number')) - for i, res_cube in itertools.izip(self.exp_iter_1d, res): + for i, res_cube in zip(self.exp_iter_1d, res): expected = self.cube[:, i] self.assertEqual(res_cube, expected) @@ -435,7 +434,7 @@ def test_1d_slice_nonexistent_coord_given(self): def test_1d_slice_coord_name_given(self): res = self.cube.slices_over('model_level_number') - for i, res_cube in itertools.izip(self.exp_iter_1d, res): + for i, res_cube in zip(self.exp_iter_1d, res): expected = self.cube[:, i] self.assertEqual(res_cube, expected) @@ -445,7 +444,7 @@ def test_1d_slice_nonexistent_coord_name_given(self): def test_1d_slice_dimension_given(self): res = self.cube.slices_over(1) - for i, res_cube in itertools.izip(self.exp_iter_1d, res): + for i, res_cube in zip(self.exp_iter_1d, res): expected = self.cube[:, i] self.assertEqual(res_cube, expected) @@ -526,13 +525,13 @@ def test_multidim_slice_coord_given(self): def test_duplicate_coordinate_given(self): res = self.cube.slices_over([1, 1]) - for i, res_cube in itertools.izip(self.exp_iter_1d, res): + for i, res_cube in zip(self.exp_iter_1d, res): expected = self.cube[:, i] self.assertEqual(res_cube, expected) def test_non_orthogonal_coordinates_given(self): res = self.cube.slices_over(['model_level_number', 'sigma']) - for i, res_cube in itertools.izip(self.exp_iter_1d, res): + for i, res_cube in zip(self.exp_iter_1d, res): expected = self.cube[:, i] self.assertEqual(res_cube, expected) @@ -647,7 +646,7 @@ def test_real_data(self): result = cube.intersection(longitude=(170, 190)) self.assertFalse(result.has_lazy_data()) self.assertArrayEqual(result.coord('longitude').points, - range(170, 191)) + np.arange(170, 191)) self.assertEqual(result.data[0, 0, 0], 170) self.assertEqual(result.data[0, 0, -1], 190) @@ -657,7 +656,7 @@ def test_real_data_wrapped(self): result = cube.intersection(longitude=(170, 190)) self.assertFalse(result.has_lazy_data()) self.assertArrayEqual(result.coord('longitude').points, - range(170, 191)) + np.arange(170, 191)) self.assertEqual(result.data[0, 0, 0], 350) self.assertEqual(result.data[0, 0, -1], 10) @@ -666,7 +665,7 @@ def test_lazy_data(self): result = cube.intersection(longitude=(170, 190)) self.assertTrue(result.has_lazy_data()) self.assertArrayEqual(result.coord('longitude').points, - range(170, 191)) + np.arange(170, 191)) self.assertEqual(result.data[0, 0, 0], 170) self.assertEqual(result.data[0, 0, -1], 190) @@ -675,7 +674,7 @@ def test_lazy_data_wrapped(self): result = cube.intersection(longitude=(170, 190)) self.assertTrue(result.has_lazy_data()) self.assertArrayEqual(result.coord('longitude').points, - range(170, 191)) + np.arange(170, 191)) self.assertEqual(result.data[0, 0, 0], 350) self.assertEqual(result.data[0, 0, -1], 10) @@ -685,7 +684,7 @@ def test_ignore_bounds(self): cube = create_cube(0, 30, bounds=True) result = cube.intersection(longitude=(9.5, 12.5), ignore_bounds=True) self.assertArrayEqual(result.coord('longitude').points, - range(10, 13)) + np.arange(10, 13)) self.assertArrayEqual(result.coord('longitude').bounds[0], [9.5, 10.5]) self.assertArrayEqual(result.coord('longitude').bounds[-1], @@ -698,54 +697,58 @@ class Test_intersection__RegionalSrcModulus(tests.IrisTest): def test_request_subset(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(45, 50)) - self.assertArrayEqual(result.coord('longitude').points, range(45, 51)) - self.assertArrayEqual(result.data[0, 0], range(5, 11)) + self.assertArrayEqual(result.coord('longitude').points, + np.arange(45, 51)) + self.assertArrayEqual(result.data[0, 0], np.arange(5, 11)) def test_request_left(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(35, 45)) - self.assertArrayEqual(result.coord('longitude').points, range(40, 46)) - self.assertArrayEqual(result.data[0, 0], range(0, 6)) + self.assertArrayEqual(result.coord('longitude').points, + np.arange(40, 46)) + self.assertArrayEqual(result.data[0, 0], np.arange(0, 6)) def test_request_right(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(55, 65)) - self.assertArrayEqual(result.coord('longitude').points, range(55, 60)) - self.assertArrayEqual(result.data[0, 0], range(15, 20)) + self.assertArrayEqual(result.coord('longitude').points, + np.arange(55, 60)) + self.assertArrayEqual(result.data[0, 0], np.arange(15, 20)) def test_request_superset(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(35, 65)) - self.assertArrayEqual(result.coord('longitude').points, range(40, 60)) - self.assertArrayEqual(result.data[0, 0], range(0, 20)) + self.assertArrayEqual(result.coord('longitude').points, + np.arange(40, 60)) + self.assertArrayEqual(result.data[0, 0], np.arange(0, 20)) def test_request_subset_modulus(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(45 + 360, 50 + 360)) self.assertArrayEqual(result.coord('longitude').points, - range(45 + 360, 51 + 360)) - self.assertArrayEqual(result.data[0, 0], range(5, 11)) + np.arange(45 + 360, 51 + 360)) + self.assertArrayEqual(result.data[0, 0], np.arange(5, 11)) def test_request_left_modulus(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(35 + 360, 45 + 360)) self.assertArrayEqual(result.coord('longitude').points, - range(40 + 360, 46 + 360)) - self.assertArrayEqual(result.data[0, 0], range(0, 6)) + np.arange(40 + 360, 46 + 360)) + self.assertArrayEqual(result.data[0, 0], np.arange(0, 6)) def test_request_right_modulus(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(55 + 360, 65 + 360)) self.assertArrayEqual(result.coord('longitude').points, - range(55 + 360, 60 + 360)) - self.assertArrayEqual(result.data[0, 0], range(15, 20)) + np.arange(55 + 360, 60 + 360)) + self.assertArrayEqual(result.data[0, 0], np.arange(15, 20)) def test_request_superset_modulus(self): cube = create_cube(40, 60) result = cube.intersection(longitude=(35 + 360, 65 + 360)) self.assertArrayEqual(result.coord('longitude').points, - range(40 + 360, 60 + 360)) - self.assertArrayEqual(result.data[0, 0], range(0, 20)) + np.arange(40 + 360, 60 + 360)) + self.assertArrayEqual(result.data[0, 0], np.arange(0, 20)) def test_tolerance_f4(self): cube = create_cube(0, 5) @@ -1091,7 +1094,7 @@ def test_superset(self): result = cube.intersection(longitude=(0, 15)) self.assertArrayEqual(result.coord('longitude').points, [5, 10, 8, 5, 3]) - self.assertArrayEqual(result.data, range(5)) + self.assertArrayEqual(result.data, np.arange(5)) # Test the API of the cube interpolation method. diff --git a/lib/iris/tests/unit/cube/test_CubeList.py b/lib/iris/tests/unit/cube/test_CubeList.py index c5d67f75cd..4aa4754ce5 100644 --- a/lib/iris/tests/unit/cube/test_CubeList.py +++ b/lib/iris/tests/unit/cube/test_CubeList.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for the `iris.cube.CubeList` class.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/experimental/equalise_cubes/test_equalise_attributes.py b/lib/iris/tests/unit/experimental/equalise_cubes/test_equalise_attributes.py index 90285fcd30..1e14ac3d7a 100644 --- a/lib/iris/tests/unit/experimental/equalise_cubes/test_equalise_attributes.py +++ b/lib/iris/tests/unit/experimental/equalise_cubes/test_equalise_attributes.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised # before importing anything else. diff --git a/lib/iris/tests/unit/experimental/raster/test_export_geotiff.py b/lib/iris/tests/unit/experimental/raster/test_export_geotiff.py index 75b6b46b7b..e5e1526892 100644 --- a/lib/iris/tests/unit/experimental/raster/test_export_geotiff.py +++ b/lib/iris/tests/unit/experimental/raster/test_export_geotiff.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -39,10 +39,10 @@ class TestDtypeAndValues(tests.IrisTest): def _cube(self, dtype): data = np.arange(12).reshape(3, 4).astype(dtype) + 20 cube = Cube(data, 'air_pressure_anomaly') - coord = DimCoord(range(3), 'latitude', units='degrees') + coord = DimCoord(np.arange(3), 'latitude', units='degrees') coord.guess_bounds() cube.add_dim_coord(coord, 0) - coord = DimCoord(range(4), 'longitude', units='degrees') + coord = DimCoord(np.arange(4), 'longitude', units='degrees') coord.guess_bounds() cube.add_dim_coord(coord, 1) return cube @@ -107,11 +107,11 @@ class TestProjection(tests.IrisTest): def _cube(self, ellipsoid=None): data = np.arange(12).reshape(3, 4).astype('u1') cube = Cube(data, 'air_pressure_anomaly') - coord = DimCoord(range(3), 'latitude', units='degrees', + coord = DimCoord(np.arange(3), 'latitude', units='degrees', coord_system=ellipsoid) coord.guess_bounds() cube.add_dim_coord(coord, 0) - coord = DimCoord(range(4), 'longitude', units='degrees', + coord = DimCoord(np.arange(4), 'longitude', units='degrees', coord_system=ellipsoid) coord.guess_bounds() cube.add_dim_coord(coord, 1) diff --git a/lib/iris/tests/unit/experimental/regrid/test_regrid_weighted_curvilinear_to_rectilinear.py b/lib/iris/tests/unit/experimental/regrid/test_regrid_weighted_curvilinear_to_rectilinear.py index 97b34f70fd..e99401bad8 100644 --- a/lib/iris/tests/unit/experimental/regrid/test_regrid_weighted_curvilinear_to_rectilinear.py +++ b/lib/iris/tests/unit/experimental/regrid/test_regrid_weighted_curvilinear_to_rectilinear.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised before # importing anything else diff --git a/lib/iris/tests/unit/experimental/um/test_Field.py b/lib/iris/tests/unit/experimental/um/test_Field.py index e3cb4522f3..092d278f14 100644 --- a/lib/iris/tests/unit/experimental/um/test_Field.py +++ b/lib/iris/tests/unit/experimental/um/test_Field.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -33,75 +34,75 @@ class Test_int_headers(tests.IrisTest): def test(self): - field = Field(range(45), range(19), None) - self.assertArrayEqual(field.int_headers, range(45)) + field = Field(np.arange(45), list(range(19)), None) + self.assertArrayEqual(field.int_headers, np.arange(45)) class Test_real_headers(tests.IrisTest): def test(self): - field = Field(range(45), range(19), None) - self.assertArrayEqual(field.real_headers, range(19)) + field = Field(list(range(45)), np.arange(19), None) + self.assertArrayEqual(field.real_headers, np.arange(19)) class Test___eq__(tests.IrisTest): def test_equal(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45), range(19), None) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45), np.arange(19), None) self.assertTrue(field1.__eq__(field2)) def test_not_equal_ints(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45, 90), range(19), None) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45, 90), np.arange(19), None) self.assertFalse(field1.__eq__(field2)) def test_not_equal_reals(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45), range(19, 38), None) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45), np.arange(19, 38), None) self.assertFalse(field1.__eq__(field2)) def test_not_equal_data(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45), range(19), np.zeros(3)) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45), np.arange(19), np.zeros(3)) self.assertFalse(field1.__eq__(field2)) def test_invalid(self): - field1 = Field(range(45), range(19), None) + field1 = Field(list(range(45)), list(range(19)), None) self.assertIs(field1.__eq__('foo'), NotImplemented) class Test___ne__(tests.IrisTest): def test_equal(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45), range(19), None) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45), np.arange(19), None) self.assertFalse(field1.__ne__(field2)) def test_not_equal_ints(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45, 90), range(19), None) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45, 90), np.arange(19), None) self.assertTrue(field1.__ne__(field2)) def test_not_equal_reals(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45), range(19, 38), None) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45), np.arange(19, 38), None) self.assertTrue(field1.__ne__(field2)) def test_not_equal_data(self): - field1 = Field(range(45), range(19), None) - field2 = Field(range(45), range(19), np.zeros(3)) + field1 = Field(list(range(45)), list(range(19)), None) + field2 = Field(np.arange(45), np.arange(19), np.zeros(3)) self.assertTrue(field1.__ne__(field2)) def test_invalid(self): - field1 = Field(range(45), range(19), None) + field1 = Field(list(range(45)), list(range(19)), None) self.assertIs(field1.__ne__('foo'), NotImplemented) class Test_num_values(tests.IrisTest): def test_64(self): - field = Field(range(45), range(19), None) + field = Field(list(range(45)), list(range(19)), None) self.assertEqual(field.num_values(), 64) def test_128(self): - field = Field(range(45), range(83), None) + field = Field(list(range(45)), list(range(83)), None) self.assertEqual(field.num_values(), 128) @@ -151,7 +152,7 @@ def _check_formats(self, if absent_provider: # Replace the provider with a simple array. provider = np.zeros(2) - field = Field(range(45), range(19), provider) + field = Field(list(range(45)), list(range(19)), provider) return field._can_copy_deferred_data(new_lbpack, new_bacc) def test_okay_simple(self): diff --git a/lib/iris/tests/unit/experimental/um/test_FixedLengthHeader.py b/lib/iris/tests/unit/experimental/um/test_FixedLengthHeader.py index dda7b6ede2..dc78b17f42 100644 --- a/lib/iris/tests/unit/experimental/um/test_FixedLengthHeader.py +++ b/lib/iris/tests/unit/experimental/um/test_FixedLengthHeader.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -74,39 +75,39 @@ def test_explicit_32_bit(self): class Test___init__(tests.IrisTest): def test_invalid_length(self): with self.assertRaisesRegexp(ValueError, 'Incorrect number of words'): - FixedLengthHeader(range(15)) + FixedLengthHeader(list(range(15))) class Test___eq__(tests.IrisTest): def test_equal(self): - ffv1 = FixedLengthHeader(range(256)) - ffv2 = FixedLengthHeader(range(256)) + ffv1 = FixedLengthHeader(list(range(256))) + ffv2 = FixedLengthHeader(np.arange(256)) self.assertTrue(ffv1.__eq__(ffv2)) def test_not_equal(self): - ffv1 = FixedLengthHeader(range(256)) - ffv2 = FixedLengthHeader(range(256, 512)) + ffv1 = FixedLengthHeader(list(range(256))) + ffv2 = FixedLengthHeader(np.arange(256, 512)) self.assertFalse(ffv1.__eq__(ffv2)) def test_invalid(self): - ffv1 = FixedLengthHeader(range(256)) - self.assertIs(ffv1.__eq__(range(256)), NotImplemented) + ffv1 = FixedLengthHeader(list(range(256))) + self.assertIs(ffv1.__eq__(np.arange(256)), NotImplemented) class Test___ne__(tests.IrisTest): def test_equal(self): - ffv1 = FixedLengthHeader(range(256)) - ffv2 = FixedLengthHeader(range(256)) + ffv1 = FixedLengthHeader(list(range(256))) + ffv2 = FixedLengthHeader(np.arange(256)) self.assertFalse(ffv1.__ne__(ffv2)) def test_not_equal(self): - ffv1 = FixedLengthHeader(range(256)) - ffv2 = FixedLengthHeader(range(256, 512)) + ffv1 = FixedLengthHeader(list(range(256))) + ffv2 = FixedLengthHeader(np.arange(256, 512)) self.assertTrue(ffv1.__ne__(ffv2)) def test_invalid(self): - ffv1 = FixedLengthHeader(range(256)) - self.assertIs(ffv1.__ne__(range(256)), NotImplemented) + ffv1 = FixedLengthHeader(list(range(256))) + self.assertIs(ffv1.__ne__(np.arange(256)), NotImplemented) def make_header(): diff --git a/lib/iris/tests/unit/fileformats/cf/test_CFReader.py b/lib/iris/tests/unit/fileformats/cf/test_CFReader.py index 9ac96a1786..a6d42f5d3e 100644 --- a/lib/iris/tests/unit/fileformats/cf/test_CFReader.py +++ b/lib/iris/tests/unit/fileformats/cf/test_CFReader.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/fileformats/ff/test_FF2PP.py b/lib/iris/tests/unit/fileformats/ff/test_FF2PP.py index a4724110f4..d0be4e0e01 100644 --- a/lib/iris/tests/unit/fileformats/ff/test_FF2PP.py +++ b/lib/iris/tests/unit/fileformats/ff/test_FF2PP.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for the :class:`iris.fileformat.ff.FF2PP` class.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -366,7 +367,8 @@ def _check_expected_levels(self, results, n_levels): self.assertEqual(results[0].lblev, self.original_lblev) else: self.assertEqual(len(results), n_levels) - self.assertEqual([fld.lblev for fld in results], range(n_levels)) + self.assertEqual([fld.lblev for fld in results], + list(range(n_levels))) def test__is_lbc(self): ff2pp = FF2PP('dummy_filename') diff --git a/lib/iris/tests/unit/fileformats/grib/load_convert/test_grid_definition_template_90.py b/lib/iris/tests/unit/fileformats/grib/load_convert/test_grid_definition_template_90.py index 48256ad04f..c72a1b9a2d 100644 --- a/lib/iris/tests/unit/fileformats/grib/load_convert/test_grid_definition_template_90.py +++ b/lib/iris/tests/unit/fileformats/grib/load_convert/test_grid_definition_template_90.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # import iris tests first so that some things can be initialised # before importing anything else. diff --git a/lib/iris/tests/unit/fileformats/grib/load_convert/test_product_definition_template_31.py b/lib/iris/tests/unit/fileformats/grib/load_convert/test_product_definition_template_31.py index e1653846ec..195372c4ea 100644 --- a/lib/iris/tests/unit/fileformats/grib/load_convert/test_product_definition_template_31.py +++ b/lib/iris/tests/unit/fileformats/grib/load_convert/test_product_definition_template_31.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised # before importing anything else. diff --git a/lib/iris/tests/unit/fileformats/grib/message/test__RawGribMessage.py b/lib/iris/tests/unit/fileformats/grib/message/test__RawGribMessage.py index 08a07879fb..de451031ae 100644 --- a/lib/iris/tests/unit/fileformats/grib/message/test__RawGribMessage.py +++ b/lib/iris/tests/unit/fileformats/grib/message/test__RawGribMessage.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/fileformats/name_loaders/test_generate_cubes.py b/lib/iris/tests/unit/fileformats/name_loaders/test_generate_cubes.py index 209640cb07..5a66f2b932 100644 --- a/lib/iris/tests/unit/fileformats/name_loaders/test_generate_cubes.py +++ b/lib/iris/tests/unit/fileformats/name_loaders/test_generate_cubes.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/fileformats/netcdf/test_Saver.py b/lib/iris/tests/unit/fileformats/netcdf/test_Saver.py index 0419c317a7..c6e83b0db5 100644 --- a/lib/iris/tests/unit/fileformats/netcdf/test_Saver.py +++ b/lib/iris/tests/unit/fileformats/netcdf/test_Saver.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for the `iris.fileformats.netcdf.Saver` class.""" from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -40,10 +41,10 @@ def _transverse_mercator_cube(self, ellipsoid=None): cube = Cube(data, 'air_pressure_anomaly') trans_merc = TransverseMercator(49.0, -2.0, -400000.0, 100000.0, 0.9996012717, ellipsoid) - coord = DimCoord(range(3), 'projection_y_coordinate', units='m', + coord = DimCoord(np.arange(3), 'projection_y_coordinate', units='m', coord_system=trans_merc) cube.add_dim_coord(coord, 0) - coord = DimCoord(range(4), 'projection_x_coordinate', units='m', + coord = DimCoord(np.arange(4), 'projection_x_coordinate', units='m', coord_system=trans_merc) cube.add_dim_coord(coord, 1) return cube @@ -209,8 +210,8 @@ def construct_cf_grid_mapping_variable(self, cube): def variable_attributes(self, mocked_variable): """Get the attributes dictionary from a mocked NetCDF variable.""" # Get the attributes defined on the mock object. - attributes = filter(lambda name: not name.startswith('_'), - sorted(mocked_variable.__dict__.keys())) + attributes = [name for name in sorted(mocked_variable.__dict__.keys()) + if not name.startswith('_')] attributes.remove('method_calls') return {key: getattr(mocked_variable, key) for key in attributes} diff --git a/lib/iris/tests/unit/fileformats/netcdf/test__load_aux_factory.py b/lib/iris/tests/unit/fileformats/netcdf/test__load_aux_factory.py index 37b1e709ec..d4196b915c 100644 --- a/lib/iris/tests/unit/fileformats/netcdf/test__load_aux_factory.py +++ b/lib/iris/tests/unit/fileformats/netcdf/test__load_aux_factory.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -61,7 +61,7 @@ def test_formula_terms_ap(self): self.assertEqual(factory.surface_air_pressure, mock.sentinel.ps) def test_formula_terms_a_p0(self): - coord_a = DimCoord(range(5), units='Pa') + coord_a = DimCoord(np.arange(5), units='Pa') coord_p0 = DimCoord(10, units='1') coord_expected = DimCoord(np.arange(5) * 10, units='Pa', long_name='vertical pressure', var_name='ap') @@ -89,14 +89,14 @@ def test_formula_terms_a_p0(self): self.assertEqual(factory.surface_air_pressure, mock.sentinel.ps) def test_formula_terms_p0_non_scalar(self): - coord_p0 = DimCoord(range(5)) + coord_p0 = DimCoord(np.arange(5)) self.provides['coordinates'].append((coord_p0, 'p0')) self.requires['formula_terms'] = dict(p0='p0') with self.assertRaises(ValueError): _load_aux_factory(self.engine, self.cube) def test_formula_terms_p0_bounded(self): - coord_a = DimCoord(range(5)) + coord_a = DimCoord(np.arange(5)) coord_p0 = DimCoord(1, bounds=[0, 2], var_name='p0') self.provides['coordinates'].extend([(coord_a, 'a'), (coord_p0, 'p0')]) self.requires['formula_terms'] = dict(a='a', b='b', ps='ps', p0='p0') diff --git a/lib/iris/tests/unit/fileformats/netcdf/test__load_cube.py b/lib/iris/tests/unit/fileformats/netcdf/test__load_cube.py index 3a50e907aa..37f5fbfb43 100644 --- a/lib/iris/tests/unit/fileformats/netcdf/test__load_cube.py +++ b/lib/iris/tests/unit/fileformats/netcdf/test__load_cube.py @@ -17,6 +17,7 @@ """Unit tests for the `iris.fileformats.netcdf._load_cube` function.""" from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/fileformats/pp/test__LBProc.py b/lib/iris/tests/unit/fileformats/pp/test__LBProc.py index 2f6fdbb1b0..769dc92b66 100644 --- a/lib/iris/tests/unit/fileformats/pp/test__LBProc.py +++ b/lib/iris/tests/unit/fileformats/pp/test__LBProc.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for :class:`iris.fileformats.pp._LBProc`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -59,7 +60,7 @@ def test_false(self): self.assertFalse(flag) def test_many(self): - for i in xrange(100): + for i in range(100): lbproc = _LBProc(i) with mock.patch('warnings.warn') as warn: flag = lbproc.flag1 @@ -83,7 +84,7 @@ def test_false(self): self.assertFalse(flag) def test_many(self): - for i in xrange(100): + for i in range(100): lbproc = _LBProc(i) with mock.patch('warnings.warn') as warn: flag = lbproc.flag2 @@ -107,7 +108,7 @@ def test_false(self): self.assertFalse(flag) def test_many(self): - for i in xrange(100): + for i in range(100): lbproc = _LBProc(i) with mock.patch('warnings.warn') as warn: flag = lbproc.flag4 @@ -131,7 +132,7 @@ def test_false(self): self.assertFalse(flag) def test_many(self): - for i in xrange(0, 260000, 1000): + for i in range(0, 260000, 1000): lbproc = _LBProc(i) with mock.patch('warnings.warn') as warn: flag = lbproc.flag131072 diff --git a/lib/iris/tests/unit/fileformats/pp_rules/test__convert_vertical_coords.py b/lib/iris/tests/unit/fileformats/pp_rules/test__convert_vertical_coords.py index f621d06813..2233e6680c 100644 --- a/lib/iris/tests/unit/fileformats/pp_rules/test__convert_vertical_coords.py +++ b/lib/iris/tests/unit/fileformats/pp_rules/test__convert_vertical_coords.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -119,7 +120,7 @@ def test_implied_height_10m(self): expect_normal=False, expect_fixed_height=10.0) def test_implied_height_10m__vector(self): - data = range(10) + data = list(range(10)) dim = 4 for blev in [data, np.asarray(data)]: for dim_i in [dim, (dim,)]: @@ -312,7 +313,7 @@ def test_normal(self): self._check_potm(_lbcode(0)) def test_normal__vector(self): - blev = range(10) + blev = list(range(10)) self._check_potm(_lbcode(0), blev=blev, dim=0) def test_cross_section(self): @@ -366,7 +367,7 @@ def test_normal(self): self._check() def test_normal__vector(self): - lblev = range(3) + lblev = list(range(3)) bhlev = [10, 20, 30] bhrlev = [5, 15, 25] brsvd2 = [15, 25, 35] diff --git a/lib/iris/tests/unit/fileformats/pp_rules/test__dim_or_aux.py b/lib/iris/tests/unit/fileformats/pp_rules/test__dim_or_aux.py index 373542692e..1cefa795bc 100644 --- a/lib/iris/tests/unit/fileformats/pp_rules/test__dim_or_aux.py +++ b/lib/iris/tests/unit/fileformats/pp_rules/test__dim_or_aux.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for :func:`iris.fileformats.pp_rules._dim_or_aux`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -28,7 +29,7 @@ class Test(tests.IrisTest): def setUp(self): - self.mono = range(5) + self.mono = list(range(5)) self.non_mono = [0, 1, 3, 2, 4] self.std_name = 'depth' self.units = 'm' diff --git a/lib/iris/tests/unit/fileformats/pp_rules/test__model_level_number.py b/lib/iris/tests/unit/fileformats/pp_rules/test__model_level_number.py index 8d8ee8535c..30fc8899b1 100644 --- a/lib/iris/tests/unit/fileformats/pp_rules/test__model_level_number.py +++ b/lib/iris/tests/unit/fileformats/pp_rules/test__model_level_number.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for :func:`iris.fileformats.pp_rules._model_level_number`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -32,7 +33,7 @@ def test(self): class Test_lblev(tests.IrisTest): def test(self): - for val in xrange(9999): + for val in range(9999): self.assertEqual(_model_level_number(val), val) diff --git a/lib/iris/tests/unit/fileformats/pp_rules/test__reshape_vector_args.py b/lib/iris/tests/unit/fileformats/pp_rules/test__reshape_vector_args.py index 041d14b7a5..6ecd0da910 100644 --- a/lib/iris/tests/unit/fileformats/pp_rules/test__reshape_vector_args.py +++ b/lib/iris/tests/unit/fileformats/pp_rules/test__reshape_vector_args.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/fileformats/pp_rules/test_convert.py b/lib/iris/tests/unit/fileformats/pp_rules/test_convert.py index 4a8a68fc5b..9a7b1b0b84 100644 --- a/lib/iris/tests/unit/fileformats/pp_rules/test_convert.py +++ b/lib/iris/tests/unit/fileformats/pp_rules/test_convert.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for :func:`iris.fileformats.pp_rules.convert`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import filter # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -163,7 +164,7 @@ def is_t_coord(coord_and_dims): coord, dims = coord_and_dims return coord.standard_name == 'time' - coords_and_dims = filter(is_t_coord, aux_coords_and_dims) + coords_and_dims = list(filter(is_t_coord, aux_coords_and_dims)) self.assertEqual(len(coords_and_dims), 1) coord, dims = coords_and_dims[0] self.assertEqual(guess_coord_axis(coord), 'T') diff --git a/lib/iris/tests/unit/fileformats/structured_array_identification/test_ArrayStructure.py b/lib/iris/tests/unit/fileformats/structured_array_identification/test_ArrayStructure.py index c48628c509..b9c534e304 100644 --- a/lib/iris/tests/unit/fileformats/structured_array_identification/test_ArrayStructure.py +++ b/lib/iris/tests/unit/fileformats/structured_array_identification/test_ArrayStructure.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -63,7 +64,8 @@ def test_1d_ones(self): def test_1d_range(self): a = np.arange(6) - self.assertEqual(self.struct_from_arr(a), ArrayStructure(1, range(6))) + self.assertEqual(self.struct_from_arr(a), + ArrayStructure(1, list(range(6)))) def test_3d_ones(self): a = np.ones([10, 2, 1]) diff --git a/lib/iris/tests/unit/fileformats/structured_array_identification/test_GroupStructure.py b/lib/iris/tests/unit/fileformats/structured_array_identification/test_GroupStructure.py index 24511be0c0..f5aed5c643 100644 --- a/lib/iris/tests/unit/fileformats/structured_array_identification/test_GroupStructure.py +++ b/lib/iris/tests/unit/fileformats/structured_array_identification/test_GroupStructure.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -100,7 +101,7 @@ def test_alternate_potentials(self): def test_shared_first_dimension(self): # One 2d potential as well as one 3d, using the same first dimension. array_structures = regular_array_structures((4, 2, 3)) - array_structures['bc combined'] = ArrayStructure(4, range(6)) + array_structures['bc combined'] = ArrayStructure(4, np.arange(6)) self.assert_potentials(24, array_structures, [['a', 'bc combined'], ['a', 'b', 'c']]) @@ -108,7 +109,7 @@ def test_non_viable_element(self): # One 2d potential as well as one 3d, using the same first dimension. array_structures = regular_array_structures((4, 2, 3)) array_structures.pop('c') - array_structures['strange_length'] = ArrayStructure(4, range(5)) + array_structures['strange_length'] = ArrayStructure(4, np.arange(5)) self.assert_potentials(24, array_structures, []) def test_completely_unstructured_element(self): @@ -173,7 +174,7 @@ def test_structured_array_not_applicable(self): # gets used. Check that 'd' which would make a good 1D array, doesn't # get used in a specific shape. elements = regular_array_structures((2, 2, 3)) - elements['d'] = ArrayStructure(3, range(4)) + elements['d'] = ArrayStructure(3, np.arange(4)) grp = GroupStructure(12, elements, array_order='f') d = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]).reshape((3, 4), diff --git a/lib/iris/tests/unit/fileformats/um/fast_load_structured_fields/test_group_structured_fields.py b/lib/iris/tests/unit/fileformats/um/fast_load_structured_fields/test_group_structured_fields.py index 3d7d13e939..535cdc96fb 100644 --- a/lib/iris/tests/unit/fileformats/um/fast_load_structured_fields/test_group_structured_fields.py +++ b/lib/iris/tests/unit/fileformats/um/fast_load_structured_fields/test_group_structured_fields.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2014, Met Office +# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range, zip # import iris tests first so that some things can be initialised # before importing anything else. diff --git a/lib/iris/tests/unit/plot/__init__.py b/lib/iris/tests/unit/plot/__init__.py index f8d1160cc4..b5749aca12 100644 --- a/lib/iris/tests/unit/plot/__init__.py +++ b/lib/iris/tests/unit/plot/__init__.py @@ -17,6 +17,7 @@ """Unit tests for the :mod:`iris.plot` module.""" from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/tests/unit/time/test_PartialDateTime.py b/lib/iris/tests/unit/time/test_PartialDateTime.py index a9a66853b9..3c6431ee81 100644 --- a/lib/iris/tests/unit/time/test_PartialDateTime.py +++ b/lib/iris/tests/unit/time/test_PartialDateTime.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Unit tests for the `iris.time.PartialDateTime` class.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # Import iris.tests first so that some things can be initialised before # importing anything else. @@ -48,7 +49,7 @@ def test_keyword_args(self): class Test___repr__(tests.IrisTest): def test_full(self): - pd = PartialDateTime(*range(7)) + pd = PartialDateTime(*list(range(7))) result = repr(pd) self.assertEqual(result, 'PartialDateTime(year=0, month=1, day=2,' ' hour=3, minute=4, second=5,' @@ -69,7 +70,7 @@ class Test_timetuple(tests.IrisTest): def test_exists(self): # Check that the PartialDateTime class implements a timetuple (needed # because of http://bugs.python.org/issue8005). - pd = PartialDateTime(*range(7)) + pd = PartialDateTime(*list(range(7))) self.assertTrue(hasattr(pd, 'timetuple')) diff --git a/lib/iris/tests/unit/util/test_broadcast_to_shape.py b/lib/iris/tests/unit/util/test_broadcast_to_shape.py index 39b9dfc10a..b303a3d54b 100644 --- a/lib/iris/tests/unit/util/test_broadcast_to_shape.py +++ b/lib/iris/tests/unit/util/test_broadcast_to_shape.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Test function :func:`iris.util.broadcast_to_shape`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import range # import iris tests first so that some things can be initialised before # importing anything else @@ -41,8 +42,8 @@ def test_added_dimensions(self): # the existing dimensions a = np.random.random([2, 3]) b = broadcast_to_shape(a, (5, 2, 4, 3), (1, 3)) - for i in xrange(5): - for j in xrange(4): + for i in range(5): + for j in range(4): self.assertArrayEqual(b[i, :, j, :], a) def test_added_dimensions_transpose(self): @@ -50,8 +51,8 @@ def test_added_dimensions_transpose(self): # transposed a = np.random.random([2, 3]) b = broadcast_to_shape(a, (5, 3, 4, 2), (3, 1)) - for i in xrange(5): - for j in xrange(4): + for i in range(5): + for j in range(4): self.assertArrayEqual(b[i, :, j, :].T, a) def test_masked(self): @@ -59,8 +60,8 @@ def test_masked(self): a = np.random.random([2, 3]) m = ma.array(a, mask=[[0, 1, 0], [0, 1, 1]]) b = broadcast_to_shape(m, (5, 3, 4, 2), (3, 1)) - for i in xrange(5): - for j in xrange(4): + for i in range(5): + for j in range(4): self.assertMaskedArrayEqual(b[i, :, j, :].T, m) def test_masked_degenerate(self): @@ -68,8 +69,8 @@ def test_masked_degenerate(self): a = np.random.random([2, 3]) m = ma.array(a) b = broadcast_to_shape(m, (5, 3, 4, 2), (3, 1)) - for i in xrange(5): - for j in xrange(4): + for i in range(5): + for j in range(4): self.assertMaskedArrayEqual(b[i, :, j, :].T, m) diff --git a/lib/iris/tests/unit/util/test_new_axis.py b/lib/iris/tests/unit/util/test_new_axis.py index 09048d6b01..6634ed6a8f 100644 --- a/lib/iris/tests/unit/util/test_new_axis.py +++ b/lib/iris/tests/unit/util/test_new_axis.py @@ -1,4 +1,4 @@ -# (C) British Crown Copyright 2013 - 2014, Met Office +# (C) British Crown Copyright 2013 - 2015, Met Office # # This file is part of Iris. # @@ -17,6 +17,7 @@ """Test function :func:`iris.util.new_axis`.""" from __future__ import (absolute_import, division, print_function) +from six.moves import zip # Import iris.tests first so that some things can be initialised before # importing anything else. diff --git a/lib/iris/unit.py b/lib/iris/unit.py index ba91f9225f..4d492f53a1 100644 --- a/lib/iris/unit.py +++ b/lib/iris/unit.py @@ -26,6 +26,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range from contextlib import contextmanager import copy diff --git a/lib/iris/util.py b/lib/iris/util.py index a47b62c17d..5115df4d2a 100644 --- a/lib/iris/util.py +++ b/lib/iris/util.py @@ -20,6 +20,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import filter, range, zip import abc import collections @@ -602,7 +603,7 @@ def column_slices_generator(full_slice, ndims): # stg1: Take a copy of the full_slice specification, turning all tuples # into a full slice - if tuple_indices != range(len(full_slice)): + if tuple_indices != list(range(len(full_slice))): first_slice = list(full_slice) for tuple_index in tuple_indices: first_slice[tuple_index] = slice(None, None) diff --git a/tools/translator/__init__.py b/tools/translator/__init__.py index 6b4c8880e3..7b80a7917a 100644 --- a/tools/translator/__init__.py +++ b/tools/translator/__init__.py @@ -21,6 +21,7 @@ """ from __future__ import (absolute_import, division, print_function) +from six.moves import range from abc import ABCMeta, abstractmethod, abstractproperty from collections import deque, namedtuple