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