Skip to content

Commit

Permalink
renaming xi->susceptibility
Browse files Browse the repository at this point in the history
  • Loading branch information
Boisselet Alexandre (IFAT DC ATV SC D TE2) authored and Boisselet Alexandre (IFAT DC ATV SC D TE2) committed Apr 4, 2024
1 parent ad7d83c commit 4bef768
Show file tree
Hide file tree
Showing 9 changed files with 75 additions and 67 deletions.
12 changes: 6 additions & 6 deletions docs/examples/cuboids_demagnetization.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,20 @@ magpy.defaults.display.backend = "plotly"
# some low quality magnets with different susceptibilities
cube1 = magpy.magnet.Cuboid(polarization=(0, 0, 1), dimension=(0.001, 0.001, 0.001))
cube1.move((-0.0015, 0, 0))
cube1.xi = 0.3 # µr=1.3
cube1.style.label = f"Cuboid, xi={cube1.xi}"
cube1.susceptibility = 0.3 # µr=1.3
cube1.style.label = f"Cuboid, susceptibility={cube1.susceptibility}"
cube2 = magpy.magnet.Cuboid(polarization=(0.9, 0, 0), dimension=(0.001, 0.001, 0.001))
cube2.rotate_from_angax(-45, "y").move((0, 0, 0.0002))
cube2.xi = 1.0 # µr=2.0
cube2.style.label = f"Cuboid, xi={cube2.xi}"
cube2.susceptibility = 1.0 # µr=2.0
cube2.style.label = f"Cuboid, susceptibility={cube2.susceptibility}"
mx = 0.6 * np.sin(np.deg2rad(30))
my = 0.6 * np.cos(np.deg2rad(30))
cube3 = magpy.magnet.Cuboid(polarization=(mx, my, 0), dimension=(0.001, 0.001, 0.002))
cube3.move((0.0016, 0, 0.0005)).rotate_from_angax(30, "z")
cube3.xi = 0.5 # µr=1.5
cube3.style.label = f"Cuboid, xi={cube3.xi}"
cube3.susceptibility = 0.5 # µr=1.5
cube3.style.label = f"Cuboid, susceptibility={cube3.susceptibility}"
# collection of all cells
coll = magpy.Collection(cube1, cube2, cube3, style_label="No demag")
Expand Down
8 changes: 4 additions & 4 deletions docs/examples/soft_magnets.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ magpy.defaults.display.backend = "plotly"
# hard magnet
cube1 = magpy.magnet.Cuboid(polarization=(0, 0, 1), dimension=(0.001, 0.001, 0.002))
cube1.move((0, 0, 0.0005))
cube1.xi = 0.5 # µr=1.5
cube1.style.label = f"Hard cuboid magnet, xi={cube1.xi}"
cube1.susceptibility = 0.5 # µr=1.5
cube1.style.label = f"Hard cuboid magnet, susceptibility={cube1.susceptibility}"
# soft magnet
cube2 = magpy.magnet.Cuboid(polarization=(0, 0, 0), dimension=(0.001, 0.001, 0.001))
cube2.rotate_from_angax(angle=45, axis="y").move((0.0015, 0, 0))
cube2.xi = 3999 # µr=4000
cube2.style.label = f"Soft cuboid magnet, xi={cube2.xi}"
cube2.susceptibility = 3999 # µr=4000
cube2.style.label = f"Soft cuboid magnet, susceptibility={cube2.susceptibility}"
# collection of all cells
coll = magpy.Collection(cube1, cube2, style_label="No demag")
Expand Down
36 changes: 17 additions & 19 deletions magpylib_material_response/demag.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,21 @@
logger.configure(**config)


