Skip to content

Commit

Permalink
Upgrade to fstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
VeckoTheGecko committed Nov 29, 2024
1 parent 3c3b036 commit 2f67cf6
Show file tree
Hide file tree
Showing 13 changed files with 20 additions and 23 deletions.
2 changes: 1 addition & 1 deletion docs/examples/example_dask_chunk_OCMs.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def test_pop(mode, chunk_mode):
filenames = str(data_folder / "t.x1_SAMOC_flux.1690*.nc")
variables = {"U": "UVEL", "V": "VVEL", "W": "WVEL"}
timestamps = np.expand_dims(
np.array([np.datetime64("2000-%.2d-01" % m) for m in range(1, 7)]), axis=1
np.array([np.datetime64(f"2000-{m:02d}-01") for m in range(1, 7)]), axis=1
)
dimensions = {"lon": "ULON", "lat": "ULAT", "depth": "w_dep"}
chs = False
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/example_moving_eddies.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def moving_eddies_example(

# Execute for 1 week, with 1 hour timesteps and hourly output
runtime = timedelta(days=7)
print("MovingEddies: Advecting %d particles for %s" % (npart, str(runtime)))
print(f"MovingEddies: Advecting {npart} particles for {runtime}")
pset.execute(
method,
runtime=runtime,
Expand Down Expand Up @@ -177,7 +177,7 @@ def test_moving_eddies_fwdbwd(mode, mesh, tmpdir, npart=2):
runtime = timedelta(days=1)
dt = timedelta(minutes=5)
outputdt = timedelta(hours=1)
print("MovingEddies: Advecting %d particles for %s" % (npart, str(runtime)))
print(f"MovingEddies: Advecting {npart} particles for {runtime}")
outfile = tmpdir.join("EddyParticlefwd")
pset.execute(
method,
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/example_peninsula.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def peninsula_example(
out = (
pset.ParticleFile(name=outfile, outputdt=timedelta(hours=1)) if output else None
)
print("Peninsula: Advecting %d particles for %s" % (npart, str(time)))
print(f"Peninsula: Advecting {npart} particles for {time}")
pset.execute(k_adv + k_p, runtime=time, dt=dt, output_file=out)

if verbose:
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/example_stommel.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def stommel_example(

maxage = runtime.total_seconds() if maxage is None else maxage
fieldset.add_constant("maxage", maxage)
print("Stommel: Advecting %d particles for %s" % (npart, runtime))
print(f"Stommel: Advecting {npart} particles for {runtime}")
parcels.timer.psetinit.stop()
parcels.timer.psetrun = parcels.timer.Timer("Pset_run", parent=parcels.timer.pset)
pset.execute(
Expand Down
2 changes: 1 addition & 1 deletion parcels/compilation/codegenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def __init__(self, fieldset=None, ptype=JITParticle):

def get_tmp(self):
"""Create a new temporary variable name."""
tmp = "parcels_tmpvar%d" % self._tmp_counter
tmp = f"parcels_tmpvar{self._tmp_counter:d}"
self._tmp_counter += 1
self.tmp_vars += [tmp]
return tmp
Expand Down
6 changes: 3 additions & 3 deletions parcels/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -1242,7 +1242,7 @@ def _search_indices_curvilinear(self, x, y, z, ti=-1, time=-1, particle=None, se
(xi, yi) = self._reconnect_bnd_indices(xi, yi, grid.xdim, grid.ydim, grid.mesh)
it += 1
if it > maxIterSearch:
print("Correct cell not found after %d iterations" % maxIterSearch)
print(f"Correct cell not found after {maxIterSearch} iterations")

Check warning on line 1245 in parcels/field.py

View check run for this annotation

Codecov / codecov/patch

parcels/field.py#L1245

Added line #L1245 was not covered by tests
raise FieldOutOfBoundError(x, y, 0, field=self)
xsi = max(0.0, xsi)
eta = max(0.0, eta)
Expand Down Expand Up @@ -2532,13 +2532,13 @@ def __init__(self, name: str, F, V=None, W=None):
assert isinstance(Fi, Field) and isinstance(
Vi, Field
), "F, and V components of a NestedField must be Field"
self.append(VectorField(name + "_%d" % i, Fi, Vi))
self.append(VectorField(f"{name}_{i}", Fi, Vi))
else:
for i, Fi, Vi, Wi in zip(range(len(F)), F, V, W, strict=True):
assert (
isinstance(Fi, Field) and isinstance(Vi, Field) and isinstance(Wi, Field)
), "F, V and W components of a NestedField must be Field"
self.append(VectorField(name + "_%d" % i, Fi, Vi, Wi))
self.append(VectorField(f"{name}_{i}", Fi, Vi, Wi))

Check warning on line 2541 in parcels/field.py

View check run for this annotation

Codecov / codecov/patch

parcels/field.py#L2541

Added line #L2541 was not covered by tests
self.name = name

def __getitem__(self, key):
Expand Down
2 changes: 1 addition & 1 deletion parcels/kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def get_kernel_compile_files(self):
dyn_dir = mpi_comm.bcast(dyn_dir, root=0)
basename = cache_name if mpi_rank == 0 else None
basename = mpi_comm.bcast(basename, root=0)
basename = basename + "_%d" % mpi_rank
basename = f"{basename}_{mpi_rank}"
else:
cache_name = (
self._cache_key
Expand Down
2 changes: 1 addition & 1 deletion parcels/particle.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def __del__(self):

def __repr__(self):
time_string = "not_yet_set" if self.time is None or np.isnan(self.time) else f"{self.time:f}"
p_string = "P[%d](lon=%f, lat=%f, depth=%f, " % (self.id, self.lon, self.lat, self.depth)
p_string = f"P[{self.id}](lon={self.lon:f}, lat={self.lat:f}, depth={self.depth:f}, "

Check warning on line 204 in parcels/particle.py

View check run for this annotation

Codecov / codecov/patch

parcels/particle.py#L204

Added line #L204 was not covered by tests
for var in vars(type(self)):
if var in ["lon_nextloop", "lat_nextloop", "depth_nextloop", "time_nextloop"]:
continue
Expand Down
2 changes: 1 addition & 1 deletion parcels/particledata.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ def getPType(self):

def __repr__(self):
time_string = "not_yet_set" if self.time is None or np.isnan(self.time) else f"{self.time:f}"
p_string = "P[%d](lon=%f, lat=%f, depth=%f, " % (self.id, self.lon, self.lat, self.depth)
p_string = f"P[{self.id}](lon={self.lon:f}, lat={self.lat:f}, depth={self.depth:f}, "
for var in self._pcoll.ptype.variables:
if var.name in [
"lon_nextloop",
Expand Down
2 changes: 1 addition & 1 deletion parcels/particleset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1193,7 +1193,7 @@ def execute(
raise RuntimeError(
"Field writing during execution only works for Fields with one snapshot in time"
)
fldfilename = str(output_file.fname).replace(".zarr", "_%.4d" % fld.to_write)
fldfilename = str(output_file.fname).replace(".zarr", f"_{fld.to_write:04d}")
fld.write(fldfilename)
fld.to_write += 1

Expand Down
6 changes: 3 additions & 3 deletions parcels/tools/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ def print_tree_sequential(self, step=0, root_time=0, parent_time=0):
time = self.local_time()
if step == 0:
root_time = time
print(("(%3d%%)" % round(time / root_time * 100)), end="")
print(f"({round(time / root_time * 100):3d}%)", end="")
print(" " * (step + 1), end="")
if step > 0:
print("(%3d%%) " % round(time / parent_time * 100), end="")
print(f"({round(time / parent_time * 100):3d}%) ", end="")
t_str = f"{time:1.3e} s" if root_time < 300 else datetime.timedelta(seconds=time)
print(f"Timer {(self._name).ljust(20 - 2*step + 7*(step == 0))}: {t_str}")
for child in self._children:
Expand All @@ -64,6 +64,6 @@ def print_tree(self, step=0, root_time=0, parent_time=0):
else:
for iproc in range(mpi_size):
if iproc == mpi_rank:
print("Proc %d/%d - Timer tree" % (mpi_rank, mpi_size))
print(f"Proc {mpi_rank}/{mpi_size} - Timer tree")

Check warning on line 67 in parcels/tools/timer.py

View check run for this annotation

Codecov / codecov/patch

parcels/tools/timer.py#L67

Added line #L67 was not covered by tests
self.print_tree_sequential(step, root_time, parent_time)
mpi_comm.Barrier()
2 changes: 1 addition & 1 deletion tests/test_kernel_language.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ def test_print(fieldset_unit_mesh, mode, capfd):
def kernel(particle, fieldset, time):
particle.p = 1e-3
tmp = 5
print("%d %f %f" % (particle.id, particle.p, tmp))
print(f"{particle.id} {particle.p:f} {tmp:f}")

Check warning on line 279 in tests/test_kernel_language.py

View check run for this annotation

Codecov / codecov/patch

tests/test_kernel_language.py#L279

Added line #L279 was not covered by tests

pset.execute(kernel, endtime=1.0, dt=1.0, verbose_progress=False)
out, err = capfd.readouterr()
Expand Down
9 changes: 3 additions & 6 deletions tests/test_mpirun.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,10 @@ def test_mpi_run(tmpdir, repeatdt, maxage, nump):
outputNoMPI = tmpdir.join("StommelNoMPI.zarr")

os.system(
"mpirun -np 2 python %s -p %d -o %s -r %d -a %d -wf False -cpf True"
% (stommel_file, nump, outputMPI_partition_function, repeatdt, maxage)
f"mpirun -np 2 python {stommel_file} -p {nump} -o {outputMPI_partition_function} -r {repeatdt} -a {maxage} -wf False -cpf True"
)
os.system(
"mpirun -np 2 python %s -p %d -o %s -r %d -a %d -wf False" % (stommel_file, nump, outputMPI, repeatdt, maxage)
)
os.system("python %s -p %d -o %s -r %d -a %d -wf False" % (stommel_file, nump, outputNoMPI, repeatdt, maxage))
os.system(f"mpirun -np 2 python {stommel_file} -p {nump} -o {outputMPI} -r {repeatdt} -a {maxage} -wf False")
os.system(f"python {stommel_file} -p {nump} -o {outputNoMPI} -r {repeatdt} -a {maxage} -wf False")

ds2 = xr.open_zarr(outputNoMPI)

Expand Down

0 comments on commit 2f67cf6

Please sign in to comment.