Skip to content

Simulation API

This page contains the supported, user-facing simulation surface. Compatibility helpers and internal solver methods are intentionally omitted.

Simulation

Simulation(name: str | None = None, phi_BEM: Any | None = None, periodic_bc: Any | None = None, do_demag: bool = True, do_sl_stt: bool = False, config: NmagConfig | None = None)

Own a finite-element micromagnetic simulation and its output lifecycle.

A simulation is configured once, then receives a tetrahedral mesh, material mapping, magnetization, and applied fields. Field calculations are lazy; saving, probing, time advancement, or relaxation computes what is needed.

Parameters:

Name Type Description Default
name str | None

Base name for NDT, HDF5, and default checkpoint files. When omitted, use config.default_name.

None
phi_BEM Any | None

Reserved legacy HLib option. Non-null values are unsupported.

None
periodic_bc Any | None

Reserved legacy periodic-boundary option. Non-null values are unsupported.

None
do_demag bool

Calculate demagnetization fields and energies when true.

True
do_sl_stt bool

Reserved for Slonczewski spin-transfer torque, which is not implemented. Zhang-Li torque is configured through material parameters and :meth:set_current_density.

False
config NmagConfig | None

Immutable output, acceleration, storage, and integrator policy. Environment defaults are read only when this argument is omitted.

None

Raises:

Type Description
NotImplementedError

If an unsupported legacy constructor option is requested.

id property

id: int

stage property

stage: int

step property

step: int

stage_step property

stage_step: int

time property

time: SI

stage_time property

stage_time: SI

real_time property

real_time: SI

last_step_dt property

last_step_dt: SI

last_bem_operator_stats property

last_bem_operator_stats: BemOperatorStats | None

Return diagnostics for the currently cached boundary operator.

last_integrator_stats property

last_integrator_stats: IntegratorStats

integrator_config property

integrator_config: IntegratorConfig

effective_integrator_max_step property

effective_integrator_max_step: SI

load_mesh

load_mesh(filename: str, region_names_and_mag_mats: Sequence[tuple[str, Any]], unit_length: SI, do_reorder: bool = False, manual_distribution: Any = None) -> Mesh

Load a mesh, scale it to metres, and map its regions to materials.

Parameters:

Name Type Description Default
filename str

Legacy Nmesh or Meshio-supported mesh file.

required
region_names_and_mag_mats Sequence[tuple[str, Any]]

(region_name, material) pairs in ascending mesh-region order. Mesh region IDs do not need to be contiguous or start at region 1.

required
unit_length SI

Physical length represented by one mesh coordinate unit.

required
do_reorder bool

Request legacy node reordering. Reordering is currently unsupported by the mesh backend.

False
manual_distribution Any

Reserved legacy distributed-mesh mapping.

None

Returns:

Type Description
Mesh

The loaded and physically scaled mesh.

Raises:

Type Description
RuntimeError

If a mesh has already been loaded.

ValueError

If mesh regions and configured materials do not match.

NotImplementedError

If reordering or manual distribution is requested by an unsupported backend.

set_m

set_m(values: Vector | VectorField, subfieldname: str | None = None) -> None

Set and normalize the nodal magnetization direction field.

Parameters:

Name Type Description Default
values Vector | VectorField

One three-component vector, one vector per mesh node, or a callable receiving a physical node position in metres.

required
subfieldname str | None

Reserved legacy material-subfield selector. Omit it; material-specific magnetization degrees of freedom are not implemented.

None

Raises:

Type Description
RuntimeError

If no mesh has been loaded.

ValueError

If a vector is zero or the field shape is invalid.

NotImplementedError

If subfieldname is supplied.

set_H_ext

set_H_ext(values: Vector, unit: SI | None = None) -> None

Set the homogeneous applied magnetic field.

Parameters:

Name Type Description Default
values Vector

Three field components. When unit is omitted, values may be SI quantities; otherwise they are interpreted in unit.

required
unit SI | None

Unit compatible with A/m.

None

set_pinning

set_pinning(values: ScalarFieldInput) -> None

Set the nodal multiplier for the complete magnetization derivative.

Parameters:

Name Type Description Default
values ScalarFieldInput

Uniform scalar, one value per mesh node, or a callable receiving physical node positions in metres. Zero pins a node, one leaves it free, and other finite values scale its rate.

required

Raises:

Type Description
RuntimeError

If no mesh has been loaded.

ValueError

