Uniformly magnetized sphere¶
A uniformly magnetized sphere has an analytic demagnetization field at its
centre: the component parallel to the magnetization is approximately
-Ms / 3. This classic Nmag example therefore gives a compact physical check of
mesh loading, material assignment, the FEM/BEM demagnetization calculation,
spatial output, and field probing.
Download both files into the same directory:
Download the script Download the mesh
"""Compute and sample the demagnetization field of a uniformly magnetized sphere."""
import sys
from pathlib import Path
import nmag
mesh_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("sphere1.nmesh.h5")
if not mesh_path.is_file():
raise SystemExit(f"Mesh not found: {mesh_path}")
output_directory = Path("results")
output_directory.mkdir(exist_ok=True)
permalloy = nmag.MagMaterial(
name="Py",
Ms=nmag.SI(1e6, "A/m"),
exchange_coupling=nmag.SI(13e-12, "J/m"),
)
config = nmag.NmagConfig(
output_directory=output_directory,
output_policy="replace",
)
simulation = nmag.Simulation(name="sphere1", config=config)
simulation.load_mesh(
str(mesh_path),
[("sphere", permalloy)],
unit_length=nmag.SI(1e-9, "m"),
)
simulation.set_m([1.0, 0.0, 0.0])
simulation.set_H_ext([0.0, 0.0, 0.0], nmag.SI("A/m"))
simulation.save_data(fields="all")
field_at_origin = simulation.probe_subfield_siv("H_demag", [0.0, 0.0, 0.0])
expected_x = -permalloy.Ms.value / 3.0
print("H_demag at the origin:", field_at_origin, "A/m")
print("Analytic x component for a sphere:", expected_x, "A/m")
print("Average magnetization:", simulation.get_subfield_average("m"))
Run the example:
You can also pass an explicit mesh path:
The script prints the interpolated H_demag at the origin and the analytic
x component. The supplied mesh agrees at the percent level. It also writes
sphere1_dat.ndt and sphere1_dat.h5 under results/.
What the example establishes¶
- The mesh contains region
1, named"sphere"when it is mapped to the material inload_mesh. - Mesh coordinates are in nanometres because
unit_lengthisSI(1e-9, "m"). set_m([1, 0, 0])assigns a normalized, uniform magnetization direction.save_data(fields="all")calculates and stores every available field.probe_subfield_sivaccepts a position in metres and returns ordinary SI values, which is convenient for plotting and numerical analysis.
The example is tested against the same pinned mesh used by the production solver tests. For a new scientific model, repeat this pattern with an analytic, legacy, or convergence reference appropriate to that model.