Skip to content

Commit

Permalink
Merge pull request #1206 from OceanParcels/fixing-pep-for-flake8-5
Browse files Browse the repository at this point in the history
Fixing new flake8 requirements
  • Loading branch information
erikvansebille committed Aug 1, 2022
2 parents 03208e5 + 9320208 commit d7b3848
Show file tree
Hide file tree
Showing 21 changed files with 95 additions and 95 deletions.
4 changes: 2 additions & 2 deletions parcels/compilation/codegenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -658,9 +658,9 @@ def visit_If(self, node):

def visit_Compare(self, node):
self.visit(node.left)
assert(len(node.ops) == 1)
assert (len(node.ops) == 1)
self.visit(node.ops[0])
assert(len(node.comparators) == 1)
assert (len(node.comparators) == 1)
self.visit(node.comparators[0])
node.ccode = "%s %s %s" % (node.left.ccode, node.ops[0].ccode,
node.comparators[0].ccode)
Expand Down
8 changes: 4 additions & 4 deletions parcels/examples/example_dask_chunk_OCMs.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,8 @@ def test_globcurrent_2D(mode, chunk_mode):
elif chunk_mode == 'failsafe': # chunking time but not lat
assert (len(field_set.U.grid.load_chunk) != 1)
assert (len(field_set.V.grid.load_chunk) != 1)
assert(abs(pset[0].lon - 23.8) < 1)
assert(abs(pset[0].lat - -35.3) < 1)
assert abs(pset[0].lon - 23.8) < 1
assert abs(pset[0].lat - -35.3) < 1


@pytest.mark.parametrize('mode', ['jit'])
Expand Down Expand Up @@ -382,8 +382,8 @@ def test_ofam_3D(mode, chunk_mode):
matching_fields = (field_set.U.grid.chunk_info == field_set.V.grid.chunk_info)
matching_uniformblocks = (len(field_set.U.grid.load_chunk) == (1 * int(math.ceil(1.0/60.0)) * int(math.ceil(601.0/50.0)) * int(math.ceil(2001.0/100.0))))
assert (matching_uniformblocks or (matching_fields and matching_numblocks))
assert(abs(pset[0].lon - 173) < 1)
assert(abs(pset[0].lat - 11) < 1)
assert abs(pset[0].lon - 173) < 1
assert abs(pset[0].lat - 11) < 1


