micromagpy 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- micromagpy/__init__.py +8 -0
- micromagpy/config.py +10 -0
- micromagpy/demag.py +144 -0
- micromagpy/drivers.py +67 -0
- micromagpy/energy.py +105 -0
- micromagpy/fft.py +59 -0
- micromagpy/fields.py +157 -0
- micromagpy/llg.py +286 -0
- micromagpy/noise.py +660 -0
- micromagpy/shapes.py +28 -0
- micromagpy/simulation.py +142 -0
- micromagpy/solvers.py +154 -0
- micromagpy/torques.py +174 -0
- micromagpy-1.0.0.dist-info/METADATA +497 -0
- micromagpy-1.0.0.dist-info/RECORD +19 -0
- micromagpy-1.0.0.dist-info/WHEEL +4 -0
- micromagpy-1.0.0.dist-info/licenses/COPYING.LESSER +165 -0
- micromagpy-1.0.0.dist-info/licenses/CREDITS.md +41 -0
- micromagpy-1.0.0.dist-info/licenses/LICENSE +674 -0
micromagpy/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""A small finite-difference micromagnetic simulator built on NumPy, numba and SciPy."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try: # the version is derived from git tags at build time (hatch-vcs)
|
|
6
|
+
__version__ = version("micromagpy")
|
|
7
|
+
except PackageNotFoundError: # pragma: no cover - running from a source tree without installing
|
|
8
|
+
__version__ = "0.0.0+unknown"
|
micromagpy/config.py
ADDED
micromagpy/demag.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Demagnetisation tensor (Newell et al. 1993) for a regular finite-difference mesh.
|
|
2
|
+
|
|
3
|
+
The tensor is evaluated on the zero-padded (2n - 1) grid in FFT ordering and
|
|
4
|
+
returned already transformed to Fourier space (real-to-complex transform over
|
|
5
|
+
the axes with more than one cell). Use it together with
|
|
6
|
+
:func:`micromagpy.fields.compute_hdemag`.
|
|
7
|
+
|
|
8
|
+
Implementation notes
|
|
9
|
+
--------------------
|
|
10
|
+
The original implementation evaluated, for every cell of the padded grid and
|
|
11
|
+
every tensor component, 64 terms of the Newell ``f``/``g`` functions in pure
|
|
12
|
+
Python. Each of those 64 terms is a second finite difference of ``f``/``g``
|
|
13
|
+
along every axis, i.e. a separable ``[-1, 2, -1]`` stencil applied to values of
|
|
14
|
+
the function on the (2n + 1) node grid. Here we evaluate ``f``/``g`` once per
|
|
15
|
+
node (numba, in parallel) and apply the stencil with NumPy slicing, which is
|
|
16
|
+
equivalent up to floating point summation order but orders of magnitude faster.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from math import asinh, atan, pi, sqrt
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from numba import njit, prange
|
|
23
|
+
|
|
24
|
+
from .config import DTYPE
|
|
25
|
+
from .fft import fft_axes, padded_shape, rfftn
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@njit(cache=True)
|
|
29
|
+
def f(x, y, z):
|
|
30
|
+
eps = 1e-18
|
|
31
|
+
x, y, z = abs(x), abs(y), abs(z)
|
|
32
|
+
return (
|
|
33
|
+
+y / 2.0 * (z**2 - x**2) * asinh(y / (sqrt(x**2 + z**2) + eps))
|
|
34
|
+
+ z / 2.0 * (y**2 - x**2) * asinh(z / (sqrt(x**2 + y**2) + eps))
|
|
35
|
+
- x * y * z * atan(y * z / (x * sqrt(x**2 + y**2 + z**2) + eps))
|
|
36
|
+
+ 1.0 / 6.0 * (2 * x**2 - y**2 - z**2) * sqrt(x**2 + y**2 + z**2)
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@njit(cache=True)
|
|
41
|
+
def g(x, y, z):
|
|
42
|
+
eps = 1e-18
|
|
43
|
+
z = abs(z)
|
|
44
|
+
return (
|
|
45
|
+
+x * y * z * asinh(z / (sqrt(x**2 + y**2) + eps))
|
|
46
|
+
+ y / 6.0 * (3.0 * z**2 - y**2) * asinh(x / (sqrt(y**2 + z**2) + eps))
|
|
47
|
+
+ x / 6.0 * (3.0 * z**2 - x**2) * asinh(y / (sqrt(x**2 + z**2) + eps))
|
|
48
|
+
- z**3 / 6.0 * atan(x * y / (z * sqrt(x**2 + y**2 + z**2) + eps))
|
|
49
|
+
- z * y**2 / 2.0 * atan(x * z / (y * sqrt(x**2 + y**2 + z**2) + eps))
|
|
50
|
+
- z * x**2 / 2.0 * atan(y * z / (x * sqrt(x**2 + y**2 + z**2) + eps))
|
|
51
|
+
- x * y * sqrt(x**2 + y**2 + z**2) / 3.0
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# (use_g, permutation) for Nxx, Nxy, Nxz, Nyy, Nyz, Nzz
|
|
56
|
+
_COMPONENTS = (
|
|
57
|
+
(False, (0, 1, 2)),
|
|
58
|
+
(True, (0, 1, 2)),
|
|
59
|
+
(True, (0, 2, 1)),
|
|
60
|
+
(False, (1, 2, 0)),
|
|
61
|
+
(True, (1, 2, 0)),
|
|
62
|
+
(False, (2, 0, 1)),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@njit(parallel=True, cache=True)
|
|
67
|
+
def _node_values(use_g, n0, n1, n2, d0, d1, d2, p0, p1, p2):
|
|
68
|
+
"""Evaluate f or g on all nodes with offsets [-n_k, n_k] along each axis."""
|
|
69
|
+
s0, s1, s2 = 2 * n0 + 1, 2 * n1 + 1, 2 * n2 + 1
|
|
70
|
+
out = np.empty((s0, s1, s2), dtype=np.float64)
|
|
71
|
+
for a in prange(s0):
|
|
72
|
+
coord = np.empty(3)
|
|
73
|
+
for b in range(s1):
|
|
74
|
+
for c in range(s2):
|
|
75
|
+
coord[0] = (a - n0) * d0
|
|
76
|
+
coord[1] = (b - n1) * d1
|
|
77
|
+
coord[2] = (c - n2) * d2
|
|
78
|
+
if use_g:
|
|
79
|
+
out[a, b, c] = g(coord[p0], coord[p1], coord[p2])
|
|
80
|
+
else:
|
|
81
|
+
out[a, b, c] = f(coord[p0], coord[p1], coord[p2])
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _second_difference(arr: np.ndarray, axis: int) -> np.ndarray:
|
|
86
|
+
"""Apply the [-1, 2, -1] stencil along ``axis`` (output shrinks by 2)."""
|
|
87
|
+
lo = [slice(None)] * arr.ndim
|
|
88
|
+
mid = [slice(None)] * arr.ndim
|
|
89
|
+
hi = [slice(None)] * arr.ndim
|
|
90
|
+
lo[axis], mid[axis], hi[axis] = slice(0, -2), slice(1, -1), slice(2, None)
|
|
91
|
+
return 2.0 * arr[tuple(mid)] - arr[tuple(lo)] - arr[tuple(hi)]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _wrap_index(nk: int, size: int) -> np.ndarray:
|
|
95
|
+
"""Positions of offsets -(nk-1)..(nk-1) on a periodic grid of ``size``."""
|
|
96
|
+
return np.arange(-(nk - 1), nk) % size
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def compute_demag_tensor_real(n: tuple, dx: tuple, shape: tuple = None) -> np.ndarray:
|
|
100
|
+
"""Real-space demag tensor on the padded grid, FFT (wrap-around) ordered.
|
|
101
|
+
|
|
102
|
+
``shape`` defaults to :func:`micromagpy.fft.padded_shape` and must be at
|
|
103
|
+
least ``2n - 1`` along every axis with more than one cell.
|
|
104
|
+
Components are ordered (xx, xy, xz, yy, yz, zz).
|
|
105
|
+
"""
|
|
106
|
+
n = tuple(int(k) for k in n)
|
|
107
|
+
# N is dimensionless, so evaluate f/g in units of the largest cell edge.
|
|
108
|
+
# This keeps the regularisation eps = 1e-18 in f/g negligible; in SI units
|
|
109
|
+
# (dx ~ 1e-9 m) terms such as x * r ~ 1e-27 are swamped by eps, which
|
|
110
|
+
# biases the self-demag factors by ~10%.
|
|
111
|
+
scale = max(float(k) for k in dx)
|
|
112
|
+
dx = tuple(float(k) / scale for k in dx)
|
|
113
|
+
if shape is None:
|
|
114
|
+
shape = padded_shape(n)
|
|
115
|
+
if any(s < 2 * k - 1 for s, k in zip(shape, n)):
|
|
116
|
+
raise ValueError(f"Padded shape {shape} too small for mesh {n}")
|
|
117
|
+
n_demag = np.zeros(tuple(shape) + (6,), dtype=DTYPE)
|
|
118
|
+
ix = np.ix_(*(_wrap_index(nk, s) for nk, s in zip(n, shape)))
|
|
119
|
+
norm = -1.0 / (4.0 * pi * np.prod(dx))
|
|
120
|
+
for c, (use_g, perm) in enumerate(_COMPONENTS):
|
|
121
|
+
nodes = _node_values(use_g, *n, *dx, *perm)
|
|
122
|
+
for axis in range(3):
|
|
123
|
+
nodes = _second_difference(nodes, axis)
|
|
124
|
+
# nodes now holds offsets [-(n-1), n-1] in natural order
|
|
125
|
+
n_demag[..., c][ix] = nodes * norm
|
|
126
|
+
return n_demag
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def compute_demag_tensor(n: tuple, dx: tuple) -> np.ndarray:
|
|
130
|
+
"""Fourier-transformed demag tensor, ready for :func:`compute_hdemag`."""
|
|
131
|
+
n_demag = compute_demag_tensor_real(n, dx)
|
|
132
|
+
axes = fft_axes(n)
|
|
133
|
+
if not axes: # single cell
|
|
134
|
+
return n_demag.astype(np.complex128)
|
|
135
|
+
return np.ascontiguousarray(rfftn(n_demag, axes=axes))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def compute_trivial_tensor(n: tuple) -> np.ndarray:
|
|
139
|
+
"""All-zero (Fourier space) tensor, i.e. demagnetisation switched off."""
|
|
140
|
+
axes = fft_axes(n)
|
|
141
|
+
shape = list(padded_shape(n))
|
|
142
|
+
if axes:
|
|
143
|
+
shape[axes[-1]] = shape[axes[-1]] // 2 + 1
|
|
144
|
+
return np.zeros(shape + [6], dtype=np.complex128)
|
micromagpy/drivers.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Time drivers: functions ``t -> value`` for fields, currents and torque amplitudes.
|
|
2
|
+
|
|
3
|
+
Mirrors cmtj's scalar/axial drivers. Values may be scalars, 3-vectors or
|
|
4
|
+
per-cell arrays. Anything accepted as an amplitude in :mod:`micromagpy`
|
|
5
|
+
(``simulate(h_ext=...)``, :class:`~micromagpy.torques.SOT`,
|
|
6
|
+
:class:`~micromagpy.torques.STT`, :class:`~micromagpy.noise.ThermalField`) is
|
|
7
|
+
converted once with :func:`as_driver`, so a plain number, an array, any
|
|
8
|
+
``callable(t)`` or one of the drivers below can be passed.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from math import pi, sin
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
from .config import DTYPE
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Driver:
|
|
23
|
+
"""A value as a function of time. ``constant`` drivers allow caching."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, fn: Callable[[float], Any], constant: bool = False):
|
|
26
|
+
self._fn = fn
|
|
27
|
+
self.constant = constant
|
|
28
|
+
|
|
29
|
+
def __call__(self, t: float):
|
|
30
|
+
return self._fn(t)
|
|
31
|
+
|
|
32
|
+
def __repr__(self) -> str:
|
|
33
|
+
return f"Driver(constant={self.constant})"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def constant(value) -> Driver:
|
|
37
|
+
"""Time independent value."""
|
|
38
|
+
v = np.asarray(value, dtype=DTYPE)
|
|
39
|
+
return Driver(lambda t: v, constant=True)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def step(value, start: float, stop: float = np.inf, base=0.0) -> Driver:
|
|
43
|
+
"""``value`` for ``start <= t < stop``, ``base`` otherwise (a pulse when ``stop`` is finite)."""
|
|
44
|
+
v = np.asarray(value, dtype=DTYPE)
|
|
45
|
+
b = np.asarray(base, dtype=DTYPE)
|
|
46
|
+
return Driver(lambda t: v if start <= t < stop else b)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def pulse(amplitude, start: float, width: float, base=0.0) -> Driver:
|
|
50
|
+
"""Rectangular pulse of ``width`` starting at ``start``."""
|
|
51
|
+
return step(amplitude, start, start + width, base)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sine(amplitude, frequency: float, phase: float = 0.0, offset=0.0) -> Driver:
|
|
55
|
+
"""``offset + amplitude * sin(2 pi f t + phase)``."""
|
|
56
|
+
a = np.asarray(amplitude, dtype=DTYPE)
|
|
57
|
+
o = np.asarray(offset, dtype=DTYPE)
|
|
58
|
+
return Driver(lambda t: o + a * sin(2 * pi * frequency * t + phase))
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def as_driver(value) -> Driver:
|
|
62
|
+
"""Wrap a constant, array, ``callable(t)`` or :class:`Driver` into a :class:`Driver`."""
|
|
63
|
+
if isinstance(value, Driver):
|
|
64
|
+
return value
|
|
65
|
+
if callable(value):
|
|
66
|
+
return Driver(lambda t: np.asarray(value(t), dtype=DTYPE))
|
|
67
|
+
return constant(value)
|
micromagpy/energy.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Micromagnetic energies and energy minimisation (relaxation).
|
|
2
|
+
|
|
3
|
+
Energies (J) of the finite-difference discretisation, consistent with the
|
|
4
|
+
fields of :mod:`micromagpy.fields` (Neumann exchange, Newell demag):
|
|
5
|
+
|
|
6
|
+
* exchange ``E_ex = -mu0 Ms / 2 * V * sum(m . H_ex)`` (= A |grad m|^2)
|
|
7
|
+
* demag ``E_d = -mu0 Ms / 2 * V * sum(m . H_d)``
|
|
8
|
+
* anisotropy ``E_K = -K V sum((m . u)^2)``
|
|
9
|
+
* Zeeman ``E_Z = -mu0 Ms V sum(m . H_ext)``
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .config import DTYPE, GAMMA, MU0
|
|
17
|
+
from .demag import compute_demag_tensor, compute_trivial_tensor
|
|
18
|
+
from .fields import anisotropy_arrays, compute_hdemag, compute_hex, h_eff
|
|
19
|
+
from .llg import normalize
|
|
20
|
+
from .solvers import RK45State, _max_cell_norm, damping_rhs_factory, rk45_step
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _tensor(n, dx, demag):
|
|
24
|
+
if demag is True:
|
|
25
|
+
return compute_demag_tensor(n, dx)
|
|
26
|
+
if demag is False or demag is None:
|
|
27
|
+
return compute_trivial_tensor(n)
|
|
28
|
+
return demag
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def energies(m, dx, ms, A=0.0, K=0.0, kaxis=(0, 0, 1), h_ext=0.0, demag=True) -> dict:
|
|
32
|
+
"""Energy terms (J) and their sum for magnetisation ``m``."""
|
|
33
|
+
m = np.ascontiguousarray(m, dtype=DTYPE)
|
|
34
|
+
n = m.shape[:3]
|
|
35
|
+
V = float(np.prod(dx))
|
|
36
|
+
f_n = _tensor(n, dx, demag)
|
|
37
|
+
e = {}
|
|
38
|
+
e["exchange"] = -0.5 * MU0 * ms * V * float(np.sum(m * compute_hex(A, ms, m, dx, n))) if A else 0.0
|
|
39
|
+
e["demag"] = -0.5 * MU0 * ms * V * float(np.sum(m * ms * compute_hdemag(m, f_n, n)))
|
|
40
|
+
hk, u = anisotropy_arrays(ms, K, kaxis, n)
|
|
41
|
+
e["anisotropy"] = -0.5 * MU0 * ms * V * float(np.sum(hk * np.einsum("...c,...c->...", m, u) ** 2))
|
|
42
|
+
h_ext = np.broadcast_to(np.asarray(h_ext, dtype=DTYPE), m.shape)
|
|
43
|
+
e["zeeman"] = -MU0 * ms * V * float(np.sum(m * h_ext))
|
|
44
|
+
e["total"] = sum(e.values())
|
|
45
|
+
return e
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def relax(
|
|
49
|
+
m,
|
|
50
|
+
dx,
|
|
51
|
+
ms,
|
|
52
|
+
A=0.0,
|
|
53
|
+
K=0.0,
|
|
54
|
+
kaxis=(0, 0, 1),
|
|
55
|
+
h_ext=0.0,
|
|
56
|
+
demag=True,
|
|
57
|
+
torque_tol: float = 1e-3,
|
|
58
|
+
tol: float = 1e-4,
|
|
59
|
+
max_steps: int = 100000,
|
|
60
|
+
dt0: float = 1e-13,
|
|
61
|
+
energy_every: int = 0,
|
|
62
|
+
):
|
|
63
|
+
"""Minimise the energy by integrating the precession-free flow ``dm/dt = -gamma m x (m x H)``.
|
|
64
|
+
|
|
65
|
+
The flow is integrated with adaptive Dormand-Prince steps (``tol`` is the
|
|
66
|
+
allowed per-cell change error, so large steps are taken once the dynamics
|
|
67
|
+
slows down). Converged when ``max |m x H| / Ms < torque_tol``.
|
|
68
|
+
|
|
69
|
+
:return: dict with ``m``, ``converged``, ``steps``, ``max_torque`` (A/m),
|
|
70
|
+
``energies`` (final, see :func:`energies`) and, with
|
|
71
|
+
``energy_every > 0``, an ``energy_history`` list of total energies.
|
|
72
|
+
"""
|
|
73
|
+
m = normalize(np.array(m, dtype=DTYPE))
|
|
74
|
+
n = m.shape[:3]
|
|
75
|
+
f_n = _tensor(n, dx, demag)
|
|
76
|
+
h_ext_arr = np.broadcast_to(np.asarray(h_ext, dtype=DTYPE), m.shape)
|
|
77
|
+
|
|
78
|
+
def field(mm, t=0.0):
|
|
79
|
+
return h_eff(A=A, ms=ms, K=K, kaxis=kaxis, m=mm, m_pad=None, f_n_demag=f_n, n=n, dx=dx) + h_ext_arr
|
|
80
|
+
|
|
81
|
+
rhs = damping_rhs_factory(GAMMA, field)
|
|
82
|
+
state = RK45State(dt=dt0)
|
|
83
|
+
t = 0.0
|
|
84
|
+
history = []
|
|
85
|
+
torque = np.inf
|
|
86
|
+
converged = False
|
|
87
|
+
for step in range(max_steps):
|
|
88
|
+
if energy_every and step % energy_every == 0:
|
|
89
|
+
history.append(energies(m, dx, ms, A, K, kaxis, h_ext, f_n)["total"])
|
|
90
|
+
m, t, _ = rk45_step(rhs, m, t, state, tol)
|
|
91
|
+
# |dm/dt| = gamma |m x H| for the damping-only flow (|m| = 1)
|
|
92
|
+
torque = _max_cell_norm(state.k1) / GAMMA
|
|
93
|
+
if torque < torque_tol * ms:
|
|
94
|
+
converged = True
|
|
95
|
+
break
|
|
96
|
+
return {
|
|
97
|
+
"m": m,
|
|
98
|
+
"converged": converged,
|
|
99
|
+
"steps": state.accepted,
|
|
100
|
+
"rejected": state.rejected,
|
|
101
|
+
"pseudo_time": t,
|
|
102
|
+
"max_torque": torque,
|
|
103
|
+
"energies": energies(m, dx, ms, A, K, kaxis, h_ext, f_n),
|
|
104
|
+
"energy_history": history,
|
|
105
|
+
}
|
micromagpy/fft.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Thin FFT wrapper: prefer multithreaded ``scipy.fft``, fall back to NumPy."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
try: # pragma: no cover - depends on the environment
|
|
6
|
+
from scipy import fft as _fft
|
|
7
|
+
|
|
8
|
+
_WORKERS = int(os.environ.get("MICROMAGPY_FFT_WORKERS", "-1"))
|
|
9
|
+
|
|
10
|
+
def rfftn(x, s=None, axes=None):
|
|
11
|
+
return _fft.rfftn(x, s=s, axes=axes, workers=_WORKERS)
|
|
12
|
+
|
|
13
|
+
def irfftn(x, s=None, axes=None):
|
|
14
|
+
return _fft.irfftn(x, s=s, axes=axes, workers=_WORKERS)
|
|
15
|
+
|
|
16
|
+
def next_fast_len(k: int) -> int:
|
|
17
|
+
return _fft.next_fast_len(k, real=True)
|
|
18
|
+
|
|
19
|
+
except ImportError: # pragma: no cover
|
|
20
|
+
import numpy as _np
|
|
21
|
+
|
|
22
|
+
def rfftn(x, s=None, axes=None):
|
|
23
|
+
return _np.fft.rfftn(x, s=s, axes=axes)
|
|
24
|
+
|
|
25
|
+
def irfftn(x, s=None, axes=None):
|
|
26
|
+
return _np.fft.irfftn(x, s=s, axes=axes)
|
|
27
|
+
|
|
28
|
+
def next_fast_len(k: int) -> int:
|
|
29
|
+
"""Smallest 2^a 3^b 5^c >= k."""
|
|
30
|
+
best = 1 << max(int(k) - 1, 0).bit_length()
|
|
31
|
+
p5 = 1
|
|
32
|
+
while p5 < best:
|
|
33
|
+
p35 = p5
|
|
34
|
+
while p35 < best:
|
|
35
|
+
p = p35
|
|
36
|
+
while p < k:
|
|
37
|
+
p *= 2
|
|
38
|
+
best = min(best, p)
|
|
39
|
+
p35 *= 3
|
|
40
|
+
p5 *= 5
|
|
41
|
+
return best
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def fft_axes(n) -> tuple:
|
|
45
|
+
"""Spatial axes that carry more than one cell (the only ones transformed)."""
|
|
46
|
+
return tuple(i for i in range(3) if n[i] > 1)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def padded_shape(n, fast: bool = True) -> tuple:
|
|
50
|
+
"""Zero-padded grid used for the FFT convolution.
|
|
51
|
+
|
|
52
|
+
Any size >= 2n - 1 gives the exact (non-periodic) convolution on the first
|
|
53
|
+
n cells, so by default we round up to a size with small prime factors,
|
|
54
|
+
which is much faster for the FFT (e.g. 2 * 100 - 1 = 199 is prime -> 200).
|
|
55
|
+
Axes with a single cell are not padded.
|
|
56
|
+
"""
|
|
57
|
+
if not fast:
|
|
58
|
+
return tuple(2 * int(k) - 1 for k in n)
|
|
59
|
+
return tuple(next_fast_len(2 * int(k) - 1) if int(k) > 1 else 1 for k in n)
|
micromagpy/fields.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Effective field contributions.
|
|
2
|
+
|
|
3
|
+
All fields are in A/m and act on arrays of shape ``n + (3,)``.
|
|
4
|
+
The heavy lifting is done by fused numba kernels which avoid the temporary
|
|
5
|
+
arrays the pure NumPy implementation allocated on every step.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numba import njit, prange
|
|
10
|
+
|
|
11
|
+
from .config import DTYPE, MU0
|
|
12
|
+
from .fft import fft_axes, irfftn, padded_shape, rfftn
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _unit_axis(axis) -> np.ndarray:
|
|
16
|
+
u = np.asarray(axis, dtype=DTYPE).reshape(3)
|
|
17
|
+
norm = np.linalg.norm(u)
|
|
18
|
+
if norm == 0:
|
|
19
|
+
raise ValueError("Anisotropy axis must be a non-zero vector")
|
|
20
|
+
return u / norm
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def anisotropy_arrays(ms, K, kaxis, n):
|
|
24
|
+
"""Per-cell ``Hk = 2K/(mu0 Ms)`` of shape ``n`` and unit axes ``n + (3,)``.
|
|
25
|
+
|
|
26
|
+
``K`` may be a scalar or an array of shape ``n``; ``kaxis`` a 3-vector or
|
|
27
|
+
an array of shape ``n + (3,)`` (normalised per cell; zero vectors allowed
|
|
28
|
+
where ``K == 0``). Scalars are broadcast without copying.
|
|
29
|
+
"""
|
|
30
|
+
n = tuple(int(k) for k in n)
|
|
31
|
+
hk = np.asarray(K, dtype=DTYPE) * (2.0 / (MU0 * ms))
|
|
32
|
+
hk = np.broadcast_to(hk, n)
|
|
33
|
+
u = np.asarray(kaxis, dtype=DTYPE)
|
|
34
|
+
if u.shape == (3,):
|
|
35
|
+
u = np.broadcast_to(_unit_axis(u) if np.any(u) else u, n + (3,))
|
|
36
|
+
else:
|
|
37
|
+
u = np.broadcast_to(u, n + (3,))
|
|
38
|
+
norm = np.linalg.norm(u, axis=-1, keepdims=True)
|
|
39
|
+
u = np.divide(u, norm, out=np.zeros(n + (3,), dtype=DTYPE), where=norm > 0)
|
|
40
|
+
return hk, u
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@njit(parallel=True, cache=True)
|
|
44
|
+
def _exchange_anisotropy_kernel(m, hd, scale_d, out, cex, idx2, hk, u, add_hd):
|
|
45
|
+
"""out = [scale_d * hd] + cex * laplacian(m) + hk * (m . u) u.
|
|
46
|
+
|
|
47
|
+
``hk`` has shape n and ``u`` shape n + (3,) (per-cell uniaxial anisotropy).
|
|
48
|
+
Neumann (edge-replicated) boundaries; ``hd`` is only read if ``add_hd``.
|
|
49
|
+
"""
|
|
50
|
+
nx, ny, nz, _ = m.shape
|
|
51
|
+
for i in prange(nx):
|
|
52
|
+
im = i - 1 if i > 0 else 0
|
|
53
|
+
ip = i + 1 if i < nx - 1 else nx - 1
|
|
54
|
+
for j in range(ny):
|
|
55
|
+
jm = j - 1 if j > 0 else 0
|
|
56
|
+
jp = j + 1 if j < ny - 1 else ny - 1
|
|
57
|
+
for k in range(nz):
|
|
58
|
+
km = k - 1 if k > 0 else 0
|
|
59
|
+
kp = k + 1 if k < nz - 1 else nz - 1
|
|
60
|
+
ux, uy, uz = u[i, j, k, 0], u[i, j, k, 1], u[i, j, k, 2]
|
|
61
|
+
hmu = hk[i, j, k] * (m[i, j, k, 0] * ux + m[i, j, k, 1] * uy + m[i, j, k, 2] * uz)
|
|
62
|
+
for c in range(3):
|
|
63
|
+
mc = m[i, j, k, c]
|
|
64
|
+
lap = (
|
|
65
|
+
(m[ip, j, k, c] + m[im, j, k, c] - 2.0 * mc) * idx2[0]
|
|
66
|
+
+ (m[i, jp, k, c] + m[i, jm, k, c] - 2.0 * mc) * idx2[1]
|
|
67
|
+
+ (m[i, j, kp, c] + m[i, j, km, c] - 2.0 * mc) * idx2[2]
|
|
68
|
+
)
|
|
69
|
+
val = cex * lap + hmu * u[i, j, k, c]
|
|
70
|
+
if add_hd:
|
|
71
|
+
val += scale_d * hd[i, j, k, c]
|
|
72
|
+
out[i, j, k, c] = val
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def compute_anisotropy_field(ms: float, K, m: np.ndarray, axis) -> np.ndarray:
|
|
76
|
+
"""Uniaxial anisotropy field ``2K/(mu0 Ms) (m . u) u`` (K, axis scalar/vector or per cell)."""
|
|
77
|
+
hk, u = anisotropy_arrays(ms, K, axis, m.shape[:3])
|
|
78
|
+
return (hk * np.einsum("...c,...c->...", m, u))[..., None] * u
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def compute_hex(
|
|
82
|
+
A: float, ms: float, m: np.ndarray, dx: tuple, n: tuple = None
|
|
83
|
+
) -> np.ndarray:
|
|
84
|
+
"""Exchange field ``2A/(mu0 Ms) laplacian(m)`` with Neumann boundaries."""
|
|
85
|
+
m = np.ascontiguousarray(m, dtype=DTYPE)
|
|
86
|
+
out = np.empty_like(m)
|
|
87
|
+
idx2 = np.array([1.0 / d**2 for d in dx], dtype=DTYPE)
|
|
88
|
+
hk, u = anisotropy_arrays(ms, 0.0, np.zeros(3), m.shape[:3])
|
|
89
|
+
_exchange_anisotropy_kernel(m, m, 0.0, out, 2 * A / (MU0 * ms), idx2, hk, u, False)
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@njit(parallel=True, cache=True)
|
|
94
|
+
def _tensor_multiply(fn, fm, out):
|
|
95
|
+
"""out = N(k) . m(k) for the symmetric tensor (xx, xy, xz, yy, yz, zz)."""
|
|
96
|
+
a, b, c, _ = fm.shape
|
|
97
|
+
for i in prange(a):
|
|
98
|
+
for j in range(b):
|
|
99
|
+
for k in range(c):
|
|
100
|
+
mx = fm[i, j, k, 0]
|
|
101
|
+
my = fm[i, j, k, 1]
|
|
102
|
+
mz = fm[i, j, k, 2]
|
|
103
|
+
out[i, j, k, 0] = (
|
|
104
|
+
fn[i, j, k, 0] * mx + fn[i, j, k, 1] * my + fn[i, j, k, 2] * mz
|
|
105
|
+
)
|
|
106
|
+
out[i, j, k, 1] = (
|
|
107
|
+
fn[i, j, k, 1] * mx + fn[i, j, k, 3] * my + fn[i, j, k, 4] * mz
|
|
108
|
+
)
|
|
109
|
+
out[i, j, k, 2] = (
|
|
110
|
+
fn[i, j, k, 2] * mx + fn[i, j, k, 4] * my + fn[i, j, k, 5] * mz
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def compute_hdemag(
|
|
115
|
+
m_pad: np.ndarray, f_n_demag: np.ndarray, n: tuple, axes: tuple = None
|
|
116
|
+
) -> np.ndarray:
|
|
117
|
+
"""Demagnetisation field (in units of Ms) by FFT convolution.
|
|
118
|
+
|
|
119
|
+
``m_pad`` can either be the zero-padded magnetisation of shape
|
|
120
|
+
``(2n - 1) + (3,)`` or the unpadded magnetisation of shape ``n + (3,)``;
|
|
121
|
+
in the latter case the padding is done implicitly by the FFT.
|
|
122
|
+
"""
|
|
123
|
+
n = tuple(int(k) for k in n)
|
|
124
|
+
if axes is None:
|
|
125
|
+
axes = fft_axes(n)
|
|
126
|
+
axes = tuple(axes)
|
|
127
|
+
m_in = m_pad
|
|
128
|
+
if m_in.shape[:3] != n:
|
|
129
|
+
m_in = m_in[: n[0], : n[1], : n[2], :]
|
|
130
|
+
if not axes: # single cell: tensor is just a constant
|
|
131
|
+
fm = m_in.astype(np.complex128)
|
|
132
|
+
out = np.empty_like(fm)
|
|
133
|
+
_tensor_multiply(f_n_demag, fm, out)
|
|
134
|
+
return out.real.copy()
|
|
135
|
+
pshape = padded_shape(n)
|
|
136
|
+
s = [pshape[a] for a in axes]
|
|
137
|
+
fm = rfftn(m_in, s=s, axes=axes)
|
|
138
|
+
out = np.empty_like(fm)
|
|
139
|
+
_tensor_multiply(f_n_demag, fm, out)
|
|
140
|
+
h = irfftn(out, s=s, axes=axes)
|
|
141
|
+
return h[: n[0], : n[1], : n[2], :]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def h_eff(A, ms, K, kaxis, m, m_pad, f_n_demag, n, dx):
|
|
145
|
+
"""Demag + exchange + uniaxial anisotropy field (A/m).
|
|
146
|
+
|
|
147
|
+
``K`` / ``kaxis`` may be per cell (shapes ``n`` / ``n + (3,)``), e.g. for
|
|
148
|
+
grains or domains with different anisotropy, see :func:`anisotropy_arrays`.
|
|
149
|
+
"""
|
|
150
|
+
n = tuple(int(k) for k in n)
|
|
151
|
+
m = np.ascontiguousarray(m, dtype=DTYPE)
|
|
152
|
+
hd = compute_hdemag(m_pad=m, f_n_demag=f_n_demag, n=n)
|
|
153
|
+
h = np.empty_like(m)
|
|
154
|
+
idx2 = np.array([1.0 / d**2 for d in dx], dtype=DTYPE)
|
|
155
|
+
hk, u = anisotropy_arrays(ms, K, kaxis, n)
|
|
156
|
+
_exchange_anisotropy_kernel(m, hd, float(ms), h, 2 * A / (MU0 * ms), idx2, hk, u, True)
|
|
157
|
+
return h
|