def get_xis(*sources, xi=None):
"""Return a list of length (len(sources)) with xi values
def get_susceptibilities(*sources, susceptibility=None):
"""Return a list of length (len(sources)) with susceptibility values
Priority is given at the source level, hovever if value is not found, it is searched
up the parent tree, if available. Raises an error if no value is found when reached
the top level of the tree."""
xis = []
susceptibilities = []
for src in sources:
xi = getattr(src, "xi", None)
if xi is None:
susceptibility = getattr(src, "susceptibility", None)
if susceptibility is None:
if src.parent is None:
raise ValueError(
"No susceptibility `xi` defined in any parent collection"
)
xis.extend(get_xis(src.parent))
raise ValueError("No susceptibility defined in any parent collection")
susceptibilities.extend(get_susceptibilities(src.parent))
else:
xis.append(xi)
return xis
susceptibilities.append(susceptibility)
return susceptibilities


def demag_tensor(
Expand Down Expand Up @@ -245,7 +243,7 @@ def match_pairs(src_list, min_log_time=1):

def apply_demag(
collection,
xi=None,
susceptibility=None,
inplace=False,
pairs_matching=False,
max_dist=0,
Expand All @@ -262,7 +260,7 @@ def apply_demag(
collection: magpylib.Collection object with n magnet sources
Each magnet source in collection is treated as a magnetic cell.
xi: array_like, shape (n,)
susceptibility: array_like, shape (n,)
Vector of n magnetic susceptibilities of the cells. If not defined, values are
searched at object level or parent level if needed.
Expand Down Expand Up @@ -340,14 +338,14 @@ def apply_demag(
) # shape ii = x1, ... xn, y1, ... yn, z1, ... zn

# set up S
if xi is None:
xi = get_xis(*magnets_list)
xi = np.array(xi)
if len(xi) != n:
if susceptibility is None:
susceptibility = get_susceptibilities(*magnets_list)
susceptibility = np.array(susceptibility)
if len(susceptibility) != n:
raise ValueError(
"Apply_demag input collection and xi must have same length."
"Apply_demag input collection and susceptibility must have same length."
)
S = np.diag(np.tile(xi, 3)) # shape ii, jj
S = np.diag(np.tile(susceptibility, 3)) # shape ii, jj

# set up T (3 pol unit, n cells, n positions, 3 Bxyz)
with timelog("Demagnetization tensor calculation", min_log_time=min_log_time):
Expand Down
6 changes: 3 additions & 3 deletions magpylib_material_response/meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@


def _collection_from_obj_and_cells(obj, cells, **style_kwargs):
xi = getattr(obj, "xi", None)
if xi is not None:
susceptibility = getattr(obj, "susceptibility", None)
if susceptibility is not None:
for cell in cells:
cell.xi = xi
cell.susceptibility = susceptibility
coll = magpy.Collection(cells)
coll.style.update(obj.style.as_dict(), _match_properties=False)
coll.style.update(coll._process_style_kwargs(**style_kwargs))
Expand Down

Large diffs are not rendered by default.

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions magpylib_material_response/polyline.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def _find_circle_center_and_tangent_points(a, b, c, r, max_ratio=1):
tan_theta = np.tan(theta)
d = r / tan_theta
if d > norm_bc * max_ratio or d > norm_ab * max_ratio:
rold, dold = r, d
# rold, dold = r, d
print("r, d, norm_ab, norm_bc: ", r, d, norm_ab, norm_bc)
d = min(norm_bc * max_ratio, norm_ab * max_ratio)
r = d * tan_theta if theta > 0 else 0
Expand Down Expand Up @@ -145,8 +145,10 @@ def create_polyline_fillet(polyline, max_radius, N):
c = filleted_points[1]
try:
filleted_points.extend(_create_fillet_segment(a, b, c, radius, N))
except ValueError:
raise ValueError(f"The radius {radius} on position vertex {i} is too large")
except ValueError as exc:
raise ValueError(
f"The radius {radius} on position vertex {i} is too large"
) from exc
if closed:
filleted_points[0] = filleted_points[-1]
else:
Expand Down Expand Up @@ -208,7 +210,7 @@ def _line_plane_intersection(plane_point, plane_normal, line_points, line_direct
"""
# Calculate the plane equation coefficients A, B, C, and D
A, B, C = plane_normal
x0, y0, z0 = plane_point
# x0, y0, z0 = plane_point
D = -np.dot(plane_normal, plane_point)

