Demagnetizing Field Inside and Around a Uniformly Magnetized Sphere
In this example, we use the finite element method (FEM) to compute the demagnetizing field inside and around a uniformly magnetized sphere. It is well known that for a uniformly magnetized sphere with magnetization vector
Outside the sphere, the field is equivalent to that produced by a magnetic dipole with moment
The corresponding magnetic scalar potential
We begin by generating the simulation mesh using Netgen. The following sphere_air.geo file defines the geometry:
algebraic3d
solid sp = sphere(0, 0, 0; 10);
solid air = orthobrick(-2,-20,-20; 2, 20, 20) and not sphere(0, 0, 0; 12);
tlo sp -maxh=1.0;
tlo air -maxh=2.0;This script creates:
A solid sphere (
sp) centered at the origin with radius 10An air box (
air) that surrounds the sphere with a buffer regionDifferent mesh sizes are assigned to the sphere (finer mesh) and air region (coarser mesh)
The resulting mesh looks like: 
Note that the sphere and air are defined as separate solids. This allows the sphere to be labeled as region 1 and the air as region 2, enabling different material parameter assignments in subsequent simulations.
Simulation Setup
Import the necessary modules:
using MicroMagnetic
using PrintfRead the mesh file:
mesh = FEMesh("sphere_air.mesh")A coarser sphere_air.mesh is available. Create a simulation object and set the saturation magnetization for region 1 (the sphere):
sim = Sim(mesh; driver="SD")
set_Ms(sim, 8e5, region_id=1) # 800,000 A/m saturation magnetizationSet the initial magnetization direction and add the demagnetization energy term:
init_m0(sim, (0, 0, 1)) # Initial magnetization along z-axis
d = add_demag(sim, name="demag") # Add demagnetization field calculationCompute the effective field and save the results in VTK format for visualization:
MicroMagnetic.effective_field(sim, sim.spin)
save_vtk(sim, "sphere_demag.vtu", fields=["demag"])The resulting VTU file can be opened in ParaView to visualize the magnetic field distribution around the sphere: 