Skip to content

Commit f839e31

Browse files
committed
fix linting errors
1 parent 066748a commit f839e31

File tree

8 files changed

+122
-112
lines changed

8 files changed

+122
-112
lines changed

docs/examples/soft_magnets.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ kernelspec:
2121
This code demonstrates demagnetization calculations for a hard and a soft cuboid
2222
magnet using the Magpylib library. Demagnetization is applied using varying
2323
numbers of cells for the mesh and compared to the computed magnetic fields from
24-
Magpylib withoug demagnetization and with FEM analysis data obtained from an
24+
Magpylib without demagnetization and with FEM analysis data obtained from an
2525
external dataset.
2626

2727
+++ {"user_expressions": []}

src/magpylib_material_response/data/__init__.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ def get_dataset(name):
1111
from pathlib import Path
1212

1313
name = Path(name).with_suffix("").with_suffix(".json")
14-
with importlib.resources.path(
15-
"magpylib_material_response.package_data", "datasets"
16-
) as resources_path:
17-
with open(resources_path / name) as fp:
18-
sim = json.load(fp)
19-
return sim
14+
with (
15+
importlib.resources.path(
16+
"magpylib_material_response.package_data", "datasets"
17+
) as resources_path,
18+
(resources_path / name).open() as fp,
19+
):
20+
return json.load(fp)

src/magpylib_material_response/demag.py

