Used f-strings to make the code in cmds_multiuse.py much better

这个提交包含在:
Sai Suraj
2023-04-15 11:26:38 +05:30
父节点 9dbf795356
当前提交 740ddb06ed

查看文件

@@ -59,9 +59,9 @@ class UserObjectMulti:
"""Readable user string as per hash commands."""
s = ''
for _, v in self.kwargs.items():
if isinstance(v, tuple) or isinstance(v, list):
if isinstance(v, (tuple, list)):
v = ' '.join([str(el) for el in v])
s += str(v) + ' '
s += f'{str(v)} '
return f'{self.hash}: {s[:-1]}'
@@ -75,7 +75,7 @@ class UserObjectMulti:
def params_str(self):
"""Readable string of parameters given to object."""
return self.hash + ': ' + str(self.kwargs)
return f'{self.hash}: {str(self.kwargs)}'
def grid_name(self, grid):
"""Returns subgrid name for use with logging info. Returns an empty
@@ -112,12 +112,14 @@ class Waveform(UserObjectMulti):
try:
wavetype = self.kwargs['wave_type'].lower()
except KeyError:
logger.exception(self.params_str() + (f" must have one of the "
f"following types {','.join(WaveformUser.types)}."))
logger.exception(
f"{self.params_str()} must have one of the following types {','.join(WaveformUser.types)}."
)
raise
if wavetype not in WaveformUser.types:
logger.exception(self.params_str() + (f" must have one of the "
f"following types {','.join(WaveformUser.types)}."))
logger.exception(
f"{self.params_str()} must have one of the following types {','.join(WaveformUser.types)}."
)
raise ValueError
if wavetype != 'user':
@@ -815,16 +817,14 @@ class Rx(UserObjectMulti):
outputs = [self.kwargs['outputs']]
except KeyError:
# If no ID or outputs are specified, use default
r.ID = (r.__class__.__name__ + '(' + str(r.xcoord) + ',' +
str(r.ycoord) + ',' + str(r.zcoord) + ')')
r.ID = f'{r.__class__.__name__}({str(r.xcoord)},{str(r.ycoord)},{str(r.zcoord)})'
for key in RxUser.defaultoutputs:
r.outputs[key] = np.zeros(grid.iterations,
dtype=config.sim_config.dtypes['float_or_double'])
else:
outputs.sort()
# Get allowable outputs
if (config.sim_config.general['solver'] =='cuda' or
config.sim_config.general['solver'] =='opencl'):
if config.sim_config.general['solver'] in ['cuda', 'opencl']:
allowableoutputs = RxUser.allowableoutputs_dev
else:
allowableoutputs = RxUser.allowableoutputs
@@ -834,15 +834,14 @@ class Rx(UserObjectMulti):
r.outputs[field] = np.zeros(grid.iterations,
dtype=config.sim_config.dtypes['float_or_double'])
else:
logger.exception(self.params_str() + ' contains an '
'output type that is not allowable. '
'Allowable outputs in current context are '
f'{allowableoutputs}.')
logger.exception(
f'{self.params_str()} contains an output type that is not allowable. Allowable outputs in current context are {allowableoutputs}.'
)
raise ValueError
logger.info(self.grid_name(grid) + f"Receiver at {p2[0]:g}m, "
f"{p2[1]:g}m, {p2[2]:g}m with output component(s) "
f"{', '.join(r.outputs)} created.")
logger.info(
f"{self.grid_name(grid)}Receiver at {p2[0]:g}m, {p2[1]:g}m, {p2[2]:g}m with output component(s) {', '.join(r.outputs)} created."
)
grid.rxs.append(r)
@@ -909,10 +908,9 @@ class RxArray(UserObjectMulti):
'not be less than the spatial discretisation.')
raise ValueError
logger.info(self.grid_name(grid) + f'Receiver array {p3[0]:g}m, '
f'{p3[1]:g}m, {p3[2]:g}m, to {p4[0]:g}m, {p4[1]:g}m, '
f'{p4[2]:g}m with steps {dx * grid.dx:g}m, '
f'{dy * grid.dy:g}m, {dz * grid.dz:g}m')
logger.info(
f'{self.grid_name(grid)}Receiver array {p3[0]:g}m, {p3[1]:g}m, {p3[2]:g}m, to {p4[0]:g}m, {p4[1]:g}m, {p4[2]:g}m with steps {dx * grid.dx:g}m, {dy * grid.dy:g}m, {dz * grid.dz:g}m'
)
for x in range(xs, xf + 1, dx):
for y in range(ys, yf + 1, dy):
@@ -928,8 +926,7 @@ class RxArray(UserObjectMulti):
p5 = np.array([x, y, z])
p5 = uip.descretised_to_continuous(p5)
p5 = uip.round_to_grid_static_point(p5)
r.ID = (r.__class__.__name__ + '(' + str(x) + ',' +
str(y) + ',' + str(z) + ')')
r.ID = f'{r.__class__.__name__}({str(x)},{str(y)},{str(z)})'
for key in RxUser.defaultoutputs:
r.outputs[key] = np.zeros(grid.iterations, dtype=config.sim_config.dtypes['float_or_double'])
logger.info(f" Receiver at {p5[0]:g}m, {p5[1]:g}m, "
@@ -984,7 +981,7 @@ class Snapshot(UserObjectMulti):
p4 = uip.round_to_grid_static_point(p2)
p1, p2 = uip.check_box_points(p1, p2, self.params_str())
except ValueError:
logger.exception(self.params_str() + ' point is outside the domain.')
logger.exception(f'{self.params_str()} point is outside the domain.')
raise
xs, ys, zs = p1
xf, yf, zf = p2
@@ -1025,10 +1022,9 @@ class Snapshot(UserObjectMulti):
# Check and set output names
for output in tmp:
if output not in SnapshotUser.allowableoutputs.keys():
logger.exception(self.params_str() + " contains an "
"output type that is not allowable. "
"Allowable outputs in current context are "
f"{', '.join(SnapshotUser.allowableoutputs.keys())}.")
logger.exception(
f"{self.params_str()} contains an output type that is not allowable. Allowable outputs in current context are {', '.join(SnapshotUser.allowableoutputs.keys())}."
)
raise ValueError
else:
outputs[output] = True
@@ -1045,7 +1041,7 @@ class Snapshot(UserObjectMulti):
'be less than the spatial discretisation.')
raise ValueError
if iterations <= 0 or iterations > grid.iterations:
logger.exception(self.params_str() + ' time value is not valid.')
logger.exception(f'{self.params_str()} time value is not valid.')
raise ValueError
s = SnapshotUser(xs, ys, zs, xf, yf, zf, dx, dy, dz, iterations,
@@ -1086,39 +1082,40 @@ class Material(UserObjectMulti):
sm = self.kwargs['sm']
material_id = self.kwargs['id']
except KeyError:
logger.exception(self.params_str() + ' requires exactly five '
'parameters.')
logger.exception(f'{self.params_str()} requires exactly five parameters.')
raise
if er < 1:
logger.exception(self.params_str() + ' requires a positive value '
'of one or greater for static (DC) permittivity.')
logger.exception(
f'{self.params_str()} requires a positive value of one or greater for static (DC) permittivity.'
)
raise ValueError
if se != 'inf':
se = float(se)
if se < 0:
logger.exception(self.params_str() + ' requires a positive '
'value for electric conductivity.')
logger.exception(
f'{self.params_str()} requires a positive value for electric conductivity.'
)
raise ValueError
else:
se = float('inf')
if mr < 1:
logger.exception(self.params_str() + ' requires a positive value '
'of one or greater for magnetic permeability.')
logger.exception(
f'{self.params_str()} requires a positive value of one or greater for magnetic permeability.'
)
raise ValueError
if sm < 0:
logger.exception(self.params_str() + ' requires a positive value '
'for magnetic loss.')
logger.exception(
f'{self.params_str()} requires a positive value for magnetic loss.'
)
raise ValueError
if any(x.ID == material_id for x in grid.materials):
logger.exception(self.params_str() + f' with ID {material_id} '
'already exists')
logger.exception(f'{self.params_str()} with ID {material_id} already exists')
raise ValueError
# Create a new instance of the Material class material
# (start index after pec & free_space)
m = MaterialUser(len(grid.materials), material_id)
m.er = er
m.se = se
m.mr = mr
m.sm = sm
@@ -1127,9 +1124,10 @@ class Material(UserObjectMulti):
if m.se == float('inf'):
m.averagable = False
logger.info(self.grid_name(grid) + f'Material {m.ID} with '
f'eps_r={m.er:g}, sigma={m.se:g} S/m; mu_r={m.mr:g}, '
f'sigma*={m.sm:g} Ohm/m created.')
m.er = er
logger.info(
f'{self.grid_name(grid)}Material {m.ID} with eps_r={m.er:g}, sigma={m.se:g} S/m; mu_r={m.mr:g}, sigma*={m.sm:g} Ohm/m created.'
)
grid.materials.append(m)
@@ -1174,8 +1172,7 @@ class AddDebyeDispersion(UserObjectMulti):
if len(materials) != len(material_ids):
notfound = [x for x in material_ids if x not in materials]
logger.exception(self.params_str() + f' material(s) {notfound} do '
'not exist')
logger.exception(f'{self.params_str()} material(s) {notfound} do not exist')
raise ValueError
for material in materials:
@@ -1187,7 +1184,7 @@ class AddDebyeDispersion(UserObjectMulti):
disp_material.type = 'debye'
disp_material.poles = poles
disp_material.averagable = False
for i in range(0, poles):
for i in range(poles):
if tau[i] > 0:
logger.debug('Not checking if relaxation times are '
'greater than time-step.')
@@ -1203,9 +1200,9 @@ class AddDebyeDispersion(UserObjectMulti):
# Replace original material with newly created DispersiveMaterial
grid.materials = [disp_material if mat.numID==material.numID else mat for mat in grid.materials]
logger.info(self.grid_name(grid) + f"Debye disperion added to {disp_material.ID} "
f"with delta_eps_r={', '.join('%4.2f' % deltaer for deltaer in disp_material.deltaer)}, "
f"and tau={', '.join('%4.3e' % tau for tau in disp_material.tau)} secs created.")
logger.info(
f"{self.grid_name(grid)}Debye disperion added to {disp_material.ID} with delta_eps_r={', '.join('%4.2f' % deltaer for deltaer in disp_material.deltaer)}, and tau={', '.join('%4.3e' % tau for tau in disp_material.tau)} secs created."
)
class AddLorentzDispersion(UserObjectMulti):
@@ -1250,8 +1247,7 @@ class AddLorentzDispersion(UserObjectMulti):
if len(materials) != len(material_ids):
notfound = [x for x in material_ids if x not in materials]
logger.exception(self.params_str() + f' material(s) {notfound} do '
'not exist')
logger.exception(f'{self.params_str()} material(s) {notfound} do not exist')
raise ValueError
for material in materials:
@@ -1263,7 +1259,7 @@ class AddLorentzDispersion(UserObjectMulti):
disp_material.type = 'lorentz'
disp_material.poles = poles
disp_material.averagable = False
for i in range(0, poles):
for i in range(poles):
if er_delta[i] > 0 and omega[i] > grid.dt and delta[i] > grid.dt:
disp_material.deltaer.append(er_delta[i])
disp_material.tau.append(omega[i])
@@ -1281,10 +1277,9 @@ class AddLorentzDispersion(UserObjectMulti):
# Replace original material with newly created DispersiveMaterial
grid.materials = [disp_material if mat.numID==material.numID else mat for mat in grid.materials]
logger.info(self.grid_name(grid) + f"Lorentz disperion added to {disp_material.ID} "
f"with delta_eps_r={', '.join('%4.2f' % deltaer for deltaer in disp_material.deltaer)}, "
f"omega={', '.join('%4.3e' % omega for omega in disp_material.tau)} secs, "
f"and gamma={', '.join('%4.3e' % delta for delta in disp_material.alpha)} created.")
logger.info(
f"{self.grid_name(grid)}Lorentz disperion added to {disp_material.ID} with delta_eps_r={', '.join('%4.2f' % deltaer for deltaer in disp_material.deltaer)}, omega={', '.join('%4.3e' % omega for omega in disp_material.tau)} secs, and gamma={', '.join('%4.3e' % delta for delta in disp_material.alpha)} created."
)
class AddDrudeDispersion(UserObjectMulti):
@@ -1325,8 +1320,7 @@ class AddDrudeDispersion(UserObjectMulti):
if len(materials) != len(material_ids):
notfound = [x for x in material_ids if x not in materials]
logger.exception(self.params_str() + f' material(s) {notfound} do '
'not exist.')
logger.exception(f'{self.params_str()} material(s) {notfound} do not exist.')
raise ValueError
for material in materials:
@@ -1338,7 +1332,7 @@ class AddDrudeDispersion(UserObjectMulti):
disp_material.type = 'drude'
disp_material.poles = poles
disp_material.averagable = False
for i in range(0, poles):
for i in range(poles):
if omega[i] > 0 and alpha[i] > grid.dt:
disp_material.tau.append(omega[i])
disp_material.alpha.append(alpha[i])
@@ -1354,9 +1348,9 @@ class AddDrudeDispersion(UserObjectMulti):
# Replace original material with newly created DispersiveMaterial
grid.materials = [disp_material if mat.numID==material.numID else mat for mat in grid.materials]
logger.info(self.grid_name(grid) + f"Drude disperion added to {disp_material.ID} "
f"with omega={', '.join('%4.3e' % omega for omega in disp_material.tau)} secs, "
f"and gamma={', '.join('%4.3e' % alpha for alpha in disp_material.alpha)} secs created.")
logger.info(
f"{self.grid_name(grid)}Drude disperion added to {disp_material.ID} with omega={', '.join('%4.3e' % omega for omega in disp_material.tau)} secs, and gamma={', '.join('%4.3e' % alpha for alpha in disp_material.alpha)} secs created."
)
class SoilPeplinski(UserObjectMulti):
@@ -1421,7 +1415,7 @@ class SoilPeplinski(UserObjectMulti):
'fraction.')
raise ValueError
if any(x.ID == ID for x in grid.mixingmodels):
logger.exception(self.params_str() + f' with ID {ID} already exists')
logger.exception(f'{self.params_str()} with ID {ID} already exists')
raise ValueError
# Create a new instance of the Material class material
@@ -1491,7 +1485,7 @@ class GeometryView(UserObjectMulti):
p4 = uip.round_to_grid_static_point(p2)
p1, p2 = uip.check_box_points(p1, p2, self.params_str())
except ValueError:
logger.exception(self.params_str() + ' point is outside the domain.')
logger.exception(f'{self.params_str()} point is outside the domain.')
raise
xs, ys, zs = p1
xf, yf, zf = p2
@@ -1511,7 +1505,7 @@ class GeometryView(UserObjectMulti):
logger.exception(self.params_str() + ' the step size should not '
'be less than the spatial discretisation.')
raise ValueError
if output_type != 'n' and output_type != 'f':
if output_type not in ['n', 'f']:
logger.exception(self.params_str() + ' requires type to be either '
'n (normal) or f (fine).')
raise ValueError