@pytest.mark.parametrize('mode', ['jit'])
Expand Down
12 changes: 6 additions & 6 deletions parcels/examples/example_globcurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ def set_globcurrent_fieldset(filename=None, indices=None, deferred_load=True, us
@pytest.mark.parametrize('use_xarray', [True, False])
def test_globcurrent_fieldset(use_xarray):
fieldset = set_globcurrent_fieldset(use_xarray=use_xarray)
assert(fieldset.U.lon.size == 81)
assert(fieldset.U.lat.size == 41)
assert(fieldset.V.lon.size == 81)
assert(fieldset.V.lat.size == 41)
assert fieldset.U.lon.size == 81
assert fieldset.U.lat.size == 41
assert fieldset.V.lon.size == 81
assert fieldset.V.lat.size == 41

if not use_xarray:
indices = {'lon': [5], 'lat': range(20, 30)}
Expand Down Expand Up @@ -88,8 +88,8 @@ def test_globcurrent_particles(mode, use_xarray):

pset.execute(AdvectionRK4, runtime=delta(days=1), dt=delta(minutes=5))

assert(abs(pset[0].lon - 23.8) < 1)
assert(abs(pset[0].lat - -35.3) < 1)
assert abs(pset[0].lon - 23.8) < 1
assert abs(pset[0].lat - -35.3) < 1


@pytest.mark.parametrize('mode', ['scipy', 'jit'])
Expand Down
4 changes: 2 additions & 2 deletions parcels/examples/example_moving_eddies.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ def test_moving_eddies_fieldset(mode, mesh, tmpdir):
assert (pset[0].lon < 2.2e5 and 1.1e5 < pset[0].lat < 1.2e5)
assert (pset[1].lon < 2.2e5 and 3.7e5 < pset[1].lat < 3.8e5)
else:
assert(pset[0].lon < 2.0 and 46.2 < pset[0].lat < 46.25)
assert(pset[1].lon < 2.0 and 48.8 < pset[1].lat < 48.85)
assert (pset[0].lon < 2.0 and 46.2 < pset[0].lat < 46.25)
assert (pset[1].lon < 2.0 and 48.8 < pset[1].lat < 48.85)


def fieldsetfile(mesh, tmpdir):
Expand Down
6 changes: 3 additions & 3 deletions parcels/examples/example_ofam.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def set_ofam_fieldset(deferred_load=True, use_xarray=False):
def test_ofam_fieldset_fillvalues(use_xarray):
fieldset = set_ofam_fieldset(deferred_load=False, use_xarray=use_xarray)
# V.data[0, 0, 150] is a landpoint, that makes NetCDF4 generate a masked array, instead of an ndarray
assert(fieldset.V.data[0, 0, 150] == 0)
assert fieldset.V.data[0, 0, 150] == 0


@pytest.mark.parametrize('dt', [delta(minutes=-5), delta(minutes=5)])
Expand Down Expand Up @@ -66,5 +66,5 @@ def test_ofam_particles(mode, use_xarray):

pset.execute(AdvectionRK4, runtime=delta(days=10), dt=delta(minutes=5))

assert(abs(pset[0].lon - 173) < 1)
assert(abs(pset[0].lat - 11) < 1)
assert abs(pset[0].lon - 173) < 1
assert abs(pset[0].lat - 11) < 1
10 changes: 5 additions & 5 deletions parcels/examples/example_peninsula.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,10 @@ def test_peninsula_fieldset(mode, mesh, tmpdir):
pset = peninsula_example(fieldset, outfile, 5, mode=mode, degree=1)
# Test advection accuracy by comparing streamline values
err_adv = np.abs(pset.p_start - pset.p)
assert(err_adv <= 1.e-3).all()
assert (err_adv <= 1.e-3).all()
# Test Field sampling accuracy by comparing kernel against Field sampling
err_smpl = np.array([abs(pset.p[i] - pset.fieldset.P[0., pset.depth[i], pset.lat[i], pset.lon[i]]) for i in range(pset.size)])
assert(err_smpl <= 1.e-3).all()
assert (err_smpl <= 1.e-3).all()


@pytest.mark.parametrize('mode', ['scipy']) # Analytical Advection only implemented in Scipy mode
Expand All @@ -161,7 +161,7 @@ def test_peninsula_fieldset_AnalyticalAdvection(mode, mesh, tmpdir):
method=AdvectionAnalytical)
# Test advection accuracy by comparing streamline values
err_adv = np.array([abs(p.p_start - p.p) for p in pset])
assert(err_adv <= 1.e-1).all()
assert (err_adv <= 1.e-1).all()


def fieldsetfile(mesh, tmpdir):
Expand All @@ -182,10 +182,10 @@ def test_peninsula_file(mode, mesh, tmpdir):
pset = peninsula_example(fieldset, outfile, 5, mode=mode, degree=1)
# Test advection accuracy by comparing streamline values
err_adv = np.abs(pset.p_start - pset.p)
assert(err_adv <= 1.e-3).all()
assert (err_adv <= 1.e-3).all()
# Test Field sampling accuracy by comparing kernel against Field sampling
err_smpl = np.array([abs(pset.p[i] - pset.fieldset.P[0., pset.depth[i], pset.lat[i], pset.lon[i]]) for i in range(pset.size)])
assert(err_smpl <= 1.e-3).all()
assert (err_smpl <= 1.e-3).all()


if __name__ == "__main__":
Expand Down
12 changes: 6 additions & 6 deletions parcels/examples/example_radial_rotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ def radial_rotation_fieldset(xdim=200, ydim=200): # Define 2D flat, square fiel
for j in range(lat.size):

r = np.sqrt((lon[i]-x0)**2 + (lat[j]-y0)**2) # Define radial displacement.
assert(r >= 0.)
assert(r <= np.sqrt(x0**2 + y0**2))
assert r >= 0.
assert r <= np.sqrt(x0**2 + y0**2)

theta = math.atan2((lat[j]-y0), (lon[i]-x0)) # Define the polar angle.
assert(abs(theta) <= np.pi)
assert abs(theta) <= np.pi

U[j, i] = r * math.sin(theta) * omega
V[j, i] = -r * math.cos(theta) * omega
Expand Down Expand Up @@ -75,10 +75,10 @@ def test_rotation_example(mode, tmpdir):
fieldset = radial_rotation_fieldset()
outfile = tmpdir.join("RadialParticle")
pset = rotation_example(fieldset, outfile, mode=mode)
assert(pset[0].lon == 30. and pset[0].lat == 30.) # Particle at centre of Field remains stationary.
assert (pset[0].lon == 30. and pset[0].lat == 30.) # Particle at centre of Field remains stationary.
vals = true_values(pset.time[1])
assert(np.allclose(pset[1].lon, vals[0], 1e-5)) # Check advected values against calculated values.
assert(np.allclose(pset[1].lat, vals[1], 1e-5))
assert np.allclose(pset[1].lon, vals[0], 1e-5) # Check advected values against calculated values.
assert np.allclose(pset[1].lat, vals[1], 1e-5)


if __name__ == "__main__":
Expand Down
4 changes: 2 additions & 2 deletions parcels/examples/example_stommel.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ def test_stommel_fieldset(pset_mode, mode, grid_type, tmpdir):
assert np.allclose(psetRK4.lon, psetRK45.lon, rtol=1e-3)
assert np.allclose(psetRK4.lat, psetRK45.lat, rtol=1.1e-3)
err_adv = np.abs(psetRK4.p_start - psetRK4.p)
assert(err_adv <= 1.e-1).all()
assert (err_adv <= 1.e-1).all()
err_smpl = np.array([abs(psetRK4.p[i] - psetRK4.fieldset.P[0., psetRK4.lon[i], psetRK4.lat[i], psetRK4.depth[i]]) for i in range(psetRK4.size)])
assert(err_smpl <= 1.e-1).all()
assert (err_smpl <= 1.e-1).all()
timer.stommel.stop()
timer.root.stop()
timer.root.print_tree()
Expand Down
2 changes: 1 addition & 1 deletion parcels/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ def from_netcdf(cls, filenames, variable, dimensions, indices=None, grid=None,
elif isinstance(filenames, dict):
for k in filenames.keys():
if k not in ['lat', 'lon', 'depth', 'time']:
assert(len(filenames[k]) == len(timestamps)), 'Outer dimension of timestamps should correspond to number of files.'
assert (len(filenames[k]) == len(timestamps)), 'Outer dimension of timestamps should correspond to number of files.'
else:
raise TypeError("Filenames type is inconsistent with manual timestamp provision."
+ "Should be dict or list")
Expand Down
2 changes: 1 addition & 1 deletion parcels/fieldset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@ def computeTimeChunk(self, time, dt):
data = f.computeTimeChunk(data, tind)
data = f.rescale_and_set_minmax(data)

if(isinstance(f.data, DeferredArray)):
if (isinstance(f.data, DeferredArray)):
f.data = DeferredArray()
f.data = f.reshape(data)
if not f.chunk_set:
Expand Down
20 changes: 10 additions & 10 deletions parcels/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,11 +262,11 @@ class RectilinearGrid(Grid):
"""

def __init__(self, lon, lat, time, time_origin, mesh):
assert(isinstance(lon, np.ndarray) and len(lon.shape) <= 1), 'lon is not a numpy vector'
assert(isinstance(lat, np.ndarray) and len(lat.shape) <= 1), 'lat is not a numpy vector'
assert (isinstance(lon, np.ndarray) and len(lon.shape) <= 1), 'lon is not a numpy vector'
assert (isinstance(lat, np.ndarray) and len(lat.shape) <= 1), 'lat is not a numpy vector'
assert (isinstance(time, np.ndarray) or not time), 'time is not a numpy array'
if isinstance(time, np.ndarray):
assert(len(time.shape) == 1), 'time is not a vector'
assert (len(time.shape) == 1), 'time is not a vector'

super(RectilinearGrid, self).__init__(lon, lat, time, time_origin, mesh)
self.xdim = self.lon.size
Expand Down Expand Up @@ -328,7 +328,7 @@ class RectilinearZGrid(RectilinearGrid):
def __init__(self, lon, lat, depth=None, time=None, time_origin=None, mesh='flat'):
super(RectilinearZGrid, self).__init__(lon, lat, time, time_origin, mesh)
if isinstance(depth, np.ndarray):
assert(len(depth.shape) <= 1), 'depth is not a vector'
assert (len(depth.shape) <= 1), 'depth is not a vector'

self.gtype = GridCode.RectilinearZGrid
self.depth = np.zeros(1, dtype=np.float32) if depth is None else depth
Expand Down Expand Up @@ -363,7 +363,7 @@ class RectilinearSGrid(RectilinearGrid):

def __init__(self, lon, lat, depth, time=None, time_origin=None, mesh='flat'):
super(RectilinearSGrid, self).__init__(lon, lat, time, time_origin, mesh)
assert(isinstance(depth, np.ndarray) and len(depth.shape) in [3, 4]), 'depth is not a 3D or 4D numpy array'
assert (isinstance(depth, np.ndarray) and len(depth.shape) in [3, 4]), 'depth is not a 3D or 4D numpy array'

self.gtype = GridCode.RectilinearSGrid
self.depth = depth
Expand All @@ -386,11 +386,11 @@ def __init__(self, lon, lat, depth, time=None, time_origin=None, mesh='flat'):
class CurvilinearGrid(Grid):

def __init__(self, lon, lat, time=None, time_origin=None, mesh='flat'):
assert(isinstance(lon, np.ndarray) and len(lon.squeeze().shape) == 2), 'lon is not a 2D numpy array'
assert(isinstance(lat, np.ndarray) and len(lat.squeeze().shape) == 2), 'lat is not a 2D numpy array'
assert (isinstance(lon, np.ndarray) and len(lon.squeeze().shape) == 2), 'lon is not a 2D numpy array'
assert (isinstance(lat, np.ndarray) and len(lat.squeeze().shape) == 2), 'lat is not a 2D numpy array'
assert (isinstance(time, np.ndarray) or not time), 'time is not a numpy array'
if isinstance(time, np.ndarray):
assert(len(time.shape) == 1), 'time is not a vector'
assert (len(time.shape) == 1), 'time is not a vector'

lon = lon.squeeze()
lat = lat.squeeze()
Expand Down Expand Up @@ -458,7 +458,7 @@ class CurvilinearZGrid(CurvilinearGrid):
def __init__(self, lon, lat, depth=None, time=None, time_origin=None, mesh='flat'):
super(CurvilinearZGrid, self).__init__(lon, lat, time, time_origin, mesh)
if isinstance(depth, np.ndarray):
assert(len(depth.shape) == 1), 'depth is not a vector'
assert (len(depth.shape) == 1), 'depth is not a vector'

self.gtype = GridCode.CurvilinearZGrid
self.depth = np.zeros(1, dtype=np.float32) if depth is None else depth
Expand Down Expand Up @@ -492,7 +492,7 @@ class CurvilinearSGrid(CurvilinearGrid):

def __init__(self, lon, lat, depth, time=None, time_origin=None, mesh='flat'):
super(CurvilinearSGrid, self).__init__(lon, lat, time, time_origin, mesh)
assert(isinstance(depth, np.ndarray) and len(depth.shape) in [3, 4]), 'depth is not a 4D numpy array'
assert (isinstance(depth, np.ndarray) and len(depth.shape) in [3, 4]), 'depth is not a 4D numpy array'

self.gtype = GridCode.CurvilinearSGrid
self.depth = depth
Expand Down
6 changes: 3 additions & 3 deletions parcels/particleset/particlesetaos.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,9 @@ def ObjectClass_sizeof_forward(self):
self.repeatdt = repeatdt.total_seconds() if isinstance(repeatdt, delta) else repeatdt
if self.repeatdt:
if self.repeatdt <= 0:
raise('Repeatdt should be > 0')
raise 'Repeatdt should be > 0'
if time[0] and not np.allclose(time, time[0]):
raise ('All Particle.time should be the same when repeatdt is not None')
raise 'All Particle.time should be the same when repeatdt is not None'
self.repeatpclass = pclass
self.repeatkwargs = kwargs

Expand Down Expand Up @@ -662,7 +662,7 @@ def search_kernel(particle, fieldset, time):
for i, p in enumerate(self):
try: # breaks if either p.xi, p.yi, p.zi, p.ti do not exist (in scipy) or field not in fieldset
if p.ti[field.igrid] < 0: # xi, yi, zi, ti, not initialised
raise('error')
raise 'error'
xi = p.xi[field.igrid]
yi = p.yi[field.igrid]
except:
Expand Down
6 changes: 3 additions & 3 deletions parcels/particleset/particlesetsoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ def ArrayClass_init(self, *args, **kwargs):
self.repeatdt = repeatdt.total_seconds() if isinstance(repeatdt, delta) else repeatdt
if self.repeatdt:
if self.repeatdt <= 0:
raise('Repeatdt should be > 0')
raise 'Repeatdt should be > 0'
if time[0] and not np.allclose(time, time[0]):
raise ('All Particle.time should be the same when repeatdt is not None')
raise 'All Particle.time should be the same when repeatdt is not None'
self.repeatpclass = pclass
self.repeatkwargs = kwargs

Expand Down Expand Up @@ -626,7 +626,7 @@ def search_kernel(particle, fieldset, time):
for i, p in enumerate(self):
try: # breaks if either p.xi, p.yi, p.zi, p.ti do not exist (in scipy) or field not in fieldset
if p.ti[field.igrid] < 0: # xi, yi, zi, ti, not initialised
raise('error')
raise 'error'
xi = p.xi[field.igrid]
yi = p.yi[field.igrid]
except:
Expand Down
2 changes: 1 addition & 1 deletion parcels/scripts/plottrajectoriesfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def plotTrajectoriesFile(filename, mode='2d', tracerfile=None, tracerfield='P',
z = np.ma.filled(pfile.variables['z'], np.nan)
mesh = pfile.attrs['parcels_mesh'] if 'parcels_mesh' in pfile.attrs else 'spherical'

if(recordedvar is not None):
if recordedvar is not None:
record = np.ma.filled(pfile.variables[recordedvar], np.nan)
pfile.close()

Expand Down
4 changes: 2 additions & 2 deletions parcels/tools/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ def __init__(self, name, parent=None, start=True):

def start(self):
if self._parent:
assert(self._parent._start), ("Timer '%s' cannot be started. Its parent timer does not run" % self._name)
assert self._parent._start, ("Timer '%s' cannot be started. Its parent timer does not run" % self._name)
if self._start is not None:
raise RuntimeError('Timer %s cannot start since it is already running' % self._name)
self._start = time.time()

def stop(self):
assert(self._start), ("Timer '%s' was stopped before being started" % self._name)
assert self._start, ("Timer '%s' was stopped before being started" % self._name)
self._t += time.time() - self._start
self._start = None

Expand Down
8 changes: 4 additions & 4 deletions tests/test_advection.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def periodicBC(particle, fieldset, time):
def test_advection_periodic_zonal(pset_mode, mode, xdim=100, ydim=100, halosize=3):
fieldset = periodicfields(xdim, ydim, uvel=1., vvel=0.)
fieldset.add_periodic_halo(zonal=True, halosize=halosize)
assert(len(fieldset.U.lon) == xdim + 2 * halosize)
assert len(fieldset.U.lon) == xdim + 2 * halosize

pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode], lon=[0.5], lat=[0.5])
pset.execute(AdvectionRK4 + pset.Kernel(periodicBC), runtime=delta(hours=20), dt=delta(seconds=30))
Expand All @@ -193,7 +193,7 @@ def test_advection_periodic_zonal(pset_mode, mode, xdim=100, ydim=100, halosize=
def test_advection_periodic_meridional(pset_mode, mode, xdim=100, ydim=100):
fieldset = periodicfields(xdim, ydim, uvel=0., vvel=1.)
fieldset.add_periodic_halo(meridional=True)
assert(len(fieldset.U.lat) == ydim + 10) # default halo size is 5 grid points
assert len(fieldset.U.lat) == ydim + 10 # default halo size is 5 grid points

pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode], lon=[0.5], lat=[0.5])
pset.execute(AdvectionRK4 + pset.Kernel(periodicBC), runtime=delta(hours=20), dt=delta(seconds=30))
Expand All @@ -205,8 +205,8 @@ def test_advection_periodic_meridional(pset_mode, mode, xdim=100, ydim=100):
def test_advection_periodic_zonal_meridional(pset_mode, mode, xdim=100, ydim=100):
fieldset = periodicfields(xdim, ydim, uvel=1., vvel=1.)
fieldset.add_periodic_halo(zonal=True, meridional=True)
assert(len(fieldset.U.lat) == ydim + 10) # default halo size is 5 grid points
assert(len(fieldset.U.lon) == xdim + 10) # default halo size is 5 grid points
assert len(fieldset.U.lat) == ydim + 10 # default halo size is 5 grid points
assert len(fieldset.U.lon) == xdim + 10 # default halo size is 5 grid points
assert np.allclose(np.diff(fieldset.U.lat), fieldset.U.lat[1]-fieldset.U.lat[0], rtol=0.001)
assert np.allclose(np.diff(fieldset.U.lon), fieldset.U.lon[1]-fieldset.U.lon[0], rtol=0.001)

Expand Down
2 changes: 1 addition & 1 deletion tests/test_diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def test_fieldKh_SpatiallyVaryingDiffusion(mesh, mode, pset_mode, kernel, xdim=2
tol = 2000*mesh_conversion # effectively 2000 m errors (because of low numbers of particles)
assert np.allclose(np.mean(lons), 0, atol=tol)
assert np.allclose(np.mean(lats), 0, atol=tol)
assert(stats.skew(lons) > stats.skew(lats))
assert stats.skew(lons) > stats.skew(lats)


@pytest.mark.parametrize('mode', ['scipy', 'jit'])
Expand Down
Loading

0 comments on commit d7b3848

Please sign in to comment.