# Calculate the parameter t
Expand Down
28 changes: 18 additions & 10 deletions magpylib_material_response/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def run(self):


@contextmanager
def timelog(msg, min_log_time=1) -> float:
def timelog(msg, min_log_time=1):
""" "Measure and log time with loguru as context manager."""
start = time.perf_counter()
end = None
Expand Down Expand Up @@ -81,16 +81,24 @@ def serialize_recursive(obj, parent="warn"):
warnings.warn(f"object parent ({obj.parent}) not included in serialization")
if isinstance(obj, BaseMagnet):
dd["polarization"] = {"value": obj.polarization.tolist(), "unit": "T"}
xi = getattr(obj, "susceptibility", None)
xi = getattr(obj, "xi", None) if xi is None else xi
if xi is not None:
dd["susceptibility"] = {"value": xi}
susceptibility = getattr(obj, "susceptibility", None)
susceptibility = (
getattr(obj, "susceptibility", None)
if susceptibility is None
else susceptibility
)
if susceptibility is not None:
dd["susceptibility"] = {"value": susceptibility}
if isinstance(obj, magpy.magnet.Cuboid):
dd["dimension"] = {"value": obj.dimension.tolist(), "unit": "m"}
xi = getattr(obj, "susceptibility", None)
xi = getattr(obj, "xi", None) if xi is None else xi
if xi is not None:
dd["susceptibility"] = {"value": xi}
susceptibility = getattr(obj, "susceptibility", None)
susceptibility = (
getattr(obj, "susceptibility", None)
if susceptibility is None
else susceptibility
)
if susceptibility is not None:
dd["susceptibility"] = {"value": susceptibility}
elif isinstance(obj, magpy.Sensor):
dd["pixel"] = {"value": obj.pixel.tolist(), "unit": "m"}
elif isinstance(obj, magpy.Collection):
Expand Down Expand Up @@ -156,7 +164,7 @@ def deserialize_recursive(inp, ids=None):
obj = constr(**kw)
ids[inp["id"]] = obj
if inp.get("susceptibility", None) is not None:
obj.xi = inp["susceptibility"]["value"]
obj.susceptibility = inp["susceptibility"]["value"]
if is_coll:
obj.add(*[deserialize_recursive(child, ids)[0] for child in inp["children"]])
return obj, ids
Expand Down
38 changes: 19 additions & 19 deletions tests/test_meshing.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ def test_mesh_Cuboid():
c.style.opacity = 0 # will be overriden by mesh kwargs lower
c.rotate_from_angax(np.linspace(0, 76, N), "z", anchor=0, start=0)
c.move(np.linspace((0, 0, 0), (0, 0, 0.0105), N), start=0)
c.xi = 3999
c.susceptibility = 3999

cm = mesh_Cuboid(c, target_elems=8, style_opacity=opacity)

# test if meshed cuboid collection provides the same field as original cuboid
np.testing.assert_allclose(c.getB([0, 0, 0]), cm.getB([0, 0, 0]))

# test if all children sources got the right xi value
assert all(s.xi == c.xi for s in cm.sources_all)
# test if all children sources got the right susceptibility value
assert all(s.susceptibility == c.susceptibility for s in cm.sources_all)

# test style kwargs
assert cm.style.label == c.style.label
Expand Down Expand Up @@ -66,15 +66,15 @@ def test_slice_Cuboid():
c.style.opacity = 0 # will be overriden by mesh kwargs lower
c.rotate_from_angax(np.linspace(0, 76, N), "z", anchor=0, start=0)
c.move(np.linspace((0, 0, 0), (0, 0, 0.0105), N), start=0)
c.xi = 3999
c.susceptibility = 3999

cm = slice_Cuboid(c, shift=0.2, axis="y", style_opacity=opacity)

# test if meshed cuboid collection provides the same field as original cuboid
np.testing.assert_allclose(c.getB([0, 0, 0]), cm.getB([0, 0, 0]))