Lines changed: 46 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""demag_functions"""
22

3-
# +
4-
# pylint: disable=invalid-name, redefined-outer-name, protected-access
53
from __future__ import annotations
64

75
import sys
@@ -18,24 +16,24 @@
1816

1917
config = {
2018
"handlers": [
21-
dict(
22-
sink=sys.stdout,
23-
colorize=True,
24-
format=(
19+
{
20+
"sink": sys.stdout,
21+
"colorize": True,
22+
"format": (
2523
"<magenta>{time:YYYY-MM-DD at HH:mm:ss}</magenta>"
2624
" | <level>{level:^8}</level>"
2725
" | <cyan>{function}</cyan>"
2826
" | <yellow>{extra}</yellow> {level.icon:<2} {message}"
2927
),
30-
),
28+
},
3129
],
3230
}
3331
logger.configure(**config)
3432

3533

3634
def get_susceptibilities(sources, susceptibility):
3735
"""Return a list of length (len(sources)) with susceptibility values
38-
Priority is given at the source level, hovever if value is not found, it is searched
36+
Priority is given at the source level, however if value is not found, it is searched
3937
up the parent tree, if available. Raises an error if no value is found when reached
4038
the top level of the tree."""
4139
n = len(sources)
@@ -47,31 +45,31 @@ def get_susceptibilities(sources, susceptibility):
4745
susceptibility = getattr(src, "susceptibility", None)
4846
if susceptibility is None:
4947
if src.parent is None:
50-
raise ValueError(
51-
"No susceptibility defined in any parent collection"
52-
)
48+
msg = "No susceptibility defined in any parent collection"
49+
raise ValueError(msg)
5350
susis.extend(get_susceptibilities(src.parent))
5451
elif not hasattr(susceptibility, "__len__"):
5552
susis.append((susceptibility, susceptibility, susceptibility))
5653
elif len(susceptibility) == 3:
5754
susis.append(susceptibility)
5855
else:
59-
raise ValueError("susceptibility is not scalar or array fo length 3")
56+
msg = "susceptibility is not scalar or array of length 3"
57+
raise ValueError(msg)
6058
# susceptibilities as input to demag function
6159
elif np.isscalar(susceptibility):
6260
susis = np.ones((n, 3)) * susceptibility
6361
elif len(susceptibility) == 3:
6462
susis = np.tile(susceptibility, (n, 1))
6563
if n == 3:
66-
raise ValueError(
64+
msg = (
6765
"Apply_demag input susceptibility is ambiguous - either scalar list or vector single entry. "
6866
"Please choose different means of input or change the number of cells in the Collection."
6967
)
68+
raise ValueError(msg)
7069
else:
7170
if len(susceptibility) != n:
72-
raise ValueError(
73-
"Apply_demag input susceptibility must be scalar, 3-vector, or same length as input Collection."
74-
)
71+
msg = "Apply_demag input susceptibility must be scalar, 3-vector, or same length as input Collection."
72+
raise ValueError(msg)
7573
susis = np.array(susceptibility)
7674
if susis.ndim == 1:
7775
susis = np.repeat(susis, 3).reshape(n, 3)
@@ -82,7 +80,7 @@ def get_susceptibilities(sources, susceptibility):
8280

8381
def get_H_ext(*sources, H_ext=None):
8482
"""Return a list of length (len(sources)) with H_ext values
85-
Priority is given at the source level, hovever if value is not found, it is searched up the
83+
Priority is given at the source level, however if value is not found, it is searched up the
8684
the parent tree, if available. Sets H_ext to zero if no value is found when reached the top
8785
level of the tree"""
8886
H_exts = []
@@ -120,7 +118,7 @@ def demag_tensor(
120118
calculated only once and copied to duplicates.
121119
122120
split: int
123-
Number of times the sources list is splitted before getH calculation ind demag
121+
Number of times the sources list is split before getH calculation ind demag
124122
tensor calculation
125123
126124
min_log_time:
@@ -141,7 +139,8 @@ def demag_tensor(
141139
nof_src = len(src_list)
142140

143141
if pairs_matching and split != 1:
144-
raise ValueError("Pairs matching does not support splitting")
142+
msg = "Pairs matching does not support splitting"
143+
raise ValueError(msg)
145144
if max_dist != 0:
146145
mask_inds, getH_params, pos0, rot0 = filter_distance(
147146
src_list, max_dist, return_params=False, return_base_geo=True
@@ -192,9 +191,7 @@ def demag_tensor(
192191
H_point.append(H_unit_pol) # shape (n_cells, n_pos, 3_xyz)
193192

194193
# shape (3_unit_pol, n_cells, n_pos, 3_xyz)
195-
T = np.array(H_point).reshape((3, nof_src, nof_src, 3))
196-
197-
return T
194+
return np.array(H_point).reshape((3, nof_src, nof_src, 3))
198195

199196

200197
def filter_distance(
@@ -208,9 +205,8 @@ def filter_distance(
208205
with timelog("Distance filter", min_log_time=min_log_time):
209206
all_cuboids = all(isinstance(src, Cuboid) for src in src_list)
210207
if not all_cuboids:
211-
raise ValueError(
212-
"filter_distance only implemented if all sources are Cuboids"
213-
)
208+
msg = "filter_distance only implemented if all sources are Cuboids"
209+
raise ValueError(msg)
214210
pos0 = np.array([getattr(src, "barycenter", src.position) for src in src_list])
215211
rotQ0 = [src.orientation.as_quat() for src in src_list]
216212
rot0 = R.from_quat(rotQ0)
@@ -222,12 +218,14 @@ def filter_distance(
222218
maxdim2 = np.concatenate(dim2, axis=1).max(axis=1)
223219
mask = (dist2 / maxdim2) < max_dist
224220
if return_params:
225-
params = dict(
226-
observers=np.tile(pos0, (len(src_list), 1))[mask],
227-
position=np.repeat(pos0, len(src_list), axis=0)[mask],
228-
orientation=R.from_quat(np.repeat(rotQ0, len(src_list), axis=0))[mask],
229-
dimension=np.repeat(dim0, len(src_list), axis=0)[mask],
230-
)
221+
params = {
222+
"observers": np.tile(pos0, (len(src_list), 1))[mask],
223+
"position": np.repeat(pos0, len(src_list), axis=0)[mask],
224+
"orientation": R.from_quat(np.repeat(rotQ0, len(src_list), axis=0))[
225+
mask
226+
],
227+
"dimension": np.repeat(dim0, len(src_list), axis=0)[mask],
228+
}
231229
dsf = sum(mask) / len(mask) * 100
232230
log_msg = (
233231
"Interaction pairs left after distance factor filtering: "
@@ -252,9 +250,8 @@ def match_pairs(src_list, min_log_time=1):
252250
with timelog("Pairs matching", min_log_time=min_log_time):
253251
all_cuboids = all(isinstance(src, Cuboid) for src in src_list)
254252
if not all_cuboids:
255-
raise ValueError(
256-
"Pairs matching only implemented if all sources are Cuboids"
257-
)
253+
msg = "Pairs matching only implemented if all sources are Cuboids"
254+
raise ValueError(msg)
258255
pos0 = np.array([getattr(src, "barycenter", src.position) for src in src_list])
259256
rotQ0 = [src.orientation.as_quat() for src in src_list]
260257
rot0 = R.from_quat(rotQ0)
@@ -283,12 +280,12 @@ def match_pairs(src_list, min_log_time=1):
283280
f"<blue>{perc:.2f}%</blue>"
284281
)
285282

286-
params = dict(
287-
observers=np.tile(pos0, (len(src_list), 1))[unique_inds],
288-
position=np.repeat(pos0, len(src_list), axis=0)[unique_inds],
289-
orientation=R.from_quat(rotQ2b)[unique_inds],
290-
dimension=np.repeat(dim0, len(src_list), axis=0)[unique_inds],
291-
)
283+
params = {
284+
"observers": np.tile(pos0, (len(src_list), 1))[unique_inds],
285+
"position": np.repeat(pos0, len(src_list), axis=0)[unique_inds],
286+
"orientation": R.from_quat(rotQ2b)[unique_inds],
287+
"dimension": np.repeat(dim0, len(src_list), axis=0)[unique_inds],
288+
}
292289
return params, unique_inds, unique_inv_inds, pos0, rot0
293290

294291

@@ -331,7 +328,7 @@ def apply_demag(
331328
`pairs_matching` or `split` and applies only cuboid cells.
332329
333330
split: int
334-
Number of times the sources list is splitted before getH calculation ind demag
331+
Number of times the sources list is split before getH calculation ind demag
335332
tensor calculation. This parameter is not compatible with `pairs_matching` or
336333
`max_dist`.
337334
@@ -353,10 +350,11 @@ def apply_demag(
353350
srcs = collection.sources_all
354351
src_with_paths = [src for src in srcs if src.position.ndim != 1]
355352
if src_with_paths:
356-
raise ValueError(
353+
msg = (
357354
f"{len(src_with_paths)} objects with paths, found. Demagnetization of "
358355
"objects with paths is not yet supported"
359356
)
357+
raise ValueError(msg)
360358
magnets_list = [src for src in srcs if isinstance(src, BaseMagnet)]
361359
currents_list = [src for src in srcs if isinstance(src, BaseCurrent)]
362360
others_list = [
@@ -365,16 +363,17 @@ def apply_demag(
365363
if not isinstance(src, (BaseMagnet, BaseCurrent, magpy.Sensor))
366364
]
367365
if others_list:
368-
raise TypeError(
366+
msg = (
369367
"Only Magnet and Current sources supported. "
370368
"Incompatible objects found: "
371369
f"{Counter(s.__class__.__name__ for s in others_list)}"
372370
)
371+
raise TypeError(msg)
373372
n = len(magnets_list)
374373
counts = Counter(s.__class__.__name__ for s in magnets_list)
375374
inplace_str = f"""{" (inplace)" if inplace else ""}"""
376375
lbl = collection.style.label
377-
coll_str = str(collection) if not lbl else lbl
376+
coll_str = lbl if lbl else str(collection)
378377
demag_msg = (
379378
f"Demagnetization{inplace_str} of <blue>{coll_str}</blue>"
380379
f" with {n} cells - {counts}"
@@ -399,9 +398,8 @@ def apply_demag(
399398
H_ext = get_H_ext(*magnets_list)
400399
H_ext = np.array(H_ext)
401400
if len(H_ext) != n:
402-
raise ValueError(
403-
"Apply_demag input collection and H_ext must have same length."
404-
)
401+
msg = "Apply_demag input collection and H_ext must have same length."
402+
raise ValueError(msg)
405403
H_ext = np.reshape(H_ext, (3 * n, 1), order="F")
406404

407405
# set up T (3 pol unit, n cells, n positions, 3 Bxyz)
@@ -442,3 +440,4 @@ def apply_demag(
442440

443441
if not inplace:
444442
return collection
443+
return None

src/magpylib_material_response/meshing.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,11 @@ def mesh_Cuboid(cuboid, target_elems, verbose=False, **kwargs):
5252
Collection of Cuboid cells
5353
"""
5454
if not isinstance(cuboid, magpy.magnet.Cuboid):
55-
raise TypeError(
55+
msg = (
5656
"Object to be meshed must be a Cuboid, "
5757
f"received instead {cuboid.__class__.__name__!r}"
5858
)
59+
raise TypeError(msg)
5960
dim0 = cuboid.dimension
6061
pol0 = cuboid.polarization
6162

@@ -128,12 +129,13 @@ def mesh_Cylinder(cylinder, target_elems, verbose=False, **kwargs):
128129
360,
129130
)
130131
else:
131-
raise TypeError("Input must be a Cylinder or CylinderSegment")
132+
msg = "Input must be a Cylinder or CylinderSegment"
133+
raise TypeError(msg)
132134

133135
al = (r2 + r1) * 3.14 * (phi2 - phi1) / 360 # arclen = D*pi*arcratio
134136
dim = al, r2 - r1, h
135137
pol0 = cylinder.polarization
136-
# "unroll" the cylinder and distribute the target number of elemens along the
138+
# "unroll" the cylinder and distribute the target number of elements along the
137139
# circumference, radius and height.
138140
if np.isscalar(target_elems):
139141
nphi, nr, nh = cells_from_dimension(dim, target_elems)
@@ -195,7 +197,7 @@ def mesh_thin_CylinderSegment_with_cuboids(
195197
CylinderSegment object to be discretized
196198
target_elems: int or tuple of int,
197199
If `target_elems` is a tuple of integers, the cylinder segment is respectively
198-
divided over circumference and height, if an integer, divisions are infered to
200+
divided over circumference and height, if an integer, divisions are inferred to
199201
build cuboids with close to squared faces.
200202
ratio_limit: positive number,
201203
Sets the r2/(r2-r1) limit to be considered as thin-walled, r1 being the inner
@@ -214,11 +216,12 @@ def mesh_thin_CylinderSegment_with_cuboids(
214216
r1, r2, h, phi1, phi2 = cyl_seg.dimension
215217
pol0 = cyl_seg.polarization
216218
if ratio_limit > r2 / (r2 - r1):
217-
raise ValueError(
219+
msg = (
218220
"This meshing function is intended for thin-walled CylinderSegment objects"
219221
f" of radii-ratio r2/(r2-r1)>{ratio_limit}, r1 being the inner radius."
220222
f"\nInstead r2/(r2-r1)={r2 / (r2 - r1)}"
221223
)
224+
raise ValueError(msg)
222225
# distribute elements -> targeting thin close-to-square surface cells
223226
circumf = 2 * np.pi * r1
224227
if np.isscalar(target_elems):
@@ -279,12 +282,14 @@ def slice_Cuboid(cuboid, shift=0.5, axis="z", **kwargs):
279282
If the shift value is not between 0 and 1 (exclusive).
280283
"""
281284
if not isinstance(cuboid, magpy.magnet.Cuboid):
282-
raise TypeError(
285+
msg = (
283286
"Object to be sliced must be a Cuboid, "
284287
f"received instead {cuboid.__class__.__name__!r}"
285288
)
289+
raise TypeError(msg)
286290
if not 0 < shift < 1:
287-
raise ValueError("Shift must be between 0 and 1 (exclusive)")
291+
msg = "Shift must be between 0 and 1 (exclusive)"
292+
raise ValueError(msg)
288293
dim0 = cuboid.dimension
289294
pol0 = cuboid.polarization
290295
ind = "xyz".index(axis)
@@ -347,7 +352,8 @@ def voxelize(obj, target_elems, strict_inside=True, **kwargs):
347352
)
348353
grid = grid[pos_inside_strict_mask]
349354
if grid.size == 0:
350-
raise ValueError("No cuboids left with strict-inside method")
355+
msg = "No cuboids left with strict-inside method"
356+
raise ValueError(msg)
351357

352358
cells = []
353359
for pos in grid:
@@ -399,7 +405,7 @@ def mesh_all(
399405
If there are incompatible objects found.
400406
"""
401407
supported = (magpy.magnet.Cuboid, magpy.magnet.Cylinder)
402-
allowed = supported + (BaseCurrent,)
408+
allowed = (*supported, BaseCurrent)
403409
if not inplace:
404410
obj = obj.copy(**kwargs)
405411
children = [obj]
@@ -415,18 +421,19 @@ def mesh_all(
415421
else:
416422
target_elems_by_child = [max(min_elems, target_elems)] * len(supported_objs)
417423
if incompatible_objs:
418-
raise TypeError(
424+
msg = (
419425
"Incompatible objects found: "
420426
f"{Counter(s.__class__.__name__ for s in incompatible_objs)}"
421427
f"\nSupported: {[s.__name__ for s in supported]}."
422428
)
423-
for child, target_elems in zip(supported_objs, target_elems_by_child):
429+
raise TypeError(msg)
430+
for child, targ_elems in zip(supported_objs, target_elems_by_child):
424431
parent = child.parent
425432
kw = kwargs if parent is None else {}
426433
if isinstance(child, magpy.magnet.Cuboid):
427-
child_meshed = mesh_Cuboid(child, target_elems, **kw)
434+
child_meshed = mesh_Cuboid(child, targ_elems, **kw)
428435
elif isinstance(child, magpy.magnet.Cylinder):
429-
child_meshed = mesh_Cylinder(child, target_elems, **kw)
436+
child_meshed = mesh_Cylinder(child, targ_elems, **kw)
430437
child.parent = None
431438
if parent is not None:
432439
parent.add(child_meshed)

0 commit comments

Comments
 (0)