If values are non-finite or have the wrong shape.

set_current_density

set_current_density(values: VectorFieldInput, unit: SI | None = None) -> None

Set the current-density field used by Zhang-Li spin-transfer torque.

Parameters:

Name Type Description Default
values VectorFieldInput

Uniform vector, nodal vectors, or a callable receiving physical node positions in metres.

required
unit SI | None

Unit compatible with A/m². Required for ordinary numeric vectors unless values already carry SI dimensions.

None

Raises:

Type Description
RuntimeError

If no mesh has been loaded.

ValueError

If the field shape or dimensions are invalid.

get_all_field_names

get_all_field_names() -> list[str]

Return the field names currently available for saving or access.

is_subfield_available

is_subfield_available(subfieldname: str) -> bool

Return whether the current model can provide a named field.

The check does not trigger expensive FEM/BEM work. Actual field access can still raise a numerical error during calculation.

Parameters:

Name Type Description Default
subfieldname str

Candidate field name.

required

Returns:

Type Description
bool

True when the field is set or derivable from current state.

get_subfield

get_subfield(subfieldname: str, units: SI | None = None) -> Any

Return all nodal or cell values for one available field.

Parameters:

Name Type Description Default
subfieldname str

Name returned by :meth:get_all_field_names.

required
units SI | None

Optional compatible SI unit for returned numeric values.

None

Returns:

Type Description
Any

Field values as Python scalars or nested lists.

Raises:

Type Description
KeyError

If the field is unknown, unset, or disabled.

get_subfield_average

get_subfield_average(subfieldname: str, mat_name: str | None = None) -> Any

Return the volume-weighted average of an available field.

Parameters:

Name Type Description Default
subfieldname str

Field name, for example m, H_total, or E_demag.

required
mat_name str | None

Restrict integration to tetrahedra belonging to this material. Omit it for the complete magnetic volume.

None

Returns:

Type Description
Any

A scalar or component list, or None when the requested derived

Any

quantity is not available for the current model.

get_maxangle_average

get_maxangle_average(field_name: str) -> float | None

Return the maximum neighboring magnetization angle in degrees.

Parameters:

Name Type Description Default
field_name str

Currently only "m" is supported.

required

Returns:

Type Description
float | None

Maximum angle across mesh edges, or None when magnetization or

float | None

a suitable mesh is unavailable.

probe_subfield

probe_subfield(subfieldname: str, pos: Sequence[float], unit: SI | None = None) -> Any

Probe a field at a physical position.

Parameters:

Name Type Description Default
subfieldname str

Field to sample.

required
pos Sequence[float]

Three coordinates in metres.

required
unit SI | None

Reserved compatibility argument. Returned values use the field's standard SI representation.

None

Returns:

Type Description
Any

Interpolated SI components, or None when the position is

Any

outside the mesh.

probe_subfield_siv

probe_subfield_siv(subfieldname: str, pos: Sequence[float], unit: SI | None = None) -> Any

Probe a field at a position expressed in metres.

Demagnetization fields are linearly interpolated in the containing tetrahedron. Magnetization uses the nearest mesh node, and a homogeneous applied field is returned directly.

Parameters:

Name Type Description Default
subfieldname str

H_demag, H_ext, or m.

required
pos Sequence[float]

Three physical coordinates in metres.

required
unit SI | None

Reserved compatibility argument. Returned values use the field's standard SI representation.

None

Returns:

Type Description
Any

Ordinary numeric components in SI, or None outside the mesh.

Raises:

Type Description
KeyError

If the field name is not supported by this probe API.

save_data

save_data(fields: str | list[str] | None = None, avoid_same_step: bool = False) -> None

Append averaged data and optionally save spatial fields.

Parameters:

Name Type Description Default
fields str | list[str] | None

None for averages only, "all" for every available field, or a list of field names to store spatially in HDF5.

None
avoid_same_step bool

Skip the save when this integrator step was already written. Primarily used by scheduled actions.

False

save_spatial_fields

save_spatial_fields(filename: str, fieldnames: list[str]) -> None

Write selected spatial fields and mesh points to an HDF5 file.

Existing datasets with the same field names are replaced inside the file; unrelated groups and datasets are retained.

Parameters:

Name Type Description Default
filename str

Destination HDF5 path.

required
fieldnames list[str]

Available field names such as m or H_demag.

required

save_mesh

save_mesh(filename: str) -> None

Save the currently loaded, physically scaled mesh.

Parameters:

Name Type Description Default
filename str

Destination path. The suffix selects Nmesh HDF5, Nmesh ASCII, or a Meshio-supported format.

required

Raises:

Type Description
RuntimeError

If no mesh has been loaded.

advance_time

advance_time(target_time: SI, max_it: int = -1, exact_tstop: bool | None = None) -> SI

Advance adaptive LLG integration toward a physical target time.

Parameters:

Name Type Description Default
target_time SI

Absolute stage time to reach.

required
max_it int

Maximum accepted steps, or -1 for no explicit cap.

-1
exact_tstop bool | None

Override whether a step crossing the target is reconstructed at exactly the requested time.

None

Returns:

Type Description
SI

The physical time reached. It can precede target_time when

SI

max_it limits the operation.

Raises:

Type Description
ValueError

If the target precedes the current time or max_it is invalid.

RuntimeError

If the numerical integrator fails.

relax

relax(H_applied: Any = None, save: list[tuple[object, ...]] | None = None, do: list[tuple[object, ...]] | None = None, convergence_check: Any = None) -> None

Relax magnetization until the convergence schedule completes.

Parameters:

Name Type Description Default
H_applied Any

Optional applied-field value for compatibility with the staged relaxation runner.

None
save list[tuple[object, ...]] | None

Scheduled save tuples such as [("averages", every("step", 10))]. Omit for averages and fields at stage end.

None
do list[tuple[object, ...]] | None

Scheduled action tuples. Omit for the default stage lifecycle.

None
convergence_check Any

Custom :class:when.When condition. Omit for the accepted-step convergence cadence.

None

Raises:

Type Description
NotImplementedError

If a custom schedule is requested with the experimental Diffsol backend.

set_params

set_params(stopping_dm_dt: SI | float | None = None, ts_rel_tol: float | None = None, ts_abs_tol: float | None = None, exact_tstop: bool | None = None, ts_max_step: SI | float | None = None) -> None

Update convergence and DOP853 integration controls.

Parameters:

Name Type Description Default
stopping_dm_dt SI | float | None

Positive convergence rate in 1/s.

None
ts_rel_tol float | None

Positive relative error tolerance.

None
ts_abs_tol float | None

Positive absolute error tolerance.

None
exact_tstop bool | None

Whether :meth:advance_time normally reconstructs state exactly at its requested target.

None
ts_max_step SI | float | None

Positive configured maximum step in seconds. Exchange stability can impose a smaller effective maximum.

None

Raises:

Type Description
ValueError

If a supplied rate, tolerance, or step is not finite and positive.

reinitialise

reinitialise(rel_tolerance: float | None = None, abs_tolerance: float | None = None, initial_time: SI | float | None = None) -> None

Rebuild the adaptive integrator from the current physical state.

Parameters:

Name Type Description Default
rel_tolerance float | None

Optional new relative tolerance.

None
abs_tolerance float | None

Optional new absolute tolerance.

None
initial_time SI | float | None

Non-negative physical start time. Omit it to retain the simulation clock.

None

Raises:

Type Description
RuntimeError

If mesh or magnetization has not been set.

ValueError

If the time or tolerances are invalid.

get_restart_file_name

get_restart_file_name() -> Path

Return the default native checkpoint path beside simulation output.

save_restart_file

save_restart_file(filename: str | Path | None = None) -> Path

Atomically save a complete native checkpoint.

Parameters:

Name Type Description Default
filename str | Path | None

Destination path, or None for the simulation's default restart filename.

None

Returns:

Type Description
Path

The checkpoint path.

Raises:

Type Description
RuntimeError

If mesh or magnetization state is incomplete.

load_restart_file

load_restart_file(filename: str | Path | None = None) -> None

Restore complete native state into a compatible loaded simulation.

The target simulation must already have the same mesh and compatible materials. Magnetization, pinning, current density, applied field, clock, integrator controls, and convergence state are restored.

Parameters:

Name Type Description Default
filename str | Path | None

Source path, or None for the default restart filename.

None

Raises:

Type Description
ValueError

If checkpoint schema, mesh, materials, or dimensions are incompatible.

load_m_from_h5file

load_m_from_h5file(filename: str | Path) -> None

Load only checkpoint magnetization into the configured simulation.

Parameters:

Name Type Description Default
filename str | Path

Native checkpoint created for the same mesh.

required

Raises:

Type Description
ValueError

If the checkpoint or mesh is incompatible.