# test if all children sources got the right xi value
assert all(s.xi == c.xi for s in cm.sources_all)
# test if all children sources got the right susceptibility value
assert all(s.susceptibility == c.susceptibility for s in cm.sources_all)

# test style kwargs
assert cm.style.label == c.style.label
Expand Down Expand Up @@ -127,15 +127,15 @@ def test_mesh_Cylinder():
c.rotate_from_angax(np.linspace(0, 90, N), "x", anchor=0, start=0)
c.move(np.linspace((0, 0, 0), (0, 0, 1), N), start=0)
c.style.magnetization.show = False
c.xi = 3999
c.susceptibility = 3999

cm = mesh_Cylinder(c, target_elems=20, style_opacity=opacity)

# test if meshed cuboid collection provides the same field as original cuboid
np.testing.assert_allclose(c.getB([0, 0, 0]), cm.getB([0, 0, 0]))

# test if all children sources got the right xi value
assert all(s.xi == c.xi for s in cm.sources_all)
# test if all children sources got the right susceptibility value
assert all(s.susceptibility == c.susceptibility for s in cm.sources_all)

# test style kwargs
assert cm.style.label == c.style.label
Expand Down Expand Up @@ -166,7 +166,7 @@ def test_mesh_thin_CylinderSegment_with_cuboids():
c.rotate_from_angax(np.linspace(0, 90, N), "z", anchor=0, start=0)
c.rotate_from_angax(np.linspace(0, 90, N), "x", anchor=0, start=0)
c.move(np.linspace((0, 0, 0), (0, 0, 1), N), start=0)
c.xi = 3999
c.susceptibility = 3999

cm = mesh_thin_CylinderSegment_with_cuboids(
c, target_elems=100, match_volume=False, style_opacity=opacity
Expand All @@ -185,8 +185,8 @@ def test_mesh_thin_CylinderSegment_with_cuboids():
# by default match_volume=True, delivers better accuracy, hence lower rtol
np.testing.assert_allclose(c.getB([0, 0, 0]), cm.getB([0, 0, 0]), rtol=0.01)

# test if all children sources got the right xi value
assert all(s.xi == c.xi for s in cm.sources_all)
# test if all children sources got the right susceptibility value
assert all(s.susceptibility == c.susceptibility for s in cm.sources_all)

# test style kwargs
assert cm.style.label == c.style.label
Expand All @@ -197,16 +197,16 @@ def test_mesh_thin_CylinderSegment_with_cuboids():


def test_mesh_all():
xi = 3999
susceptibility = 3999
c = magpy.magnet.Cuboid(
polarization=(1, 0, 0),
dimension=(1, 2, 3),
position=[4, 5, 6],
style_label="C1",
)
c.xi = xi
c.susceptibility = susceptibility
cy = magpy.magnet.Cylinder(polarization=(1, 1, 1), dimension=(4, 1))
cy.xi = c.xi
cy.susceptibility = c.susceptibility
c2 = magpy.Collection(c.copy(dimension=c.dimension / 2).move((5, 0, 0)))
c2.style.label = "C2 super"
# currents and sensors and sensors should be just silently ignored by meshing
Expand Down Expand Up @@ -241,13 +241,13 @@ def test_mesh_all():
# mesh on copy (by default)
cm = mesh_all(c0, target_elems=20)
assert cm is not c0
# test if all children sources got the right xi value
# test if all children sources got the right susceptibility value
mags = [s for s in cm.sources_all if not isinstance(s, magpy.current.Circle)]
assert all(s.xi == c.xi for s in mags)
assert all(s.susceptibility == c.susceptibility for s in mags)

# mesh inplace
cm = mesh_all(c0, target_elems=20, inplace=True)
assert cm is c0
# test if all children sources got the right xi value
# test if all children sources got the right susceptibility value
mags = [s for s in cm.sources_all if not isinstance(s, magpy.current.Circle)]
assert all(s.xi == c.xi for s in mags)
assert all(s.susceptibility == c.susceptibility for s in mags)

0 comments on commit 4bef768

Please sign in to comment.