Commit 6da3cef6 authored by Simeon Doetsch's avatar Simeon Doetsch

Removed f-strings for compatibility with Python 3.5

parent bb8f1b09
......@@ -20,7 +20,7 @@ def parameter_generator(sim: Simulation, plot_func, output_path,
def generate_frame(sim, i, plot_func, output_path, plot_args, save_args):
fig = plot_func(sim[i], **plot_args)
fig.savefig(f"{output_path}{i:04d}.png", **save_args)
fig.savefig("{}{:04d}.png".format(output_path, i), **save_args)
plt.close(fig)
del sim[i]
......@@ -38,7 +38,7 @@ def generate_animation(sim: Simulation, plot_func, output_name: str='animation.m
os.mkdir('tmp')
render_frames_parallel(sim, plot_func, 'tmp/', plot_args, save_args)
subprocess.run(['ffmpeg', '-f', 'lavfi', '-i', 'anullsrc=stereo',
'-framerate', f'{framerate:d}', '-i', 'tmp/%04d.png',
'-framerate', '{:d}'.format(framerate), '-i', 'tmp/%04d.png',
'-shortest', '-c:v', 'libx264', '-pix_fmt', 'yuv420p',
'-c:a', 'aac', output_name])
subprocess.run(['rm', '-r', 'tmp'])
......@@ -24,11 +24,11 @@ def generate_coord_mapping(coordinates: str) -> dict:
}
}
if coordinates not in mappings:
raise NotImplementedError(f'Coordinate system {coordinates} not implemented')
raise NotImplementedError("Coordinate system {} not implemented".format(coordinates))
mapping = mappings[coordinates]
velocities = {}
for key, value in mapping.items():
velocities[f"v{key}"] = f"v{value}"
velocities["v"+key] = "v"+value
mapping.update(velocities)
return mapping
......@@ -55,11 +55,11 @@ def generate_tex_mapping(coordinates: str) -> dict:
}
}
if coordinates not in mappings:
raise NotImplementedError(f'Tex mappings for {coordinates} not implemented')
raise NotImplementedError("Tex mappings for {} not implemented".format(coordinates))
mapping = mappings[coordinates]
velocities = {}
for key, value in mapping:
velocities[f"v{key}"] = f"v_{value}"
velocities["v"+key] = "v_" + value
mapping.update(velocities)
mapping['rho'] = r'\rho'
mapping['prs'] = 'p'
......
......@@ -47,8 +47,8 @@ class Grid:
# save in grid datastructure
for i, xn in enumerate(x, start=1):
setattr(self, f"x{i}", xn[0])
setattr(self, f"dx{i}", xn[1])
setattr(self, "x{}".format(i), xn[0])
setattr(self, "dx{}".format(i), xn[1])
self.dims = tuple(dims)
shape = []
......@@ -70,10 +70,10 @@ class Grid:
mappings = object.__getattribute__(self, 'mappings')
return object.__getattribute__(self, mappings[name])
except KeyError:
raise AttributeError(f"{type(self)} has no attribute '{name}'")
raise AttributeError("{} has no attribute '{}'".format(type(self), name))
def __str__(self):
return f"PLUTO Grid, Dimensions {self.dims}"
return "PLUTO Grid, Dimensions {}".format(self.dims)
__repr__ = __str__
......@@ -103,7 +103,7 @@ class SimulationMetadata:
self.charsize = 8 if format == 'dbl' else 4
endianness = '<' if endianness == 'little' else '>'
self.binformat = f"{endianness}f{self.charsize}"
self.binformat = "{}f{}".format(endianness, self.charsize)
class Pluto_ini(OrderedDict):
"""Parser for Plutocode initialization file pluto.ini"""
......
......@@ -22,8 +22,8 @@ def plot(data: np.ndarray, grid: Grid, ax=None, label: str=None, figsize=None,
ax.set_ylabel('$y$')
else:
X, Y = grid.x1, grid.x2
ax.set_xlabel(f"${grid.mappings_tex['x1']}$")
ax.set_ylabel(f"${grid.mappings_tex['x2']}$")
ax.set_xlabel("${}$".format(grid.mappings_tex['x1']))
ax.set_ylabel("${}$".format(grid.mappings_tex['x2']))
im = ax.pcolormesh(X, Y, data.T, vmin=vmin, vmax=vmax, cmap=cmap)
ax.set_aspect(1)
......
......@@ -52,17 +52,17 @@ class PlutoData(object):
except AttributeError:
pass
raise AttributeError(f"{type(self)} has no attribute '{name}'")
raise AttributeError("{} has no attribute '{}'".format(type(self), name))
def _load_var(self, var):
"""Load data for var into memory. Read either var dbl file (multiple_files mode),
or, slice data from single dbl file"""
if self.file_mode == 'single':
filename = f"data.{self.n:04d}.{self.format}"
filename = "data.{n:04d}.{format}".format(n=self.n, format=self.format)
# byte offset of variable in dbl file
offset = self.charsize * self.size * self.vars.index(var)
elif self.file_mode == 'multiple':
filename = f"{var}.{self.n:04d}.{self.format}"
filename = "{var}.{:04d}.{srmat}".format(var=var, n=self.n, format=self.format)
offset = 0
with open(os.path.join(self.wdir, filename), 'rb') as f:
......@@ -82,9 +82,9 @@ class PlutoData(object):
try:
if coord[0] == 'v':
return f"$v_{{{self._latex(self.coord_names[int(coord[2])-1], 0)}}}$"
return "$v_{{{}}}$".format(self._latex(self.coord_names[int(coord[2])-1], 0))
if tags:
return f'${latex_map[coord]}$'
return '${}$'.format(latex_map[coord])
else:
return latex_map[coord]
except KeyError:
......@@ -99,17 +99,19 @@ class PlutoData(object):
else:
varname = None
return plot(var, self.grid, label=f"${self.grid.mappings_tex.get(varname, varname)}$", **kwargs)
return plot(var, self.grid, label="${}$".format(self.grid.mappings_tex.get(varname, varname)), **kwargs)
def __str__(self) -> None:
return f"""PlutoData, wdir: '{self.wdir}'
resolution: {self.dims}, {self.grid.coordinates} coordinates
file nr: {self.n}, time: {self.t}, simulation step: {self.nstep}
Variables: {self.vars}"""
return """PlutoData, wdir: '{wdir}'
resolution: {dims}, {cords} coordinates
file nr: {n}, time: {t}, simulation step: {nstep}
Variables: {vars}""".format(wdir=self.wdir, dims=self.dims, coord=self.grid.coordinates,
n=self.n, t=self.t, nstep=self.nstep, vars=self.vars)
def __repr__(self) -> None:
return f"PlutoData({self.n}, wdir='{self.wdir}', coordinates='{self.grid.coordinates}')"
return "PlutoData({n}, wdir='{wdir}', coordinates='{coords}')".format(n=self.n,
wdir=self.wdir, coords=self.grid.coordinates)
def __dir__(self) -> list:
return object.__dir__(self) + self.vars + list(self.grid.keys())
......@@ -48,23 +48,25 @@ class Simulation:
## Find data format
if format is None:
for f in self.supported_formats:
if os.path.exists(join(self.data_dir, f'{f}.out')):
if os.path.exists(join(self.data_dir, f+'.out')):
self.format = f
break
try:
self.format
except AttributeError:
raise FileNotFoundError(f'No Metadata file for formats {self.supported_formats} found in {self.data_dir}')
raise FileNotFoundError("No Metadata file for formats "
"{} found in {}".format(self.supported_formats, self.data_dir))
else:
if format not in self.supported_formats:
raise NotImplementedError(f"Format '{format}' not supported")
if os.path.exists(join(self.data_dir, f'{format}.out')):
raise NotImplementedError("Format '{}' not supported".format(format))
if os.path.exists(join(self.data_dir, '{}.out'.format(format))):
self.format = format
else:
raise FileNotFoundError(f"Metadata file {join(self.data_dir, f'{format}.out')} for format {format} not found")
raise FileNotFoundError("Metadata file {} "
"for format {} not found".format(join(self.data_dir, format+'.out'), format))
## Read metadata ##
self.metadata = SimulationMetadata(join(self.data_dir, f'{self.format}.out'), self.format)
self.metadata = SimulationMetadata(join(self.data_dir, '{}.out'.format(self.format)), self.format)
self.vars = self.metadata.vars
## Read grid coordinate system ##
......@@ -121,7 +123,7 @@ class Simulation:
except AttributeError:
raise
raise AttributeError(f"{type(self)} has no attribute '{name}'")
raise AttributeError("{} has no attribute '{}'".format(type(self), name))
def _index(self, key: int) -> int:
"""Checks if index is in range and implements negative indexing"""
......@@ -221,14 +223,17 @@ class Simulation:
self._data.clear()
def __str__(self) -> str:
return f"""PLUTO simulation, sim_dir: '{self.sim_dir}',
data_dir: '{self.data_dir}'
resolution: {self.dims}, {self.grid.coordinates} coordinates
data files: {self.n}, last time: {self.t[-1]}
Variables: {self.vars}"""
return """PLUTO simulation, sim_dir: '{sim_dir}',
data_dir: '{data_dir}'
resolution: {dims}, {coord} coordinates
data files: {n}, last time: {t}
Variables: {self.vars}""".format(sim_dir=self.sim_dir, data_dir=self.data_dir,
dims=self.dims, coord=self.grid.coordinates, n=self.n, t=self.t[-1],
vars=self.vars)
def __repr__(self) -> str:
return f"Simulation('{self.sim_dir}', format='{self.format}', coordinates='{self.grid.coordinates}')"
return "Simulation('{sim_dir}', format='{format}', coordinates='{coord}')".format(
sim_dir=self.sim_dir, format=self.format, coord=self.grid.coordinates)
def __dir__(self) -> list:
return object.__dir__(self) + self.vars + dir(self.metadata) + dir(self.grid)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment