repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
finmag
|
finmag-master/src/finmag/tests/test_skyrmions.py
|
# every function which starts with test_
# will get automatically by the test runner.
# you can have as many test functions per file as you want.
def test_skyrmion():
TOLERANCE = 1e-6
# Setup your problem, compute some results.
my_result = 1e-5
expected_result = 1e-5
assert abs(my_result - expected_result) < TOLERANCE
| 345 | 22.066667 | 59 |
py
|
finmag
|
finmag-master/src/finmag/tests/test_llg.py
|
import numpy as np
import dolfin as df
from finmag.physics.llg import LLG
from finmag.util.helpers import components
def test_method_of_computing_the_average_matters():
length = 20e-9 # m
simplices = 10
mesh = df.IntervalMesh(simplices, 0, length)
S1 = df.FunctionSpace(mesh, "Lagrange", 1)
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
llg = LLG(S1, S3)
llg.set_m((
'(2*x[0]-L)/L',
'sqrt(1 - ((2*x[0]-L)/L)*((2*x[0]-L)/L))',
'0'), L=length)
average1 = llg.m_average
average2 = np.mean(components(llg.m_numpy), axis=1)
diff = np.abs(average1 - average2)
assert diff.max() > 5e-2
| 662 | 26.625 | 59 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/oscillator/test_oscillator.py
|
import os
import run as sim
import numpy as np
epsilon = 1e-16
tolerance = 1e-3
nmag_file = os.path.join(sim.MODULE_DIR, "averages_nmag5.txt")
def _test_oscillator():
if not os.path.exists(sim.initial_m_file):
sim.create_initial_state()
sim.run_simulation()
averages = np.loadtxt(sim.averages_file)
nmag_avg = np.loadtxt(nmag_file)
diff = np.abs(np.array(averages) - np.array(nmag_avg))
assert np.max(diff[:, 0]) < epsilon # compare times
assert np.max(diff[:, 1:]) < tolerance
| 520 | 23.809524 | 62 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/oscillator/run.py
|
import os
import numpy as np
from finmag import Simulation as Sim
from finmag.energies import Exchange, Demag
from finmag.util.meshes import from_geofile
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
initial_m_file = os.path.join(MODULE_DIR, "m0.txt")
averages_file = os.path.join(MODULE_DIR, "averages.txt")
mesh = from_geofile(os.path.join(MODULE_DIR, "mesh.geo"))
mesh_centre = (5, 50, 50)
Ms = 8.6e5
def m_gen(rs):
v = np.zeros(rs.shape)
v[0] = 1
v[1] = rs[2] - mesh_centre[2]
v[2] = - (rs[1] - mesh_centre[1])
return v
def create_initial_state():
print "Creating initial relaxed state."
sim = Sim(mesh, Ms=Ms, unit_length=1e-9)
sim.set_m(m_gen)
sim.alpha = 0.5
sim.add(Exchange(1.3e-11))
sim.add(Demag())
sim.relax()
np.savetxt(initial_m_file, sim.m)
def run_simulation():
print "Running simulation of STT dynamics."
sim = Sim(mesh, Ms=Ms, unit_length=1e-9)
sim.set_m(np.loadtxt(initial_m_file))
sim.alpha = 0.01
sim.add(Exchange(1.3e-11))
sim.add(Demag())
sim.llg.use_slonczewski(J=0.1e12, P=0.4, d=10e-9, p=(0, 1, 0))
with open(averages_file, "w") as f:
dt = 5e-12
t_max = 10e-9
for t in np.arange(0, t_max, dt):
sim.run_until(t)
f.write("{} {} {} {}\n".format(t, *sim.m_average))
if __name__ == "__main__":
if not os.path.exists(initial_m_file):
create_initial_state()
run_simulation()
| 1,460 | 26.566038 | 66 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/oscillator/run_nmag5.py
|
import os
import sys
from nsim.si_units.si import SI, degrees_per_ns
from nmag.nmag5 import Simulation, MagMaterial
from nmag import at, every
from nsim.model import Value
from nsim.netgen import netgen_mesh_from_file
mesh_filename = "mesh.nmesh.h5"
mesh_geo = "mesh.geo"
# create mesh if required
if not os.path.exists(mesh_filename):
netgen_mesh_from_file(mesh_geo, mesh_filename)
relaxed_m = "m0.h5"
film_centre = (5, 50, 50)
do_relaxation = not os.path.exists(relaxed_m)
ps = SI(1e-12, "s")
mat = MagMaterial("Py",
Ms=SI(0.86e6, "A/m"),
exchange_coupling=SI(13e-12, "J/m"),
llg_damping=SI(0.5 if do_relaxation else 0.01))
mat.sl_P = 0.0 if do_relaxation else 0.4 # Polarisation
mat.sl_d = SI(10e-9, "m") # Free layer thickness
sim = Simulation(do_sl_stt=True)
sim.load_mesh(mesh_filename, [("region1", mat)], unit_length=SI(1e-9, "m"))
def m0(r):
dx, dy, dz = tuple(ri - ri0 * 1e-9 for ri, ri0 in zip(r, film_centre))
v = (1.0e-9, dz, -dy)
vn = (1.0e-9 ** 2 + dy * dy + dz * dz) ** 0.5
return tuple(vi / vn for vi in v)
sim.set_m(m0)
sim.set_H_ext([0, 0, 0], SI("A/m"))
# Direction of the polarization
sim.model.quantities["sl_fix"].set_value(Value([0, 1, 0]))
# Current density
sim.model.quantities["sl_current_density"].set_value(
Value(SI(0.1e12, "A/m^2")))
if do_relaxation:
print "DOING RELAXATION"
sim.relax(save=[("fields", at("time", 0 * ps) | at("convergence"))])
sim.save_m_to_file(relaxed_m)
sys.exit(0)
else:
print "DOING DYNAMICS"
sim.load_m_from_h5file(relaxed_m)
sim.set_params(stopping_dm_dt=0 * degrees_per_ns)
sim.relax(save=[("averages", every("time", 5 * ps))],
do=[("exit", at("time", 10000 * ps))])
# ipython()
| 1,797 | 25.835821 | 75 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/simple/run_no_stt.py
|
import os
import numpy as np
from finmag import Simulation as Sim
from finmag.energies import Exchange, Zeeman
from finmag.util.meshes import from_geofile
from finmag.util.consts import mu0
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
averages_file = os.path.join(MODULE_DIR, "averages_no_stt.txt")
mesh = from_geofile(os.path.join(MODULE_DIR, "mesh.geo"))
def run_simulation():
L = W = 12.5e-9
H = 5e-9
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)
sim.set_m((1, 0.01, 0.01))
sim.alpha = 0.014
sim.gamma = 221017
H_app_mT = np.array([0.0, 0.0, 10.0])
H_app_SI = H_app_mT / (1000 * mu0)
sim.add(Zeeman(tuple(H_app_SI)))
sim.add(Exchange(1.3e-11))
with open(averages_file, "w") as f:
dt = 10e-12
t_max = 10e-9
for t in np.arange(0, t_max, dt):
sim.run_until(t)
f.write("{} {} {} {}\n".format(t, *sim.m_average))
if __name__ == "__main__":
run_simulation()
| 967 | 25.888889 | 63 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/simple/run.py
|
import os
import numpy as np
from math import pi, sin, cos
from finmag import Simulation as Sim
from finmag.energies import Exchange, Zeeman
from finmag.util.meshes import from_geofile
from finmag.util.consts import mu0
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
averages_file = os.path.join(MODULE_DIR, "averages.txt")
mesh = from_geofile(os.path.join(MODULE_DIR, "mesh.geo"))
def run_simulation():
L = W = 12.5e-9
H = 2.5e-9
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)
sim.set_m((1, 0.01, 0.01))
sim.alpha = 0.014
sim.gamma = 221017
H_app_mT = np.array([0.0, 0.0, 10.0])
H_app_SI = H_app_mT / (1000 * mu0)
sim.add(Zeeman(tuple(H_app_SI)))
sim.add(Exchange(1.3e-11))
I = 5e-5 # current in A
J = I / (L * W) # current density in A/m^2
theta = 40.0 * pi / 180
phi = pi / 2 # polarisation direction
p = (sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta))
sim.llg.use_slonczewski(J=J, P=0.4, d=H, p=p)
with open(averages_file, "w") as f:
dt = 10e-12
t_max = 10e-9
for t in np.arange(0, t_max, dt):
sim.run_until(t)
f.write("{} {} {} {}\n".format(t, *sim.m_average))
if __name__ == "__main__":
run_simulation()
| 1,258 | 27.613636 | 66 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/simple/run_nmag5_no_stt.py
|
import math
from nmag.common import SI, degrees_per_ns, Tesla, mu0, at, every
from nmag.nmag5 import Simulation, MagMaterial
# Applied field
Happ_dir = [0, 0, 10] # in mT
# Material definition
mat = MagMaterial("Py", Ms=SI(860e3, "A/m"),
exchange_coupling=SI(13e-12, "J/m"),
llg_gamma_G=SI(221017, "m/s A"),
llg_damping=SI(0.014))
sim = Simulation("nmag_no_stt", do_demag=False)
nm = SI(1e-9, "m")
sim.load_mesh("mesh.nmesh", [("cube", mat)], unit_length=nm)
sim.set_m([1, 0.01, 0.01])
sim.set_H_ext(Happ_dir, 0.001 * Tesla / mu0)
# Define the tolerances for the simulation
ns = SI(1e-9, "s")
sim.set_params(stopping_dm_dt=0 * degrees_per_ns,
ts_rel_tol=1e-8, ts_abs_tol=1e-8,
ts_pc_rel_tol=1e-3, ts_pc_abs_tol=1e-8,
demag_dbc_rel_tol=1e-6, demag_dbc_abs_tol=1e-6)
sim.relax(save=[("averages", every("time", 0.01 * ns))],
do=[("exit", at("time", 10 * ns))])
| 972 | 33.75 | 65 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/simple/run_nmag5.py
|
import math
from nmag.common import SI, degrees_per_ns, Tesla, mu0, at, every
from nmag.nmag5 import Simulation, MagMaterial
from nsim.model import Value
# Geometry
nm = SI(1e-9, "m")
length = width = 12.5 * nm
height = 2.5 * nm
# Applied field
Happ_dir = [0, 0, 10] # in mT
# Material definition
mat = MagMaterial("Py", Ms=SI(860e3, "A/m"),
exchange_coupling=SI(13e-12, "J/m"),
llg_gamma_G=SI(221017, "m/s A"),
llg_damping=SI(0.014))
# Parameters relevant to spin-torque transfer
# Current and Current Density
I = SI(5e-5, "A")
J = I / (length * width)
mat.sl_P = 0.4 # Polarisation
mat.sl_lambda = 2.0 # lambda parameter
mat.sl_d = height # Free layer thickness
# Direction of the polarisation
theta = 40.0
phi = 90.0
theta_rad = math.pi * theta / 180.0
phi_rad = math.pi * phi / 180.0
P_direction = [math.sin(theta_rad) * math.cos(phi_rad),
math.sin(theta_rad) * math.sin(phi_rad),
math.cos(theta_rad)]
sim = Simulation(do_sl_stt=True, do_demag=False)
sim.load_mesh("mesh.nmesh", [("cube", mat)], unit_length=nm)
sim.set_m([1, 0.01, 0.01])
sim.set_H_ext(Happ_dir, 0.001 * Tesla / mu0)
# Set the polarization direction and current density
sim.model.quantities["sl_fix"].set_value(Value(P_direction))
sim.model.quantities["sl_current_density"].set_value(Value(J))
# Define the tolerances for the simulation
ps = SI(1e-12, "s")
sim.set_params(stopping_dm_dt=0 * degrees_per_ns,
ts_rel_tol=1e-8, ts_abs_tol=1e-8,
ts_pc_rel_tol=1e-3, ts_pc_abs_tol=1e-8,
demag_dbc_rel_tol=1e-6, demag_dbc_abs_tol=1e-6)
sim.relax(save=[("averages", every("time", 10 * ps))],
do=[("exit", at("time", 10000 * ps))])
| 1,771 | 31.218182 | 65 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/with_and_without/run.py
|
import os
import dolfin as df
import numpy as np
from math import pi, sin, cos
from finmag import Simulation as Sim
from finmag.energies import Exchange, UniaxialAnisotropy, Zeeman
from finmag.util.consts import mu0
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
averages_without = os.path.join(MODULE_DIR, "m_averages_without.txt")
averages_with = os.path.join(MODULE_DIR, "m_averages_with.txt")
L = W = 12.5e-9
H = 5e-9
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(L, W, H), 5, 5, 2)
def run_sim_without_stt():
sim = Sim(mesh, Ms=8.6e5)
sim.set_m((1, 0.01, 0.01))
sim.alpha = 0.014
sim.gamma = 221017
H_app_mT = np.array([0.2, 0.2, 10.0])
H_app_SI = H_app_mT / (1000 * mu0)
sim.add(Zeeman(tuple(H_app_SI)))
sim.add(Exchange(1.3e-11))
sim.add(UniaxialAnisotropy(1e5, (0, 0, 1)))
with open(averages_without, "w") as f:
dt = 5e-12
t_max = 10e-9
for t in np.arange(0, t_max, dt):
sim.run_until(t)
f.write("{} {} {} {}\n".format(t, *sim.m_average))
def run_sim_with_stt():
sim = Sim(mesh, Ms=8.6e5)
sim.set_m((1, 0.01, 0.01))
sim.alpha = 0.014
sim.gamma = 221017
H_app_mT = np.array([0.2, 0.2, 10.0])
H_app_SI = H_app_mT / (1000 * mu0)
sim.add(Zeeman(tuple(H_app_SI)))
sim.add(Exchange(1.3e-11))
sim.add(UniaxialAnisotropy(1e5, (0, 0, 1)))
I = 5e-5 # current in A
J = I / (L * W) # current density in A/m^2
theta = 40.0 * pi / 180
phi = pi / 2 # polarisation direction
p = (sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta))
sim.llg.use_slonczewski(J=J, P=0.4, d=5e-9, p=(0, 1, 0))
with open(averages_with, "w") as f:
dt = 5e-12
t_max = 10e-9
for t in np.arange(0, t_max, dt):
sim.run_until(t)
f.write("{} {} {} {}\n".format(t, *sim.m_average))
if __name__ == "__main__":
print "Running sim without STT."
run_sim_without_stt()
print "Running sim with STT."
run_sim_with_stt()
| 2,023 | 27.507042 | 69 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/validation/nmag/run.py
|
import os
import math
import numpy as np
from nsim.netgen import netgen_mesh_from_string
from nmag.common import SI, degrees_per_ns, Tesla, mu0, at, every
from nmag.nmag5 import Simulation, MagMaterial, uniaxial_anisotropy
from nsim.model import Value
ps = SI(1e-12, "s")
nm = SI(1e-9, "m") # Useful definitions
theta = 40.0
phi = 90.0 # Polarization direction
length, width, thick = (12.5 * nm, 12.5 * nm, 5 * nm) # System geometry
I = SI(5e-5, "A")
current_density = I / (length * width) # Applied current
Happ_dir = [0.2, 0.2, 10.0] # Applied field (mT)
# Create the mesh, if it does not exist
mesh_filename = "film.nmesh.h5"
if not os.path.exists(mesh_filename):
mesh_geo = \
("algebraic3d\n"
"solid cube = orthobrick (0, 0, 0; %s, %s, %s) -maxh = 2.5;\n"
"tlo cube;\n" % tuple(map(lambda x: float(x / nm), (length, width, thick))))
netgen_mesh_from_string(mesh_geo, mesh_filename, keep_geo=True)
# Material definition
anis = uniaxial_anisotropy(axis=[0, 0, 1], K1=-SI(0.1e6, "J/m^3"))
mat = MagMaterial("Py",
Ms=SI(860e3, "A/m"),
exchange_coupling=SI(13e-12, "J/m"),
llg_gamma_G=SI(221017, "m/s A"),
llg_damping=SI(0.014),
anisotropy=anis)
mat.sl_P = 0.4 # Polarisation
mat.sl_lambda = 2.0 # lambda parameter
mat.sl_d = SI(5.0e-9, "m") # Free layer thickness
sim = Simulation(do_sl_stt=True, do_demag=False)
sim.load_mesh(mesh_filename, [("region1", mat)], unit_length=nm)
sim.set_m([1, 0.01, 0.01])
sim.set_H_ext(Happ_dir, 0.001 * Tesla / mu0)
# Direction of the polarization. We normalize this by hand because
# nmag doesn't seem to do it automatically.
theta_rad = math.pi * theta / 180.0
phi_rad = math.pi * phi / 180.0
P_direction = np.array([math.sin(theta_rad) * math.cos(phi_rad),
math.sin(theta_rad) * math.sin(phi_rad),
math.cos(theta_rad)])
P_direction = list(P_direction / np.linalg.norm(P_direction))
# Set the polarization direction and current density
sim.model.quantities["sl_fix"].set_value(Value(P_direction))
sim.model.quantities["sl_current_density"].set_value(Value(current_density))
# Define the tolerances for the simulation
sim.set_params(stopping_dm_dt=0 * degrees_per_ns,
ts_rel_tol=1e-8, ts_abs_tol=1e-8,
ts_pc_rel_tol=1e-3, ts_pc_abs_tol=1e-8,
demag_dbc_rel_tol=1e-6, demag_dbc_abs_tol=1e-6)
sim.relax(save=[("averages", every("time", 5 * ps))],
do=[("exit", at("time", 10000 * ps))])
| 2,649 | 39.769231 | 85 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/validation/finmag/test_finmag_validation.py
|
import os
import numpy as np
from finmag.util.fileio import Tablereader
from run_validation import run_simulation
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
FINMAG_DYNAMICS_FILE = "finmag_validation_light.ndt"
NMAG_FILE = os.path.join(MODULE_DIR, "../nmag/averages_nmag5.txt")
OOMMF_FILE = os.path.join(MODULE_DIR, "../oommf/averages_oommf.txt")
EPSILON = 1e-16
TOLERANCE = 1e-4
def extract_magnetisation_dynamics():
reader = Tablereader("finmag_validation.ndt")
dynamics = np.array(reader["time", "m_x", "m_y", "m_z"]).T
np.savetxt(FINMAG_DYNAMICS_FILE, dynamics, header="time mx my mz")
def test_against_nmag():
run_simulation()
if not os.path.isfile(FINMAG_DYNAMICS_FILE):
extract_magnetisation_dynamics()
finmag_dynamics = np.loadtxt(FINMAG_DYNAMICS_FILE)
nmag_dynamics = np.loadtxt(NMAG_FILE)
diff = np.abs(np.array(finmag_dynamics) - np.array(nmag_dynamics))
print("Deviation is %s" % (np.max(diff)))
assert np.max(diff[:, 0]) < EPSILON # compare timesteps
assert np.max(diff[:, 1:]) < TOLERANCE
def plot_dynamics():
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(15, 6))
ax = fig.add_subplot(111)
if os.path.isfile(NMAG_FILE):
nmag = np.loadtxt(NMAG_FILE)
nmag[:, 0] *= 1e9
ax.plot(nmag[:, 0], nmag[:, 1], "rx", label="nmag m_x")
ax.plot(nmag[:, 0], nmag[:, 2], "bx", label="nmag m_y")
ax.plot(nmag[:, 0], nmag[:, 3], "gx", label="nmag m_z")
else:
print "Missing nmag file."
if os.path.isfile(OOMMF_FILE):
oommf = np.loadtxt(OOMMF_FILE)
oommf[:, 0] *= 1e9
ax.plot(oommf[:, 0], oommf[:, 1], "r+", label="oommf m_x")
ax.plot(oommf[:, 0], oommf[:, 2], "b+", label="oommf m_y")
ax.plot(oommf[:, 0], oommf[:, 3], "g+", label="oommf m_z")
else:
print "Missing oommf file."
finmag = np.loadtxt(FINMAG_DYNAMICS_FILE)
finmag[:, 0] *= 1e9
ax.plot(finmag[:, 0], finmag[:, 1], "k", label="finmag m_x")
ax.plot(finmag[:, 0], finmag[:, 2], "k", label="finmag m_y")
ax.plot(finmag[:, 0], finmag[:, 3], "k", label="finmag m_z")
ax.set_xlim((0, 2))
ax.set_xlabel("time (ns)")
ax.legend()
plt.savefig("dynamics.png")
if __name__ == "__main__":
plot_dynamics()
| 2,305 | 31.478873 | 70 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/validation/finmag/run_validation.py
|
import os
import dolfin as df
import numpy as np
from math import pi, sin, cos
from finmag import Simulation as Sim
from finmag.energies import Exchange, UniaxialAnisotropy, Zeeman
from finmag.util.consts import mu0
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
averages_file = os.path.join(MODULE_DIR, "averages.txt")
def run_simulation():
L = W = 12.5e-9
H = 5e-9
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(L, W, H), 5, 5, 2)
sim = Sim(mesh, Ms=860e3, name="finmag_validation")
sim.set_m((1, 0.01, 0.01))
sim.alpha = 0.014
sim.gamma = 221017
H_app_mT = np.array([0.2, 0.2, 10.0])
H_app_SI = H_app_mT / (1000 * mu0)
sim.add(Zeeman(tuple(H_app_SI)))
sim.add(Exchange(1.3e-11))
sim.add(UniaxialAnisotropy(-1e5, (0, 0, 1)))
I = 5e-5 # current in A
J = I / (L * W) # current density in A/m^2
theta = 40.0 * pi / 180 # polarisation direction
phi = pi / 2
p = (sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta))
sim.set_stt(current_density=J, polarisation=0.4, thickness=H, direction=p)
sim.schedule("save_averages", every=5e-12)
sim.run_until(10e-9)
if __name__ == "__main__":
run_simulation()
| 1,205 | 28.414634 | 78 |
py
|
finmag
|
finmag-master/src/finmag/tests/slonczewski/validation/oommf/run.py
|
import os
import sys
import numpy as np
if not os.path.isfile("spinxfer-onespin.odt"):
print "Please run oommf on the run.mif file."
sys.exit(1)
oommf_data = np.loadtxt("spinxfer-onespin.odt")
dynamics = np.zeros((oommf_data.shape[0], 4))
dynamics[:, 0] = oommf_data[:, -1] # time
dynamics[:, 1:4] = oommf_data[:, -5:-2]
np.savetxt("averages_oommf.txt", dynamics, header="time mx my mz")
| 400 | 25.733333 | 66 |
py
|
finmag
|
finmag-master/src/finmag/tests/jacobean/test_jacobean_integration.py
|
# FinMag - a thin layer on top of FEniCS to enable micromagnetic multi-physics simulations
# Copyright (C) 2012 University of Southampton
# Do not distribute
#
# CONTACT: [email protected]
#
# AUTHOR(S) OF THIS FILE: Dmitri Chernyshenko ([email protected])
import numpy as np
import scipy.integrate
import unittest
from domain_wall_cobalt import setup_domain_wall_cobalt, domain_wall_error
from finmag.native import sundials
from finmag.util.ode import scipy_to_cvode_rhs
from datetime import datetime
NODE_COUNT = 100
END_TIME = 1e-10
class JacobeanIntegrationTests(unittest.TestCase):
def setUp(self):
self.n_rhs_evals = 0
def scipy_rhs(self, t, y):
self.n_rhs_evals += 1
return self.llg.solve_for(y, t)
def run_scipy_test(self, method):
self.llg = setup_domain_wall_cobalt(node_count=NODE_COUNT)
integrator = scipy.integrate.ode(self.scipy_rhs)
integrator.set_integrator(
"vode", method=method, atol=1e-8, rtol=1e-8, nsteps=40000)
integrator.set_initial_value(self.llg.m_numpy)
t = datetime.now()
ys = integrator.integrate(END_TIME)
dt = datetime.now() - t
print "scipy integration: method=%s, n_rhs_evals=%d, error=%g, elapsed time=%s" % (method, self.n_rhs_evals, domain_wall_error(ys, NODE_COUNT), dt)
def test_scipy_bdf(self):
self.run_scipy_test("bdf")
def test_scipy_adams(self):
self.run_scipy_test("adams")
def run_sundials_test_no_jacobean(self, method):
self.llg = setup_domain_wall_cobalt(node_count=NODE_COUNT)
if method == "bdf":
integrator = sundials.cvode(sundials.CV_BDF, sundials.CV_NEWTON)
else:
assert method == "adams"
integrator = sundials.cvode(
sundials.CV_ADAMS, sundials.CV_FUNCTIONAL)
integrator.init(
scipy_to_cvode_rhs(self.scipy_rhs), 0, self.llg.m_numpy.copy())
if method == "bdf":
integrator.set_linear_solver_diag()
integrator.set_scalar_tolerances(1e-8, 1e-8)
integrator.set_max_num_steps(40000)
ys = np.zeros(self.llg.m_numpy.shape)
t = datetime.now()
integrator.advance_time(END_TIME, ys)
dt = datetime.now() - t
print "sundials integration, no jacobean (%s, diagonal): n_rhs_evals=%d, error=%g, elapsed time=%s" % (method, self.n_rhs_evals, domain_wall_error(ys, NODE_COUNT), dt)
def test_sundials_diag_bdf(self):
self.run_sundials_test_no_jacobean("bdf")
def test_sundials_diag_adams(self):
self.run_sundials_test_no_jacobean("adams")
def test_sundials_test_with_jacobean(self):
self.llg = setup_domain_wall_cobalt(node_count=NODE_COUNT)
integrator = sundials.cvode(sundials.CV_BDF, sundials.CV_NEWTON)
integrator.init(
scipy_to_cvode_rhs(self.scipy_rhs), 0, self.llg.m_numpy.copy())
integrator.set_linear_solver_sp_gmr(sundials.PREC_NONE)
integrator.set_spils_jac_times_vec_fn(self.llg.sundials_jtimes)
integrator.set_scalar_tolerances(1e-8, 1e-8)
integrator.set_max_num_steps(40000)
ys = np.zeros(self.llg.m_numpy.shape)
t = datetime.now()
integrator.advance_time(END_TIME, ys)
dt = datetime.now() - t
print "sundials integration, with jacobean: n_rhs_evals=%d, error=%g, elapsed time=%s" % (self.n_rhs_evals, domain_wall_error(ys, NODE_COUNT), dt)
if __name__ == '__main__':
unittest.main()
| 3,514 | 37.626374 | 175 |
py
|
finmag
|
finmag-master/src/finmag/tests/jacobean/domain_wall_cobalt.py
|
import numpy as np
import dolfin as df
import math
from finmag.physics.llg import LLG
from finmag.drivers.llg_integrator import llg_integrator
from finmag.energies import Exchange, UniaxialAnisotropy
# Material parameters
Ms_Co = 1400e3 # A/m
K1_Co = 520e3 # A/m
A_Co = 30e-12 # J/m
LENGTH = 100e-9
NODE_COUNT = 100
# Initial m
def initial_m(xi, node_count):
mz = 1. - 2. * xi / (node_count - 1)
my = math.sqrt(1 - mz * mz)
return [0, my, mz]
# Analytical solution for the relaxed mz
def reference_mz(x):
return math.cos(math.pi / 2 + math.atan(math.sinh((x - LENGTH / 2) / math.sqrt(A_Co / K1_Co))))
def setup_domain_wall_cobalt(node_count=NODE_COUNT, A=A_Co, Ms=Ms_Co, K1=K1_Co, length=LENGTH, do_precession=True):
mesh = df.IntervalMesh(node_count - 1, 0, length)
S1 = df.FunctionSpace(mesh, "Lagrange", 1)
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
llg = LLG(S1, S3)
llg.set_m(np.array([initial_m(xi, node_count)
for xi in xrange(node_count)]).T.reshape((-1,)))
exchange = Exchange(A)
llg.effective_field.add(exchange)
anis = UniaxialAnisotropy(K1, (0, 0, 1))
llg.effective_field.add(anis)
llg.pins = [0, node_count - 1]
return llg
def domain_wall_error(ys, node_count):
m = ys.view()
m.shape = (3, -1)
return np.max(np.abs(m[2] - [reference_mz(x) for x in np.linspace(0, LENGTH, node_count)]))
def compute_domain_wall_cobalt(end_time=1e-9):
llg = setup_domain_wall_cobalt()
integrator = llg_integrator(llg, llg.m_field)
integrator.advance_time(end_time)
return np.linspace(0, LENGTH, NODE_COUNT), llg.m.reshape((3, -1))
if __name__ == '__main__':
import matplotlib.pyplot as plt
xs, m = compute_domain_wall_cobalt()
print "max difference between simulation and reference: ", domain_wall_error(m, NODE_COUNT)
xs = np.linspace(0, LENGTH, NODE_COUNT)
plt.plot(xs, np.transpose([m[2], [reference_mz(x) for x in xs]]), label=[
'Simulation', 'Reference'])
plt.xlabel('x [m]')
plt.ylabel('m')
plt.title('Domain wall in Co')
plt.show()
| 2,127 | 28.971831 | 115 |
py
|
finmag
|
finmag-master/src/finmag/tests/jacobean/test_jacobean_computation.py
|
import numpy as np
import unittest
from domain_wall_cobalt import setup_domain_wall_cobalt
def norm(a):
return np.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2])
# Set up the LLG with all parameters close to 1
def setup_llg_params_near_one(node_count=5, A=3.6 * 4e-7 * np.pi, Ms=6.7e5, K1=4.3, do_precession=True):
llg = setup_domain_wall_cobalt(
node_count=node_count, A=A, Ms=Ms, K1=K1, length=1.3, do_precession=do_precession)
llg.c = 1.23
llg.gamma = 1.56
llg.set_alpha(2.35)
llg.pins = []
n = llg.m_numpy.size / 3
# Generate a random (non-normalised) magnetisation vector with norm close
# to 1
np.random.seed(1)
m = np.random.rand(3, n) * 2 - 1
m = 0.1 * m + 0.9 * (m / norm(m))
m.shape = (-1,)
return llg, m
class JacobeanComputationTests(unittest.TestCase):
# Use 4th order FD scheme
# Without demag, this scheme should produce an exact result hence set eps
# to 1
def compute_jacobean_fd(self, m, eps=1):
n = self.llg.m_numpy.size / 3
# Compute the jacobean using the finite difference approximation
jac = np.zeros((3 * n, 3 * n))
w = np.array([1. / 12., -2. / 3., 2. / 3., -1. / 12.]) / eps
for j, v in enumerate(np.eye(3 * n)):
f0 = self.llg.solve_for(m - 2 * eps * v, 0)
f1 = self.llg.solve_for(m - eps * v, 0)
f2 = self.llg.solve_for(m + eps * v, 0)
f3 = self.llg.solve_for(m + 2 * eps * v, 0)
jac[:, j] = w[0] * f0 + w[1] * f1 + w[2] * f2 + w[3] * f3
return jac
# Use the jtimes function to compute the jacobean
def compute_jacobean_jtimes(self, m):
n = self.llg.m_numpy.size / 3
jac = np.zeros((3 * n, 3 * n))
tmp = np.zeros(m.shape)
jtimes = np.zeros(m.shape)
for j, v in enumerate(np.eye(3 * n)):
# use fy=None since it's not used for the computation
self.assertGreaterEqual(
self.llg.sundials_jtimes(v, jtimes, 0., m, None, tmp), 0)
jac[:, j] = jtimes
return jac
def test_compute_fd(self):
self.llg, m = setup_llg_params_near_one()
# Jacobean computation should be exact with eps=1 or eps=2
self.assertLess(np.max(np.abs(self.compute_jacobean_fd(
m, eps=1) - self.compute_jacobean_fd(m, eps=2))), 1e-13)
def test_compute_jtimes(self):
self.llg, m = setup_llg_params_near_one()
self.assertLess(np.max(
np.abs(self.compute_jacobean_jtimes(m) - self.compute_jacobean_fd(m))), 1e-13)
def test_compute_jtimes_pinning(self):
self.llg, m = setup_llg_params_near_one()
self.llg.pins = [0, 3, 4]
self.assertLess(np.max(
np.abs(self.compute_jacobean_jtimes(m) - self.compute_jacobean_fd(m))), 1e-13)
def test_compute_jtimes_no_precession(self):
self.llg, m = setup_llg_params_near_one(do_precession=False)
self.assertLess(np.max(
np.abs(self.compute_jacobean_jtimes(m) - self.compute_jacobean_fd(m))), 1e-13)
if __name__ == "__main__":
unittest.main()
| 3,117 | 35.682353 | 104 |
py
|
finmag
|
finmag-master/src/finmag/tests/jacobean/__init__.py
| 0 | 0 | 0 |
py
|
|
finmag
|
finmag-master/src/finmag/tests/jacobean/test_native_llg.py
|
import numpy as np
import unittest
from finmag.native import llg as native_llg
from test_jacobean_computation import setup_llg_params_near_one
from finmag.util.time_counter import counter
class NativeLlgTests(unittest.TestCase):
def test_llg_performance(self):
# Unfortunately 100000 nodes is not enough to even fill the L3 cache
# TODO: Increase the number of nodes when this is fast enough
llg, m = setup_llg_params_near_one(node_count=200000)
# Calculate H_eff etc
llg.solve_for(m, 0)
# Profile the LLG computation using pyinstant
c = counter()
H_eff = llg.effective_field.H_eff.reshape((3, -1))
m.shape = (3, -1)
dmdt = np.zeros(m.shape)
while c.next():
native_llg.calc_llg_dmdt(m, H_eff, 0.0, dmdt, llg.pins, llg.gamma, llg.alpha.vector(
).array(), 0.1 / llg.c, llg.do_precession)
print "Computing dm/dt via native C++ code", c
if __name__ == "__main__":
unittest.main()
| 1,008 | 35.035714 | 96 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/exchange_3d/run_nmag.py
|
import nmag
from nmag import SI, every
from nsim.si_units.si import degrees_per_ns
# example 2 of the nmag documentation
# without demag but with external field
mat_Py = nmag.MagMaterial(
name="Py",
Ms=SI(0.86e6, "A/m"),
exchange_coupling=SI(13.0e-12, "J/m"),
llg_damping=0.1)
L = 30.0e-9
H = 10.0e-9
W = 10.0e-9
def m0(r):
mx = 2 * r[0] / L - 1
my = 2 * r[1] / W - 1
mz = 1
return [mx, my, mz]
sim = nmag.Simulation("bar", do_demag=False)
sim.load_mesh("bar.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9, "m"))
sim.set_H_ext([1, 0, 0], SI(0.43e6, "A/m"))
sim.set_m(m0)
sim.set_params(stopping_dm_dt=1 * degrees_per_ns,
ts_rel_tol=1e-6, ts_abs_tol=1e-6)
sim.relax(save=[('averages', every('time', SI(5e-11, "s")))])
| 773 | 22.454545 | 74 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/exchange_3d/run_dolfin.py
|
import os
import dolfin as df
from finmag import Simulation as Sim
from finmag.energies import Exchange, Zeeman
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def run_simulation():
L = 3e-8
W = 1e-8
H = 1e-8
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(L, W, H), 10, 4, 4)
Ms = 0.86e6 # A/m
A = 1.3e-11 # J/m
sim = Sim(mesh, Ms)
sim.set_m(("2*x[0]/L - 1", "2*x[1]/W - 1", "1"), L=3e-8, H=1e-8, W=1e-8)
sim.alpha = 0.1
sim.add(Zeeman((Ms / 2, 0, 0)))
sim.add(Exchange(A))
t = 0
dt = 1e-11
tmax = 1e-9 # s
fh = open(os.path.join(MODULE_DIR, "averages.txt"), "w")
while t <= tmax:
mx, my, mz = sim.m_average
fh.write(str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")
t += dt
sim.run_until(t)
fh.close()
if __name__ == "__main__":
run_simulation()
| 882 | 22.236842 | 79 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/exchange_3d/test_dynamics_3D.py
|
import os
import cProfile
import pstats
import pytest
import numpy as np
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
TOLERANCE = 8e-3
def setup_module(module):
import run_dolfin as s
s.run_simulation()
@pytest.mark.slow
def test_compare_averages():
ref = np.loadtxt(os.path.join(MODULE_DIR, "averages_ref.txt"))
computed = np.loadtxt(os.path.join(MODULE_DIR, "averages.txt"))
for i in range(len(computed)):
t_ref, mx_ref, my_ref, mz_ref = ref[i]
t, mx, my, mz = computed[i]
assert abs(mx - mx_ref) < TOLERANCE
assert abs(my - my_ref) < TOLERANCE
assert abs(mz - mz_ref) < TOLERANCE
if __name__ == "__main__":
def do_it():
import run_dolfin as s
s.run_simulation()
test_compare_averages()
cProfile.run("do_it()", "test_profile")
p = pstats.Stats("test_profile")
print "TOP10 Cumulative time:"
p.sort_stats("cumulative").print_stats(10)
print "TOP10 Time inside a function:"
p.sort_stats("time").print_stats(10)
| 1,042 | 25.075 | 67 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/exchange_1d/run_nmag.py
|
# One dimensional magnetic system studied using nsim
import numpy as np
import nmag
from nmag import SI
import nmeshlib.unidmesher as unidmesher
# Details about the layers and the mesh and the material
length = 20.0 # in nanometers
mesh_unit = SI(1e-9, "m") # mesh unit (1 nm)
layers = [(0.0, length)] # the mesh
discretization = 2.0 # discretization
# Initial magnetization
xfactor = float(SI("m") / (length * mesh_unit))
def m0(r):
x = max(0.0, min(1.0, r[0] * xfactor))
mx = 2.0 * x - 1.0
my = (1.0 - mx * mx) ** 0.5
return [mx, my, 0.0]
dx = 0.5 * float(discretization * mesh_unit / SI("m"))
xmin = dx
xmax = float(length * mesh_unit / SI("m")) - dx
def pin(r):
p = (1.0 if xmin <= r[0] <= xmax else 0.0)
return p
# Create the material
mat_Py = nmag.MagMaterial(name="Py",
Ms=SI(0.86e6, "A/m"),
exchange_coupling=SI(13.0e-12, "J/m"),
llg_gamma_G=SI(0.2211e6, "m/A s"),
llg_damping=SI(0.2),
llg_normalisationfactor=SI(0.001e12, "1/s"))
# Create the simulation object
sim = nmag.Simulation("1d", do_demag=False)
# Creates the mesh from the layer structure
mesh_file_name = '1d.nmesh'
mesh_lists = unidmesher.mesh_1d(layers, discretization)
unidmesher.write_mesh(mesh_lists, out=mesh_file_name)
# Load the mesh
sim.load_mesh(mesh_file_name, [("Py", mat_Py)], unit_length=mesh_unit)
sim.set_m(m0) # Set the initial magnetisation
sim.set_pinning(pin) # Set pinning
# Save the anisotropy field once at the beginning of the simulation
# for comparison with finmag
np.savetxt("exc_t0_ref.txt", sim.get_subfield("H_exch_Py"))
np.savetxt("m_t0_ref.txt", sim.get_subfield("m_Py"))
t = t0 = 0
t1 = 5e-10
dt = 1e-11 # s
fh = open("third_node_ref.txt", "w")
while t <= t1:
sim.save_data("fields")
m2x, m2y, m2z = sim.probe_subfield_siv("m_Py", [4e-9]) # third node
fh.write(str(t) + " " + str(m2x) + " " + str(m2y) + " " + str(m2z) + "\n")
t += dt
sim.advance_time(SI(t, "s"))
fh.close()
| 2,097 | 28.138889 | 78 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/exchange_1d/test_exchange_1d.py
|
import os
import numpy as np
import finmag.util.helpers as h
from dolfin import IntervalMesh
from finmag import Simulation as Sim
from finmag.energies import Exchange
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def setup_module(module=None):
# define the mesh
x_max = 20e-9 # m
simplexes = 10
mesh = IntervalMesh(simplexes, 0, x_max)
def m_gen(coords):
x = coords[0]
mx = min(1.0, 2.0 * x / x_max - 1.0)
my = np.sqrt(1.0 - mx ** 2)
mz = 0.0
return np.array([mx, my, mz])
Ms = 0.86e6
A = 1.3e-11
global sim
sim = Sim(mesh, Ms)
sim.alpha = 0.2
sim.set_m(m_gen)
sim.pins = [0, 10]
exchange = Exchange(A)
sim.add(exchange)
# Save H_exc and m at t0 for comparison with nmag
global H_exc_t0, m_t0
H_exc_t0 = exchange.compute_field()
m_t0 = sim.m
t = 0
t1 = 5e-10
dt = 1e-11
# s
av_f = open(os.path.join(MODULE_DIR, "averages.txt"), "w")
tn_f = open(os.path.join(MODULE_DIR, "third_node.txt"), "w")
global averages
averages = []
global third_node
third_node = []
while t <= t1:
mx, my, mz = sim.m_average
averages.append([t, mx, my, mz])
av_f.write(
str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")
mx, my, mz = h.components(sim.m)
m2x, m2y, m2z = mx[2], my[2], mz[2]
third_node.append([t, m2x, m2y, m2z])
tn_f.write(
str(t) + " " + str(m2x) + " " + str(m2y) + " " + str(m2z) + "\n")
t += dt
sim.run_until(t)
av_f.close()
tn_f.close()
def test_angles():
TOLERANCE = 5e-8
m = h.vectors(sim.m)
angles = np.array([h.angle(m[i], m[i + 1]) for i in xrange(len(m) - 1)])
max_diff = abs(angles.max() - angles.min())
mean_angle = np.mean(angles)
print "test_angles: max_difference= {}.".format(max_diff)
print "test_angles: mean= {}.".format(mean_angle)
assert max_diff < TOLERANCE
assert np.abs(mean_angle - np.pi / 10) < TOLERANCE
def test_averages():
TOLERANCE = 2e-3
"""
We compare absolute values here, because values which should be
exactly zero in the idealised physical experiment (z-components of the
magnetisation as well as the average of the x-component) are not numerically.
In nmag, these "zeros" have the order of magnitude 1e-8, whereas
in finmag, they are in the order of 1e-14 and less. The difference is
roughly 1e-8 and the relative difference (dividing by nmag) would be 1.
That's useless for comparing. Solutions:
1. compute the relative difference by dividing by the norm of the vector or
something like this. Meh...
2. Check for zeros instead of comparing with nmag. But then you couldn't
copy&paste the comparison code anymore.
3. Write this comment and compare absolute values. Note that the tolerance
reflects the difference beetween non-zero components.
"""
ref = np.loadtxt(os.path.join(MODULE_DIR, "averages_ref.txt"))
computed = np.array(averages)
dt = ref[:, 0] - computed[:, 0]
assert np.max(dt) < 1e-15, "Compare timesteps."
ref, computed = np.delete(ref, [0], 1), np.delete(computed, [0], 1)
diff = ref - computed
print "test_averages, max. difference per axis:"
print np.nanmax(np.abs(diff), axis=0)
assert np.nanmax(diff) < TOLERANCE
def test_third_node():
REL_TOLERANCE = 6e-3
ref = np.loadtxt(os.path.join(MODULE_DIR, "third_node_ref.txt"))
computed = np.array(third_node)
dt = ref[:, 0] - computed[:, 0]
assert np.max(dt) < 1e-15, "Compare timesteps."
ref, computed = np.delete(ref, [0], 1), np.delete(computed, [0], 1)
diff = ref - computed
rel_diff = np.abs(diff / ref)
print "test_third_node, max. difference per axis:"
print np.nanmax(np.abs(diff), axis=0)
print "test_third_node, max. relative difference per axis:"
max_diffs = np.nanmax(rel_diff, axis=0)
print max_diffs
assert max_diffs[0] < REL_TOLERANCE and max_diffs[1] < REL_TOLERANCE
def test_m_cross_H():
"""
compares m x H_exc at the beginning of the simulation.
"""
REL_TOLERANCE = 8e-8
m_ref = np.genfromtxt(os.path.join(MODULE_DIR, "m_t0_ref.txt"))
m_computed = h.vectors(m_t0)
assert m_ref.shape == m_computed.shape
H_ref = np.genfromtxt(os.path.join(MODULE_DIR, "exc_t0_ref.txt"))
H_computed = h.vectors(H_exc_t0)
assert H_ref.shape == H_computed.shape
assert m_ref.shape == H_ref.shape
m_cross_H_ref = np.cross(m_ref, H_ref)
m_cross_H_computed = np.cross(m_computed, H_computed)
diff = np.abs(m_cross_H_ref - m_cross_H_computed)
max_norm = max([h.norm(v) for v in m_cross_H_ref])
rel_diff = diff / max_norm
print "test_m_cross_H, max. relative difference per axis:"
print np.nanmax(rel_diff, axis=0)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == '__main__':
setup_module()
test_angles()
test_averages()
test_third_node()
test_m_cross_H()
| 5,058 | 28.074713 | 81 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/anisotropy_1d/run_nmag.py
|
# One dimensional magnetic system studied using nsim
import numpy as np
import nmag
from nmag import SI
import nmeshlib.unidmesher as unidmesher
# Details about the layers and the mesh and the material
length = 100.0 # in nanometers
mesh_unit = SI(1e-9, "m") # mesh unit (1 nm)
layers = [(0.0, length)] # the mesh
discretization = 2.0 # discretization
# Initial magnetization
xfactor = float(SI("m") / (length * mesh_unit))
def m0(r):
x = max(0.0, min(1.0, r[0] * xfactor))
mx = x
mz = 0.1
my = (1.0 - (mx * mx * 0.99 + mz * mz)) ** 0.5
return [mx, my, mz]
# Create the material
mat_Py = nmag.MagMaterial(name="Py",
Ms=SI(0.86e6, "A/m"),
exchange_coupling=SI(0, "J/m"), # disables exchange?
anisotropy=nmag.uniaxial_anisotropy(
axis=[0, 0, 1], K1=SI(520e3, "J/m^3")),
llg_gamma_G=SI(0.2211e6, "m/A s"),
llg_damping=SI(0.2),
llg_normalisationfactor=SI(0.001e12, "1/s"))
# Create the simulation object
sim = nmag.Simulation("1d", do_demag=False)
# Creates the mesh from the layer structure
mesh_file_name = '1d.nmesh'
mesh_lists = unidmesher.mesh_1d(layers, discretization)
unidmesher.write_mesh(mesh_lists, out=mesh_file_name)
# Load the mesh
sim.load_mesh(mesh_file_name, [("Py", mat_Py)], unit_length=mesh_unit)
# Set the initial magnetisation
sim.set_m(m0)
# Save the anisotropy field once at the beginning of the simulation
# for comparison with finmag
np.savetxt("anis_t0_ref.txt", sim.get_subfield("H_anis_Py"))
np.savetxt("m_t0_ref.txt", sim.get_subfield("m_Py"))
with open("third_node_ref.txt", "w") as fh:
t = t0 = 0
t1 = 3e-10
dt = 5e-12 # s
while t <= t1:
sim.save_data()
# Save magnetisation of third node for comparison with finmag
m2x, m2y, m2z = sim.probe_subfield_siv("m_Py", [4e-9])
fh.write(
str(t) + " " + str(m2x) + " " + str(m2y) + " " + str(m2z) + "\n")
t += dt
sim.advance_time(SI(t, "s"))
| 2,127 | 30.761194 | 79 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/anisotropy_1d/test_nmag_1d_anisotropy.py
|
import os
import numpy as np
import finmag.util.helpers as h
from finmag import Simulation as Sim
from finmag.energies import UniaxialAnisotropy
import dolfin
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
averages = []
third_node = []
# run the simulation
def setup_module(module=None):
x_max = 100e-9 # m
simplexes = 50
mesh = dolfin.IntervalMesh(simplexes, 0, x_max)
def m_gen(coords):
x = coords[0]
mx = min(1.0, x / x_max)
mz = 0.1
my = np.sqrt(1.0 - (0.99 * mx ** 2 + mz ** 2))
return np.array([mx, my, mz])
K1 = 520e3 # J/m^3
Ms = 0.86e6
sim = Sim(mesh, Ms)
sim.alpha = 0.2
sim.set_m(m_gen)
anis = UniaxialAnisotropy(K1, (0, 0, 1))
sim.add(anis)
# Save H_anis and m at t0 for comparison with nmag
global H_anis_t0, m_t0
H_anis_t0 = anis.compute_field()
m_t0 = sim.m
av_f = open(os.path.join(MODULE_DIR, "averages.txt"), "w")
tn_f = open(os.path.join(MODULE_DIR, "third_node.txt"), "w")
t = 0
t_max = 3e-10
dt = 5e-12
# s
while t <= t_max:
mx, my, mz = sim.m_average
averages.append([t, mx, my, mz])
av_f.write(
str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")
mx, my, mz = h.components(sim.m)
m2x, m2y, m2z = mx[2], my[2], mz[2]
third_node.append([t, m2x, m2y, m2z])
tn_f.write(
str(t) + " " + str(m2x) + " " + str(m2y) + " " + str(m2z) + "\n")
t += dt
sim.run_until(t)
av_f.close()
tn_f.close()
def test_averages():
REL_TOLERANCE = 9e-2
ref = np.loadtxt(os.path.join(MODULE_DIR, "averages_ref.txt"))
computed = np.array(averages)
dt = ref[:, 0] - computed[:, 0]
assert np.max(dt) < 1e-15, "Compare timesteps."
ref, computed = np.delete(ref, [0], 1), np.delete(computed, [0], 1)
diff = ref - computed
rel_diff = np.abs(diff / np.sqrt(ref[0] ** 2 + ref[1] ** 2 + ref[2] ** 2))
print "test_averages, max. relative difference per axis:"
print np.nanmax(rel_diff, axis=0)
rel_err = np.nanmax(rel_diff)
if rel_err > 1e-3:
print "nmag:\n", ref
print "finmag:\n", computed
assert rel_err < REL_TOLERANCE
def test_third_node():
REL_TOLERANCE = 3e-1
ref = np.loadtxt(os.path.join(MODULE_DIR, "third_node_ref.txt"))
computed = np.array(third_node)
dt = ref[:, 0] - computed[:, 0]
assert np.max(dt) < 1e-15, "Compare timesteps."
ref, computed = np.delete(ref, [0], 1), np.delete(computed, [0], 1)
diff = ref - computed
rel_diff = np.abs(diff / np.sqrt(ref[0] ** 2 + ref[1] ** 2 + ref[2] ** 2))
print "test_third_node: max. relative difference per axis:"
print np.nanmax(rel_diff, axis=0)
rel_err = np.nanmax(rel_diff)
if rel_err > 1e-3:
print "nmag:\n", ref
print "finmag:\n", computed
assert rel_err < REL_TOLERANCE
def test_m_cross_H():
"""
compares m x H_anis at the beginning of the simulation.
motivation: Hans on IRC, 13.04.2012 10:45
"""
REL_TOLERANCE = 7e-5
m_ref = np.genfromtxt(os.path.join(MODULE_DIR, "m_t0_ref.txt"))
m_computed = h.vectors(m_t0)
assert m_ref.shape == m_computed.shape
H_ref = np.genfromtxt(os.path.join(MODULE_DIR, "anis_t0_ref.txt"))
H_computed = h.vectors(H_anis_t0)
assert H_ref.shape == H_computed.shape
assert m_ref.shape == H_ref.shape
m_cross_H_ref = np.cross(m_ref, H_ref)
m_cross_H_computed = np.cross(m_computed, H_computed)
diff = np.abs(m_cross_H_ref - m_cross_H_computed)
max_norm = max([h.norm(v) for v in m_cross_H_ref])
rel_diff = diff / max_norm
print "test_m_cross_H: max rel diff=", np.max(rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == '__main__':
setup_module()
test_averages()
test_third_node()
test_m_cross_H()
| 3,900 | 25.719178 | 78 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/spinwaves/run_nmag.py
|
import nmag
from nmag import SI
import math
"""
periodic spinwaves example straight from nmag's documentation
http://nmag.soton.ac.uk/nmag/0.2/manual/html/example_periodic_spinwaves/doc.html
minus the periodic part...
"""
# define magnetic material
Py = nmag.MagMaterial(name="Py",
Ms=SI(1e6, "A/m"),
exchange_coupling=SI(13.0e-12, "J/m"),
llg_damping=SI(0.02, "")
)
# create simulation object
sim = nmag.Simulation("spinwaves", do_demag=False)
# load mesh
sim.load_mesh("film.nmesh", [("film", Py)], unit_length=SI(1e-9, "m"))
# function to set the magnetisation
def perturbed_magnetisation(pos):
x, y, z = pos
newx = x * 1e9
newy = y * 1e9
if 8 < newx < 14 and -3 < newy < 3:
# the magnetisation is twisted a bit
return [1.0, 5. * (math.cos(math.pi * ((newx - 11) / 6.))) ** 3 *
(math.cos(math.pi * (newy / 6.))) ** 3, 0.0]
else:
return [1.0, 0.0, 0.0]
# set initial magnetisation
sim.set_m(perturbed_magnetisation)
# let the system relax generating spin waves
s = SI("s")
from nsim.when import every, at
sim.relax(save=[('averages', every('time', 0.05e-12 * s) | at('convergence'))],
do=[('exit', at('time', 10e-12 * s))])
| 1,294 | 26.553191 | 80 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/spinwaves/test_spinwaves.py
|
import os
import cProfile
import pstats
import pytest
import numpy as np
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
TOLERANCE = 3e-4
def setup_module(module):
import run_finmag as f
f.run_simulation()
@pytest.mark.slow
def test_compare_averages():
ref = np.loadtxt(os.path.join(MODULE_DIR, "averages_ref.txt"))
computed = np.loadtxt(os.path.join(MODULE_DIR, "averages.txt"))
highest_diff = 0
for i in range(len(computed)):
t_ref, mx_ref, my_ref, mz_ref = ref[i]
t, mx, my, mz = computed[i]
dx = abs(mx - mx_ref)
dy = abs(my - my_ref)
dz = abs(mz - mz_ref)
d = max([dx, dy, dz])
if d > highest_diff:
highest_diff = d
assert d < TOLERANCE
print "Highest difference was {0}.".format(highest_diff)
if __name__ == "__main__":
def do_it():
import run_finmag as f
f.run_simulation()
test_compare_averages()
cProfile.run("do_it()", "test_profile")
p = pstats.Stats("test_profile")
print "TOP10 Cumulative time:"
p.sort_stats("cumulative").print_stats(10)
print "TOP10 Time inside a function:"
p.sort_stats("time").print_stats(10)
| 1,202 | 23.55102 | 67 |
py
|
finmag
|
finmag-master/src/finmag/tests/nmag/spinwaves/run_finmag.py
|
import os
from scipy.integrate import ode
from finmag.physics.llg import LLG
from finmag.energies import Exchange
import dolfin as df
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def run_simulation():
"""
Translation of the nmag code.
Mesh generated on the fly.
"""
x0 = 0
x1 = 15e-9
nx = 30
y0 = -4.5e-9
y1 = 4.5e-9
ny = 18
z0 = -0.1e-9
z1 = 0.1e-9
nz = 1
mesh = df.BoxMesh(df.Point(x0, y0, z0), df.Point(x1, y1, z1), nx, ny, nz)
S1 = df.FunctionSpace(mesh, "Lagrange", 1)
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
nb_nodes = len(mesh.coordinates())
llg = LLG(S1, S3)
llg.Ms = 1e6
llg.set_alpha(0.02)
exchange = Exchange(1.3e-11)
llg.effective_field.add(exchange)
llg.set_m(("1",
"5 * pow(cos(pi * (x[0] * pow(10, 9) - 11) / 6), 3) \
* pow(cos(pi * x[1] * pow(10, 9) / 6), 3)",
"0"))
m = llg.m_numpy
for i in xrange(nb_nodes):
x, y, z = mesh.coordinates()[i]
mx = 1
my = 0
mz = 0
if 8e-9 < x < 14e-9 and -3e-9 < y < 3e-9:
pass
else:
m[i] = mx
m[i + nb_nodes] = my
m[i + 2 * nb_nodes] = mz
llg.m_field.set_with_numpy_array_debug(m)
llg_wrap = lambda t, y: llg.solve_for(y, t)
t0 = 0
dt = 0.05e-12
t1 = 10e-12
r = ode(llg_wrap).set_integrator(
"vode", method="bdf", rtol=1e-5, atol=1e-5)
r.set_initial_value(llg.m_numpy, t0)
fh = open(os.path.join(MODULE_DIR, "averages.txt"), "w")
while r.successful() and r.t <= t1:
mx, my, mz = llg.m_average
fh.write(
str(r.t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")
r.integrate(r.t + dt)
fh.close()
if __name__ == "__main__":
run_simulation()
| 1,859 | 23.473684 | 77 |
py
|
finmag
|
finmag-master/src/finmag/tests/oommf/convergence_anis_oommf.py
|
import os
import dolfin as df
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from finmag.util.oommf.comparison import compare_anisotropy
from finmag.util.oommf import mesh
K1 = 45e4 # J/m^3
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
max_rdiffs = [[], []]
mean_rdiffs = [[], []]
vertices = [[], []]
x_max = 100e-9
def m_gen(rs):
xs = rs[0]
return np.array([xs / x_max, np.sqrt(1 - (xs / x_max) ** 2), np.zeros(len(xs))])
def test_1d():
print "1D problem..."
for x_n in [1e1, 1e2, 1e3, 1e4, 1e5, 1e6]:
dolfin_mesh = df.IntervalMesh(int(x_n), 0, x_max)
oommf_mesh = mesh.Mesh((int(x_n), 1, 1), size=(x_max, 1e-12, 1e-12))
res = compare_anisotropy(
m_gen, 1.0, K1, (1, 1, 1), dolfin_mesh, oommf_mesh, dims=1, name="1D")
vertices[0].append(dolfin_mesh.num_vertices())
mean_rdiffs[0].append(np.mean(res["rel_diff"]))
max_rdiffs[0].append(np.max(res["rel_diff"]))
def linear(x, a, b):
return a * x + b
xs = np.log(vertices[0])
ys = np.log(mean_rdiffs[0])
popt, pcov = curve_fit(linear, xs, ys)
assert popt[0] < - 1.0
if __name__ == '__main__':
test_1d()
plt.xlabel("number of vertices")
plt.ylabel("relative difference")
plt.loglog(vertices[0], mean_rdiffs[0], "b--")
plt.loglog(vertices[0], mean_rdiffs[0], "bo", label="average")
plt.loglog(vertices[0], max_rdiffs[0], "b-.")
plt.loglog(vertices[0], max_rdiffs[0], "bs", label="maximum")
plt.legend()
plt.savefig(os.path.join(MODULE_DIR, "anis_convergence.png"))
plt.show()
| 1,630 | 27.614035 | 84 |
py
|
finmag
|
finmag-master/src/finmag/tests/oommf/test_anisotropy.py
|
import dolfin as df
import numpy as np
from finmag.util.oommf import mesh
from finmag.util.oommf.comparison import compare_anisotropy
from finmag.util.helpers import stats
K1 = 45e4 # J/m^31
Ms = 0.86e6
def test_small_problem():
results = small_problem()
REL_TOLERANCE = 1e-15
print "0d: rel_diff_max:", np.nanmax(results["rel_diff"])
assert np.nanmax(results["rel_diff"]) < REL_TOLERANCE
def test_one_dimensional_problem():
results = one_dimensional_problem()
REL_TOLERANCE = 1e-9 # for 100,000 FE nodes, 6e-4 for 200 nodes
print "1d: rel_diff_max:", np.nanmax(results["rel_diff"])
assert np.nanmax(results["rel_diff"]) < REL_TOLERANCE
def test_three_dimensional_problem():
results = three_dimensional_problem()
REL_TOLERANCE = 9e-2
print "3d: rel_diff_max:", np.nanmax(results["rel_diff"])
assert np.nanmax(results["rel_diff"]) < REL_TOLERANCE
def small_problem():
# The oommf mesh corresponding to this problem only has a single cell.
x_max = 1e-9
y_max = 1e-9
z_max = 1e-9
dolfin_mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(x_max, y_max, z_max), 5, 5, 5)
oommf_mesh = mesh.Mesh((1, 1, 1), size=(x_max, y_max, z_max))
def m_gen(rs):
rn = len(rs[0])
return np.array([np.ones(rn), np.zeros(rn), np.zeros(rn)])
from finmag.util.oommf.comparison import compare_anisotropy
return compare_anisotropy(m_gen, Ms, K1, (1, 1, 1), dolfin_mesh, oommf_mesh, name="single")
def one_dimensional_problem():
x_min = 0
x_max = 100e-9
x_n = 100000
dolfin_mesh = df.IntervalMesh(x_n, x_min, x_max)
oommf_mesh = mesh.Mesh((20, 1, 1), size=(x_max, 1e-12, 1e-12))
def m_gen(rs):
xs = rs[0]
return np.array([xs / x_max, np.sqrt(1 - (xs / x_max) ** 2), np.zeros(len(xs))])
return compare_anisotropy(m_gen, Ms, K1, (1, 1, 1), dolfin_mesh, oommf_mesh, dims=1, name="1D")
def three_dimensional_problem():
x_max = 100e-9
y_max = z_max = 1e-9
x_n = 20
y_n = z_n = 1
dolfin_mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(x_max, y_max, z_max), x_n, y_n, z_n)
print dolfin_mesh.num_vertices()
oommf_mesh = mesh.Mesh((x_n, y_n, z_n), size=(x_max, y_max, z_max))
def m_gen(rs):
xs = rs[0]
return np.array([xs / x_max, np.sqrt(1 - (0.9 * xs / x_max) ** 2 - 0.01), 0.1 * np.ones(len(xs))])
from finmag.util.oommf.comparison import compare_anisotropy
return compare_anisotropy(m_gen, Ms, K1, (0, 0, 1), dolfin_mesh, oommf_mesh, dims=3, name="3D")
if __name__ == '__main__':
res0 = small_problem()
print "0D problem, relative difference:\n", stats(res0["rel_diff"])
res1 = one_dimensional_problem()
print "1D problem, relative difference:\n", stats(res1["rel_diff"])
res3 = three_dimensional_problem()
print "3D problem, relative difference:\n", stats(res3["rel_diff"])
| 2,883 | 32.149425 | 106 |
py
|
finmag
|
finmag-master/src/finmag/tests/oommf/test_exchange.py
|
import os
import numpy as np
import dolfin as df
import matplotlib.pyplot as plt
from finmag.util.helpers import stats
from finmag.util.oommf import mesh
from finmag.util.oommf.comparison import compare_exchange
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
Ms = 8.6e6
A = 1.3e-11
def test_one_dimensional_problem():
REL_TOLERANCE = 1e-3
results = one_dimensional_problem(5000)
assert np.nanmax(np.mean(results["rel_diff"], axis=1)) < REL_TOLERANCE
def one_dimensional_problem(vertices):
x_min = 0
x_max = 100e-9
dolfin_mesh = df.IntervalMesh(vertices, x_min, x_max)
oommf_mesh = mesh.Mesh((vertices, 1, 1), size=(x_max, 1e-12, 1e-12))
def m_gen(coords):
xs = coords[0]
return np.array([np.sqrt(xs / x_max), np.sqrt(1 - xs / x_max), np.zeros(len(xs))])
return compare_exchange(m_gen, Ms, A, dolfin_mesh, oommf_mesh, dims=1, name="1d")
if __name__ == '__main__':
vertices = []
mean_diffs = []
for n in [10, 1e2, 1e3, 1e4, 1e5]:
res = one_dimensional_problem(int(n))
print "1D problem ({} nodes) relative difference:".format(n)
print stats(res["rel_diff"])
vertices.append(int(n))
mean_diffs.append(np.nanmax(np.mean(res["rel_diff"], axis=1)))
plt.xlabel("vertices")
plt.ylabel("rel. mean diff.")
plt.loglog(vertices, mean_diffs, "--")
plt.loglog(vertices, mean_diffs, "o", label="1d problem")
plt.legend()
plt.savefig(os.path.join(MODULE_DIR, "exchange_convergence.png"))
| 1,521 | 28.843137 | 90 |
py
|
finmag
|
finmag-master/src/finmag/tests/energy_density/test_energy_density.py
|
import os
import sys
import pytest
import commands
import subprocess
import numpy as np
import dolfin as df
from finmag.field import Field
from finmag.energies import UniaxialAnisotropy, Exchange, Demag, DMI
from finmag.util.consts import mu0
from finmag.util.meshes import sphere
TOL = 1e-14
# TODO: We're missing the Zeeman energy density here!
@pytest.mark.skipif('subprocess.call(["which", "nsim"]) != 0')
def test_exchange_energy_density():
"""
Compare solution with nmag for now. Should derive the
analytical solution here as well.
Our initial magnetisation looks like this:
^ ~
| / ---> \ | (Hahahaha! :-D)
~ v
"""
TOL = 1e-7 # Should be lower when comparing with analytical solution
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
# run nmag
cmd = "nsim %s --clean" % os.path.join(MODULE_DIR, "run_nmag_Eexch.py")
status, output = commands.getstatusoutput(cmd)
if status != 0:
print output
sys.exit("Error %d: Running %s failed." % (status, cmd))
nmag_data = np.loadtxt(
os.path.join(MODULE_DIR, "nmag_exchange_energy_density.txt"))
# run finmag
mesh = df.IntervalMesh(100, 0, 10e-9)
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
Ms = 42
m = Field(S3, value=df.Expression(
("cos(x[0]*pi/10e-9)", "sin(x[0]*pi/10e-9)", "0"), degree=1))
exch = Exchange(1.3e-11)
Ms_field = Field(df.FunctionSpace(mesh, 'DG', 0), Ms)
exch.setup(m, Ms_field)
finmag_data = exch.energy_density()
rel_err = np.abs(nmag_data - finmag_data) / np.linalg.norm(nmag_data)
print ("Nmag data = %g" % nmag_data[0])
print ("Finmag data = %g" % finmag_data[0])
print "Relative error from nmag data (expect array of 0):"
print rel_err
print "Max relative error:", np.max(rel_err)
assert np.max(rel_err) < TOL, \
"Max relative error is %g, should be zero." % np.max(rel_err)
print("Work out average energy density and energy")
S1 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=1)
# only approximative -- using assemble would be better
average_energy_density = np.average(finmag_data)
w = df.TestFunction(S1)
vol = sum(df.assemble(df.dot(df.Constant([1]), w) * df.dx))
# finmag 'manually' computed, based on node values of energy density:
energy1 = average_energy_density * vol
# finmag computed by energy class
energy2 = exch.compute_energy()
# comparison with Nmag
energy3 = np.average(nmag_data) * vol
print energy1, energy2, energy3
assert abs(energy1 - energy2) < 1e-12 # actual value is 0, but
# that must be pure luck.
assert abs(energy1 - energy3) < 5e-8 # actual value
# is 1.05e-8, 30 June 2012
def test_anisotropy_energy_density():
"""
Written in sperical coordinates, the equation for the
anisotropy energy density reads
E/V = K*sin^2(theta),
where theta is the angle between the magnetisation and
the easy axis. With a magnetisation pointing 45 degrees
between the x- and z-axis, and using the z-axis as the
easy axis, theta becomes pi/4. sin^2(pi/4) evaluates
to 1/2, and with K set to 1 in this simple test case,
we expect the energy density to be 1/2 at every node.
"""
# 5 simplices between 0 and 1 nm.
mesh = df.IntervalMesh(5, 0, 1e-9)
V = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
# Initial magnetisation 45 degress between x- and z-axis.
m_vec = df.Constant((1 / np.sqrt(2), 0, 1 / np.sqrt(2)))
m = Field(V, value=m_vec)
# Easy axis in z-direction.
a = df.Constant((0, 0, 1))
# These are 1 just to simplify the analytical solution.
K = 1
Ms = 1
anis = UniaxialAnisotropy(K, a)
anis.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms))
density = anis.energy_density()
deviation = np.abs(density - 0.5)
print "Anisotropy energy density (expect array of 0.5):"
print density
print "Max deviation: %g" % np.max(deviation)
assert np.all(deviation < TOL), \
"Max deviation %g, should be zero." % np.max(deviation)
def test_DMI_energy_density_2D():
"""
For a vector field (x, y, z) = 0.5 * (-y, x, c),
the curl is exactly 1.0. (HF)
"""
mesh = df.UnitSquareMesh(4, 4)
V = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
M = Field(V, value=df.Expression(("-0.5*x[1]", "0.5*x[0]", "1"), degree=1))
Ms = 1
D = 1
dmi = DMI(D)
dmi.setup(M, Field(df.FunctionSpace(mesh, 'DG', 0), Ms))
density = dmi.energy_density()
deviation = np.abs(density - 1.0)
print "2D energy density (expect array of 1):"
print density
print "Max deviation: %g" % np.max(deviation)
assert np.all(deviation < TOL), \
"Max deviation %g, should be zero." % np.max(deviation)
def test_DMI_energy_density_3D():
"""Same as above, on a 3D mesh."""
mesh = df.UnitCubeMesh(4, 4, 4)
V = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
M = Field(V, df.Expression(("-0.5*x[1]", "0.5*x[0]", "1"), degree=1))
Ms = 10
D = 1
dmi = DMI(D)
dmi.setup(M, Field(df.FunctionSpace(mesh, 'DG', 0), Ms))
density = dmi.energy_density()
deviation = np.abs(density - 1.0)
print "3D energy density (expect array of 1):"
print density
print "Max deviation: %g" % np.max(deviation)
assert np.all(deviation < TOL), \
"Max deviation %g, should be zero." % np.max(deviation)
def test_demag_energy_density():
"""
With a sphere mesh, unit magnetisation in x-direction,
we expect the demag energy to be
E = 1/6 * mu0 * Ms^2 * V.
(See section about demag solvers in the documentation
for how this is found.)
To make it simple, we define Ms = sqrt(6/mu0).
Energy density is then
E/V = 1.
"""
TOL = 5e-2
mesh = sphere(r=1.0, maxh=0.2)
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1)
mu0 = 4 * np.pi * 1e-7
demag = Demag()
m = Field(S3, value=(1, 0, 0))
Ms = np.sqrt(6.0 / mu0)
demag.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms), 1)
density = demag.energy_density()
deviation = np.abs(density - 1.0)
print "Demag energy density (expect array of 1s):"
print density
print "Max deviation:", np.max(deviation)
assert np.max(deviation) < TOL, \
"Max deviation is %g, should be zero." % np.max(deviation)
if __name__ == '__main__':
test_exchange_energy_density()
sys.exit(0)
test_demag_energy_density()
test_exchange_energy_density()
test_anisotropy_energy_density()
test_DMI_energy_density_2D()
test_DMI_energy_density_3D()
| 6,682 | 29.797235 | 79 |
py
|
finmag
|
finmag-master/src/finmag/tests/energy_density/run_nmag_Eexch.py
|
import os
import numpy as np
import nmag
from nmag import SI
import nmeshlib.unidmesher as unidmesher
L = 10
mesh_unit = SI(1e-9, "m") # mesh unit (1 nm)
layers = [(0.0, L)] # the mesh
discretization = 0.1 # discretization
# Initial magnetization
xfactor = float(SI("m") / (L * mesh_unit))
def m0(r):
return [np.cos(r[0] * np.pi * xfactor), np.sin(r[0] * np.pi * xfactor), 0]
mat_Py = nmag.MagMaterial(name="Py",
Ms=SI(42, "A/m"))
sim = nmag.Simulation("Hans' configuration", do_demag=False)
mesh_file_name = '1d.nmesh'
mesh_lists = unidmesher.mesh_1d(layers, discretization)
unidmesher.write_mesh(mesh_lists, out=mesh_file_name)
sim.load_mesh(mesh_file_name,
[("Py", mat_Py)],
unit_length=mesh_unit)
sim.set_m(m0)
mod_dir = os.path.dirname(os.path.abspath(__file__))
np.savetxt(os.path.join(mod_dir, "nmag_exchange_energy_density.txt"),
sim.get_subfield("E_exch_Py"))
| 964 | 25.805556 | 78 |
py
|
finmag
|
finmag-master/src/finmag/tests/bugs/test_bug_ndt_file_writing.py
|
import pytest
# coding: utf-8
# Saving spatially averaged magnetisation into a file
# Bug 8 June 2014. On some machines, we seem to have wrong data in the
# ndt file. Some inspection shows that there are too many columns in
# the ndt file.
# We didn't have a test for this, it was only caught by chance (Max
# looking at a plot in a notebook plotting the curves). Max writes:
#
# Quick update for tonight: fortunately this doesn't seem to be
# very serious. Increasing the number of points to be plotted
# shows that it is always only the very first data point that is
# off. So it seems that this is an issue with .ndt saving where
# the first value is somehow not correctly updated.
#
# I just did a bisection of the history (version control and
# bisect FTW! :)) and the commit which introduced this buglet is
# 30145c2f9595 ("ndt file now saves max dmdt norm"). However, I
# can't see offhand why that changeset would introduce the
# bug. Anyway, off to sleep now. Just thought I'd send this
# update. Once someone finds the cause of the bug we should also
# add a regression test (it's a bit strange that this hasn't been
# picked up by our existing tests).
#
#
# Note that there is an additional Ipython notebook file for this bug
# that is convenient for experimentation.
def test_ndt_writing_pretest():
import finmag
# In[4]:
sim = finmag.example.barmini(name='bug-saving-average-data-june-2014')
# What is the current magnetisation? We expect it to be $ \vec{m}
# = [\sqrt(2), 0, \sqrt(2)]$ as this is the initial value in the
# barmini example.
# In[5]:
import math
m = sim.get_field_as_dolfin_function('m')
points = [[0, 0, 0], [1, 0, 0], [2, 0, 0], [0, 0, 5], [1, 1, 2],
[3, 3, 10]]
for point in points:
print("m({}) = {}".format(point, m(point)))
assert (m(point)[0] - math.sqrt(2)) < 1e-15
assert (m(point)[1] - 0) < 1e-15
assert (m(point)[2] - math.sqrt(2)) < 1e-15
# now we know for sure what data we are writing.
def number_of_columns_in_ndt_file_consistent(ndtfile):
lines = open(ndtfile).readlines()
headers = lines[0][1:].split() # string of leading hash in first line
n = len(headers)
print("Found {} headers: = {}".format(n, headers))
# skip line 1 which contains the units
for i in range(2, len(lines)):
print("Found {} columns in line {}.".format(len(lines[i].split()), i))
print("Printed the length to show all the data, now we test each line")
for i in range(2, len(lines)):
assert(len(lines[i].split()) == n)
def test_ndt_writing_correct_number_of_columns_1line():
# Here we write only one line to the ndt file
import finmag
sim = finmag.example.barmini(name='bug-saving-average-data-june-2014-a')
sim.save_averages()
# The first line contains the title for every column, the second
# line the (SI) units in which the entity is measured, and the
# third and any other lines contain the actual data.
# Check that all lines in this data file have the right number of
# entries (columns)
number_of_columns_in_ndt_file_consistent(
'bug_saving_average_data_june_2014_a.ndt')
#@pytest.mark.xfail
def test_ndt_writing_correct_number_of_columns_2_and_more_lines():
# Here we write multiple lines to the ndt file
import finmag
# In[4]:
sim = finmag.example.barmini(name='bug-saving-average-data-june-2014-b')
sim.save_averages()
# and write some more data
sim.schedule("save_ndt", every=10e-12)
sim.run_until(0.1e-9)
# The first line contains the title for every column, the second
# line the (SI) units in which the entity is measured, and the
# third and any other lines contain the actual data.
# Check that all lines in this data file have the right number of
# entries (columns)
number_of_columns_in_ndt_file_consistent(
'bug_saving_average_data_june_2014_b.ndt')
def check_magnetisation_is_of_sensible_magnitude(ndtfile):
import finmag
data = finmag.util.fileio.Tablereader(ndtfile)
mx, my, mz = data['m_x', 'm_y', 'm_z']
print("Found {} saved steps.".format(len(mx)))
assert len(mx) == len(my) == len(mz)
# magnetisation should be normalised, so cannot exceed 1
for m_x, m_y, m_z in zip(mx, my, mz):
assert abs(m_x) <= 1, "m_x = {}".format(m_x)
assert abs(m_y) <= 1, "m_x = {}".format(m_x)
assert abs(m_z) <= 1, "m_x = {}".format(m_x)
def test_ndt_writing_order_of_magnitude_m_1line():
# Here we write only one line to the ndt file
import finmag
sim = finmag.example.barmini(name='bug-saving-average-data-june-2014-c')
sim.save_averages()
check_magnetisation_is_of_sensible_magnitude(
'bug_saving_average_data_june_2014_c.ndt')
#@pytest.mark.xfail
def test_ndt_writing_order_of_magnitude_m_2_and_more_lines():
# Here we write multiple lines to the ndt file
import finmag
sim = finmag.example.barmini(name='bug-saving-average-data-june-2014-d')
sim.save_averages()
sim.schedule("save_ndt", every=10e-12)
sim.run_until(0.1e-9)
check_magnetisation_is_of_sensible_magnitude(
'bug_saving_average_data_june_2014_d.ndt')
| 5,316 | 30.64881 | 78 |
py
|
finmag
|
finmag-master/src/finmag/tests/bugs/segfault-paraview/nobug-2.py
|
from paraview import servermanager
import dolfin as df
| 56 | 13.25 | 34 |
py
|
finmag
|
finmag-master/src/finmag/tests/bugs/segfault-paraview/bug-1.py
|
import paraview
import dolfin as df
import finmag
| 50 | 11.75 | 19 |
py
|
finmag
|
finmag-master/src/finmag/tests/bugs/segfault-paraview/bug-2.py
|
import dolfin as df
from paraview import servermanager
| 55 | 17.666667 | 34 |
py
|
finmag
|
finmag-master/src/finmag/tests/cython/test_cython.py
|
""" This is a bit of an odd test: it checks that a work-around for a
particular cython problem is still working. More meant to document
a solution rather than test cython, but can't do much harm.
HF 1 Feb 2013
"""
import subprocess
import os
# Cython complains about this:
# f_callable_normalised = vector_valued_function(lambda (x,y,z): (a*x, b*y, c*z), S3, normalise=True)
# try to reproduce with a simple example
def myfunc(callable):
print callable((0, 1, 2))
print callable((10, 10, 10))
def cython_test_code():
a, b, c = 1, 1, 1
x, y, z = 1, 1, 1
# cython complains about this
#myfunc(lambda (x, y, z): (a * x, b * y, c * z))
# but this one works:
myfunc(lambda t: (a * t[0], b * t[1], c * t[1]))
# and so does this:
def myf(tup):
x, y, z = tup
return (a * x, b * y, c * z)
myfunc(myf)
def test_cython_compiles_this_file():
cmd = "cython {}".format(os.path.abspath(__file__))
print("about to execute {}".format(cmd))
subprocess.check_call(cmd, shell=True)
if __name__ == '__main__':
test_cython_compiles_this_file()
| 1,116 | 21.795918 | 102 |
py
|
finmag
|
finmag-master/src/finmag/tests/zhangli/stt_nonlocal_test.py
|
import os
import dolfin as df
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from finmag import Simulation as Sim
from finmag.energies import Exchange, UniaxialAnisotropy
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def sech(x):
return 1 / np.cosh(x)
def init_m(pos):
x = pos[0]
delta = np.sqrt(13e-12 / 520e3) * 1e9
sx = -np.tanh((x - 50) / delta)
sy = sech((x - 50) / delta)
return (sx, sy, 0)
def init_J(pos):
return (1e12, 0, 0)
def test_zhangli():
#mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(100, 1, 1), 50, 1, 1)
mesh = df.IntervalMesh(50, 0, 100)
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9, kernel='llg_stt')
sim.set_m(init_m)
sim.add(UniaxialAnisotropy(K1=520e3, axis=[1, 0, 0]))
sim.add(Exchange(A=13e-12))
sim.alpha = 0.01
sim.llg.set_parameters(J_profile=init_J, speedup=50)
p0 = sim.m_average
sim.run_until(5e-12)
p1 = sim.m_average
print sim.integrator.stats()
print p0, p1
sim.run_until(1e-11)
p1 = sim.m_average
print sim.integrator.stats()
print p0, p1
assert p1[0] < p0[0]
assert abs(p0[0]) < 1e-15
assert abs(p1[0]) > 1e-3
if __name__ == "__main__":
test_zhangli()
| 1,274 | 18.921875 | 72 |
py
|
finmag
|
finmag-master/src/finmag/tests/zhangli/standard.py
|
import os
import dolfin as df
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from finmag import Simulation as Sim
from finmag.energies import Exchange, Demag
from finmag.util.fileio import Tablereader
from finmag.util.meshes import from_geofile, mesh_info
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def init_m(pos):
x0 = 50
y0 = 50
r = 10
x, y, z = pos
fx, fy, fz = y0 - y, x - x0, r
R = np.sqrt(fx ** 2 + fy ** 2 + fz ** 2)
return (fx, fy, fz) / R
def init_J(pos):
return (1e12, 0, 0)
def relax_system(mesh):
sim = Sim(mesh, Ms=8.0e5, unit_length=1e-9)
sim.gamma = 2.211e5
sim.alpha = 1
sim.add(Exchange(A=13e-12))
sim.add(Demag())
sim.set_m(init_m)
sim.relax(stopping_dmdt=0.01)
np.save('m0.npy', sim.m)
df.plot(sim._m)
# df.interactive()
def spin_length(sim):
spin = sim.m
spin.shape = (3, -1)
length = np.sqrt(np.sum(spin ** 2, axis=0))
spin.shape = (-1,)
print sim.t, np.max(length), np.min(length)
def with_current(mesh):
sim = Sim(mesh, Ms=8.0e5, unit_length=1e-9, name='stt')
sim.gamma = 2.211e5
sim.alpha = 0.1
sim.set_m(np.load('m0.npy'))
sim.add(Exchange(A=13e-12))
sim.add(Demag())
sim.set_zhangli(init_J, 1.0, 0.05)
sim.schedule('save_ndt', every=5e-11)
#sim.schedule('save_vtk', every=5e-11)
sim.schedule(spin_length, every=5e-11)
sim.run_until(8e-9)
df.plot(sim._m)
# df.interactive()
def plot_data():
data = Tablereader('stt.ndt')
ts = data['time']
fig = plt.figure()
ms = 8.0e5 / 1e6
plt.plot(ts * 1e9, data['m_x'] * ms, '.-', label='m_x')
plt.plot(ts * 1e9, data['m_y'] * ms, '+-', label='m_y')
plt.plot(ts * 1e9, data['m_z'] * ms, '-', label='m_z')
plt.xlim([0, 5])
plt.ylim([-0.3, 0.2])
plt.xlabel('Time (ns)')
plt.ylabel('Average Magnetisation ($10^6$A/m)')
plt.gray()
plt.legend()
fig.savefig('averaged_m.pdf')
if __name__ == "__main__":
#mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(100, 100, 10), 40, 40, 2)
mesh = from_geofile('thinfilm100.geo')
print mesh_info(mesh)
# relax_system(mesh)
with_current(mesh)
plot_data()
| 2,260 | 19.935185 | 76 |
py
|
finmag
|
finmag-master/src/finmag/tests/zhangli/zhang_li_test.py
|
import pytest
import os
import dolfin as df
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from finmag import Simulation as Sim
from finmag.energies import Exchange, UniaxialAnisotropy
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def sech(x):
return 1 / np.cosh(x)
def init_m(pos):
x = pos[0]
delta = np.sqrt(13e-12 / 520e3) * 1e9
sx = -np.tanh((x - 50) / delta)
sy = sech((x - 50) / delta)
return (sx, sy, 0)
def field_at(pos):
delta = np.sqrt(13e-12 / 520e3) * 1e9
x = (pos[0] - 50) / delta
fx = -sech(x) ** 2 / delta * 1e9
fy = -np.tanh(x) * sech(x) / delta * 1e9
return (fx, fy, 0)
def init_J(pos):
return (1e12, 0, 0)
def test_zhangli():
#mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(100, 1, 1), 50, 1, 1)
mesh = df.IntervalMesh(50, 0, 100)
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)
sim.set_m(init_m)
sim.add(UniaxialAnisotropy(K1=520e3, axis=[1, 0, 0]))
sim.add(Exchange(A=13e-12))
sim.alpha = 0.01
sim.set_zhangli(init_J, 0.5, 0.02)
p0 = sim.m_average
sim.run_until(2e-12)
p1 = sim.m_average
# print p0,p1
assert p1[0] < p0[0]
assert abs(p0[0]) < 1e-15
assert abs(p1[0]) > 1e-3
def test_zhangli_sllg():
#mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(100, 1, 1), 50, 1, 1)
mesh = df.IntervalMesh(50, 0, 100)
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9, kernel='sllg')
sim.set_m(init_m)
sim.add(UniaxialAnisotropy(K1=520e3, axis=[1, 0, 0]))
sim.add(Exchange(A=13e-12))
sim.alpha = 0.01
sim.set_zhangli(init_J, 0.5, 0.02)
p0 = sim.m_average
sim.run_until(2e-12)
p1 = sim.m_average
# print p0,p1
assert p1[0] < p0[0]
assert abs(p0[0]) < 1e-15
assert abs(p1[0]) > 1e-3
# the result got by llg is -1.310956e-3
assert abs(p1[0] + 1.310956e-3) < 1e-8
def init_J_x(pos):
return (1, 0, 0)
def compare_gradient_field1():
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(100, 1, 1), 50, 1, 1)
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)
sim.set_m(init_m)
sim.set_zhangli(init_J_x, 0.5, 0.01)
coords = mesh.coordinates()
field = sim.llg.compute_gradient_field()
v = df.Function(sim.S3)
v.vector().set_local(field)
f2 = field.copy()
f2.shape = (3, -1)
print f2
i = 0
for c in coords:
print c, field_at(c)
f2[0][i], f2[1][i], f2[2][i] = field_at(c)
i += 1
f2.shape = (-1,)
v2 = df.Function(sim.S3)
v2.vector().set_local(f2)
df.plot(v)
df.plot(v2)
df.interactive()
print field
def init_J_xy(pos):
return (1, 2, 0)
def init_m2(pos):
x, y = pos[0], pos[1]
sx = np.sin(x) * np.cos(y)
sy = np.sqrt(1 - sx ** 2)
return (sx, sy, 0)
def field_at2(pos):
x, y = pos[0], pos[1]
jx = 1
jy = 2
mx = np.sin(x) * np.cos(y)
my = np.sqrt(1 - mx ** 2)
mx_x = np.cos(x) * np.cos(y)
mx_y = -np.sin(x) * np.sin(y)
my_x = -0.5 * np.sin(2 * x) * np.cos(y) ** 2 / my
my_y = 0.5 * np.sin(x) ** 2 * np.sin(2 * y) / my
fx = jx * mx_x + jy * mx_y
fy = jx * my_x + jy * my_y
return (fx, fy, 0)
def compare_gradient_field2():
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(np.pi / 2, np.pi / 2, 1), 20, 20, 1)
sim = Sim(mesh, Ms=8.6e5, unit_length=1)
sim.set_m(init_m2)
sim.set_zhangli(init_J_xy, 0.5, 0.01)
coords = mesh.coordinates()
field = sim.llg.compute_gradient_field()
v = df.Function(sim.S3)
v.vector().set_local(field)
f2 = field.copy()
f2.shape = (3, -1)
i = 0
for c in coords:
tx, ty, tz = field_at2(c)
f2[0][i], f2[1][i], f2[2][i] = field_at2(c)
i += 1
f2.shape = (-1,)
v2 = df.Function(sim.S3)
v2.vector().set_local(f2)
df.plot(v)
df.plot(v2)
print np.abs(field - f2)
print f2
df.interactive()
if __name__ == "__main__":
test_zhangli()
test_zhangli_sllg()
# compare_gradient_field1()
# compare_gradient_field2()
| 4,080 | 19.103448 | 86 |
py
|
finmag
|
finmag-master/src/finmag/tests/demag/compute_demag_sphere.py
|
from test_bem_computation import compute_scalar_potential_native_fk
from finmag.util.meshes import sphere
import numpy as np
from mayavi import mlab
# Create the mesh and compute the scalar potential
mesh = sphere(r=1.0, maxh=0.1)
phi = compute_scalar_potential_native_fk(mesh)
x, y, z = mesh.coordinates().T
values = phi.vector().array()
# Set up the visualisation
figure = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
# Use unconnected datapoints and scalar_scatter and interpolate using a
# delaunay mesh
src = mlab.pipeline.scalar_scatter(x, y, z, values)
field = mlab.pipeline.delaunay3d(src)
# Make the contour plot
contours = np.linspace(np.min(values), np.max(values), 10)
mlab.pipeline.iso_surface(field, contours=list(contours))
mlab.show()
| 760 | 30.708333 | 71 |
py
|
finmag
|
finmag-master/src/finmag/tests/demag/__init__.py
| 0 | 0 | 0 |
py
|
|
finmag
|
finmag-master/src/finmag/tests/demag/test_demag_sphere.py
|
import pytest
import numpy as np
import dolfin as df
from finmag.field import Field
from finmag.util.meshes import sphere
from finmag.energies import Demag
TOL = 1e-2
solvers = ['FK']
@pytest.fixture(scope="module")
def uniformly_magnetised_sphere():
Ms = 1
mesh = sphere(r=1, maxh=0.25)
S3 = df.VectorFunctionSpace(mesh, "CG", 1)
m = Field(S3)
m.set(df.Constant((1, 0, 0)))
solutions = []
for solver in solvers:
demag = Demag(solver)
demag.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms), unit_length=1e-9)
demag.H = demag.compute_field()
solutions.append(demag)
return solutions
def test_H_demag(uniformly_magnetised_sphere):
for solution in uniformly_magnetised_sphere:
H = solution.H.reshape((3, -1)).mean(1)
H_expected = np.array([-1.0 / 3.0, 0, 0])
print "{}: Hx = {}, should be {}.".format(
solution.__class__.__name__, H, H_expected)
diff = np.max(np.abs(H - H_expected))
assert diff < TOL
def test_H_demag_deviation(uniformly_magnetised_sphere):
for solution in uniformly_magnetised_sphere:
H = solution.H.reshape((3, -1))
delta = np.max(np.abs(H.max(axis=1) - H.min(axis=1)))
assert delta < TOL
if __name__ == "__main__":
uniformly_magnetised_sphere()
| 1,328 | 26.6875 | 84 |
py
|
finmag
|
finmag-master/src/finmag/tests/demag/test_bem_computation.py
|
import os
import pytest
import unittest
import numpy as np
import dolfin as df
from finmag.field import Field
from finmag.util.versions import get_version_dolfin
from finmag.native.llg import compute_lindholm_L, compute_lindholm_K, compute_bem_fk, compute_bem_gcr
from finmag.util import time_counter
from finmag.util import helpers
from finmag.util.meshes import mesh_volume, sphere
from finmag.energies.demag import belement_magpar
from finmag.energies.demag import belement
from finmag.tests.test_solid_angle_invariance import random_3d_rotation_matrix
from finmag.energies import Demag
compute_belement = belement_magpar.return_bele_magpar()
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
class MagSphereBase(object):
"""Base class for MagSphere classes"""
def __init__(self, maxh, radius=10):
self.mesh = sphere(radius, maxh, directory=MODULE_DIR)
self.Ms = 1.0
self.m = (str(self.Ms), "0.0", "0.0")
self.M = self.m # do we need this?
self.V = df.VectorFunctionSpace(self.mesh, "CG", 1)
self.m = df.interpolate(df.Expression(self.m, degree=1), self.V)
self.r = radius
self.maxh = maxh
def desc(self):
return "Sphere demag test problem, Ms=%g, radius=%g, maxh=%g" % (self.Ms, self.r, self.maxh)
def compute_belement_magpar(r1, r2, r3):
res = np.zeros(3)
compute_belement(np.zeros(3), np.array(r1, dtype=float), np.array(
r2, dtype=float), np.array(r3, dtype=float), res)
return res
def normalise_phi(phi, mesh):
volume = mesh_volume(mesh)
average = df.assemble(phi * df.dx)
phi.vector()[:] = phi.vector().array() - average / volume
def compute_scalar_potential_llg(mesh, m_expr=df.Constant([1, 0, 0]), Ms=1.):
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
m = Field(S3, value=m_expr)
m.set_with_numpy_array_debug(helpers.fnormalise(m.get_numpy_array_debug()))
demag = Demag()
demag.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms), unit_length=1)
phi = demag.compute_potential()
normalise_phi(phi, mesh)
return phi
# Computes the derivative f'(x) using the finite difference approximation
def differentiate_fd(f, x, eps=1e-4, offsets=(-2, -1, 1, 2), weights=(1. / 12., -2. / 3., 2. / 3., -1. / 12.)):
return sum(f(x + eps * dx) * weights[i] for i, dx in enumerate(offsets)) / eps
def compute_scalar_potential_native_fk(mesh, m_expr=df.Constant([1, 0, 0]), Ms=1.):
fkdemag = Demag("FK")
V = df.VectorFunctionSpace(mesh, "Lagrange", 1)
m = Field(V, value=m_expr)
m.set_with_numpy_array_debug(helpers.fnormalise(m.get_numpy_array_debug()))
fkdemag.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms), unit_length=1)
phi1 = fkdemag.compute_potential()
normalise_phi(phi1, mesh)
return phi1
# Solves the demag problem for phi using the GCR method and the native BEM
# matrix
def compute_scalar_potential_native_gcr(mesh, m_expr=df.Constant([1, 0, 0]), Ms=1.0):
gcrdemag = Demag("GCR")
V = df.VectorFunctionSpace(mesh, "Lagrange", 1)
m = Field(V, value=m_expr)
m.set_with_numpy_array_debug(helpers.fnormalise(m.get_numpy_array_debug()))
gcrdemag.setup(m, Ms, unit_length=1)
phi1 = gcrdemag.compute_potential()
normalise_phi(phi1, mesh)
return phi1
class BemComputationTests(unittest.TestCase):
def test_simple(self):
r1 = np.array([1., 0., 0.])
r2 = np.array([2., 1., 3.])
r3 = np.array([5., 0., 1.])
be_magpar = compute_belement_magpar(r1, r2, r3)
be_native = compute_lindholm_L(np.zeros(3), r1, r2, r3)
print "Magpar: ", be_magpar
print "Native C++: ", be_native
self.assertAlmostEqual(
np.max(np.abs(be_magpar - be_native)), 0, delta=1e-12)
def test_cell_ordering(self):
mesh = df.UnitCubeMesh(1, 1, 1)
centre = np.array([0.5, 0.5, 0.5])
boundary_mesh = df.BoundaryMesh(mesh, 'exterior', False)
coordinates = boundary_mesh.coordinates()
for i in xrange(boundary_mesh.num_cells()):
cell = df.Cell(boundary_mesh, i)
p1 = coordinates[cell.entities(0)[0]]
p2 = coordinates[cell.entities(0)[1]]
p3 = coordinates[cell.entities(0)[2]]
n = np.cross(p2 - p1, p3 - p1)
print "Boundary face %d, normal orientation %g" % (i, np.sign(np.dot(n, p1 - centre)))
def run_bem_computation_test(self, mesh):
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
m = df.interpolate(df.Constant((1, 0, 0)), S3)
Ms = 1.0
bem_magpar, g2finmag = belement.BEM_matrix(mesh)
bem_finmag = np.zeros(bem_magpar.shape)
bem, b2g = compute_bem_fk(df.BoundaryMesh(mesh, 'exterior', False))
for i_dolfin in xrange(bem.shape[0]):
i_finmag = g2finmag[b2g[i_dolfin]]
for j_dolfin in xrange(bem.shape[0]):
j_finmag = g2finmag[b2g[j_dolfin]]
bem_finmag[i_finmag, j_finmag] = bem[i_dolfin, j_dolfin]
if np.max(np.abs(bem_finmag - bem_magpar)) > 1e-12:
print "Finmag:", np.round(bem_finmag, 4)
print "Magpar:", np.round(bem_magpar, 4)
print "Difference:", np.round(bem_magpar - bem_finmag, 4)
self.fail(
"Finmag and magpar computation of BEM differ, mesh: " + str(mesh))
def test_bem_computation(self):
self.run_bem_computation_test(sphere(1., 0.8))
self.run_bem_computation_test(sphere(1., 0.4))
self.run_bem_computation_test(sphere(1., 0.3))
self.run_bem_computation_test(sphere(1., 0.2))
self.run_bem_computation_test(df.UnitCubeMesh(3, 3, 3))
def test_bem_perf(self):
mesh = df.UnitCubeMesh(15, 15, 15)
boundary_mesh = df.BoundaryMesh(mesh, 'exterior', False)
c = time_counter.counter()
while c.next():
df.BoundaryMesh(mesh, 'exterior', False)
print "Boundary mesh computation for %s: %s" % (mesh, c)
c = time_counter.counter()
while c.next():
bem, _ = compute_bem_fk(boundary_mesh)
n = bem.shape[0]
print "FK BEM computation for %dx%d (%.2f Mnodes/sec): %s" % (n, n, c.calls_per_sec(n * n / 1e6), c)
c = time_counter.counter()
while c.next():
bem, _ = compute_bem_gcr(boundary_mesh)
print "GCR BEM computation for %dx%d (%.2f Mnodes/sec): %s" % (n, n, c.calls_per_sec(n * n / 1e6), c)
def test_bem_netgen(self):
module_dir = os.path.dirname(os.path.abspath(__file__))
netgen_mesh = df.Mesh(
os.path.join(module_dir, "bem_netgen_test_mesh.xml.gz"))
bem, b2g_map = compute_bem_fk(
df.BoundaryMesh(netgen_mesh, 'exterior', False))
def run_demag_computation_test(self, mesh, m_expr, compute_func, method_name, tol=1e-10, ref=compute_scalar_potential_llg, k=0):
phi_a = ref(mesh, m_expr)
phi_b = compute_func(mesh, m_expr)
error = df.errornorm(phi_a, phi_b, mesh=mesh)
message = "Method: %s, mesh: %s, m: %s, error: %8g" % (
method_name, mesh, m_expr, error)
print message
print "K = ", k
print "m_expr = ", m_expr
self.assertAlmostEqual(
error, 0, delta=tol, msg="Error is above threshold %g, %s" % (tol, message))
def test_compute_scalar_potential_fk(self):
m1 = df.Constant([1, 0, 0])
m2 = df.Expression(["x[0]*x[1]+3", "x[2]+5", "x[1]+7"], degree=1)
expressions = [m1, m2]
for exp in expressions:
for k in xrange(1, 5 + 1):
self.run_demag_computation_test(df.UnitCubeMesh(k, k, k), exp,
compute_scalar_potential_native_fk,
"native, FK", k=k)
self.run_demag_computation_test(sphere(1., 1. / k), exp,
compute_scalar_potential_native_fk,
"native, FK", k=k)
self.run_demag_computation_test(MagSphereBase(0.25, 1).mesh, exp,
compute_scalar_potential_native_fk,
"native, FK", k=k)
@pytest.mark.skipif("get_version_dolfin()[:3] != '1.0'")
def test_compute_scalar_potential_gcr(self):
m1 = df.Constant([1, 0, 0])
m2 = df.Expression(["x[0]*x[1]+3", "x[2]+5", "x[1]+7"], degree=1)
tol = 1e-1
expressions = [m1, m2]
self.run_demag_computation_test(MagSphereBase(0.1, 1.).mesh, m1,
compute_scalar_potential_native_gcr,
"native, GCR",
ref=compute_scalar_potential_native_fk, tol=tol)
for exp in expressions:
for k in xrange(3, 10 + 1, 2):
self.run_demag_computation_test(df.UnitCubeMesh(k, k, k), exp,
compute_scalar_potential_native_gcr,
"native, GCR, cube", tol=tol,
ref=compute_scalar_potential_native_fk)
self.run_demag_computation_test(MagSphereBase(1. / k, 1.).mesh, exp,
compute_scalar_potential_native_gcr,
"native, GCR, sphere", tol=tol,
ref=compute_scalar_potential_native_fk, k=k)
def run_symmetry_test(self, formula):
func = globals()[formula]
np.random.seed(1)
for i in xrange(100):
r = np.random.rand(3) * 2 - 1
r1 = np.random.rand(3) * 2 - 1
r2 = np.random.rand(3) * 2 - 1
r3 = np.random.rand(3) * 2 - 1
a = np.random.rand(3) * 2 - 1
b = random_3d_rotation_matrix(1)[0]
# Compute the formula
v1 = func(r, r1, r2, r3)
# The formula is invariant under rotations via b
v2 = func(
np.dot(b, r), np.dot(b, r1), np.dot(b, r2), np.dot(b, r3))
self.assertAlmostEqual(np.max(np.abs(v1 - v2)), 0)
# and under translations via a
v3 = func(r + a, r1 + a, r2 + a, r3 + a)
self.assertAlmostEqual(np.max(np.abs(v1 - v3)), 0)
# and under permutations of r1-r2-r3
v4 = func(r, r2, r3, r1)
self.assertAlmostEqual(np.max(np.abs(v1[[1, 2, 0]] - v4)), 0)
def test_lindholm_L_symmetry(self):
# Lindholm formulas should be invariant under rotations and
# translations
self.run_symmetry_test("compute_lindholm_L")
def test_lindholm_K_symmetry(self):
self.run_symmetry_test("compute_lindholm_K")
def test_lindholm_derivative(self):
# the double layer potential is the derivative of the single layer potential
# with respect to displacements of the triangle in the normal direction
np.random.seed(1)
for i in xrange(100):
r = np.random.rand(3) * 2 - 1
r1 = np.random.rand(3) * 2 - 1
r2 = np.random.rand(3) * 2 - 1
r3 = np.random.rand(3) * 2 - 1
zeta = np.cross(r2 - r1, r3 - r1)
zeta /= np.linalg.norm(zeta)
def f(x):
return compute_lindholm_K(r, r1 + x * zeta, r2 + x * zeta, r3 + x * zeta)
L1 = compute_lindholm_L(r, r1, r2, r3)
L2 = differentiate_fd(f, 0)
self.assertAlmostEqual(np.max(np.abs(L1 - L2)), 0, delta=1e-10)
def test_facet_normal_direction(self):
mesh = df.UnitCubeMesh(1, 1, 1)
field = df.Expression(["x[0]", "x[1]", "x[2]"], degree=1)
n = df.FacetNormal(mesh)
# Divergence of R is 3, the volume of the unit cube is 1 so we divide
# by 3
print "Normal: +1=outward, -1=inward:", df.assemble(df.dot(field, n) * df.ds) / 3.
if __name__ == "__main__":
unittest.main()
| 12,113 | 41.356643 | 132 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/test_dmdt.py
|
import dolfin as df
import numpy as np
from finmag.physics.llg import LLG
from finmag.energies import Zeeman
from finmag.util.oommf import mesh, oommf_dmdt
from finmag.util.helpers import stats
TOLERANCE = 1e-15
L = 20e-9
W = 10e-9
H = 1e-9
nL = 20
nW = 10
nH = 1
msh = df.BoxMesh(df.Point(0, 0, 0), df.Point(L, W, H), nL, nW, nH)
S1 = df.FunctionSpace(msh, "Lagrange", 1)
S3 = df.VectorFunctionSpace(msh, "Lagrange", 1)
def test_dmdt_computation_with_oommf():
# set up finmag
llg = LLG(S1, S3)
llg.set_m((-3, -2, 1))
Ms = llg.Ms.vector().array()[0]
Ms = float(Ms)
h = Ms / 2
H_app = (h / np.sqrt(3), h / np.sqrt(3), h / np.sqrt(3))
zeeman = Zeeman(H_app)
zeeman.setup(llg.m_field, llg.Ms, 1)
llg.effective_field.add(zeeman)
dmdt_finmag = df.Function(llg.S3)
dmdt_finmag.vector()[:] = llg.solve(0)
# set up oommf
msh = mesh.Mesh((nL, nW, nH), size=(L, W, H))
m0 = msh.new_field(3)
m0.flat[0] += -3
m0.flat[1] += -2
m0.flat[2] += 1
m0.flat /= np.sqrt(m0.flat[0] * m0.flat[0] +
m0.flat[1] * m0.flat[1] + m0.flat[2] * m0.flat[2])
dmdt_oommf = oommf_dmdt(
m0, Ms, A=0, H=H_app, alpha=0.5, gamma_G=llg.gamma).flat
# extract finmag data for comparison with oommf
dmdt_finmag_like_oommf = msh.new_field(3)
for i, (x, y, z) in enumerate(msh.iter_coords()):
dmdt_x, dmdt_y, dmdt_z = dmdt_finmag(x, y, z)
dmdt_finmag_like_oommf.flat[0, i] = dmdt_x
dmdt_finmag_like_oommf.flat[1, i] = dmdt_y
dmdt_finmag_like_oommf.flat[2, i] = dmdt_z
# compare
difference = np.abs(dmdt_finmag_like_oommf.flat - dmdt_oommf)
relative_difference = difference / np.max(np.sqrt(dmdt_oommf[0] ** 2 +
dmdt_oommf[1] ** 2 + dmdt_oommf[2] ** 2))
print "comparison with oommf, dm/dt, relative difference:"
print stats(relative_difference)
assert np.max(relative_difference) < TOLERANCE
return difference, relative_difference
if __name__ == '__main__':
test_dmdt_computation_with_oommf()
| 2,102 | 29.478261 | 95 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/exchange/run_nmag.py
|
# One dimensional magnetic system studied using nsim
import math
import numpy as np
import nmag
from nmag import SI
import nmeshlib.unidmesher as unidmesher
# Details about the layers and the mesh and the material
length = 20.0 # in nanometers
mesh_unit = SI(1e-9, "m") # mesh unit (1 nm)
layers = [(0.0, length)] # the mesh
discretization = 2.0 # discretization
# Initial magnetization
xfactor = float(SI("m") / (length * mesh_unit))
def m0(r):
x = max(0.0, min(1.0, r[0] * xfactor))
mx = (2.0 * x - 1.0) * 2.0 / 3.0
mz = math.sin(2 * math.pi * x) / 2
my = (1.0 - mx * mx - mz * mz) ** 0.5
return [mx, my, mz]
# Create the material
mat_Py = nmag.MagMaterial(name="Py",
Ms=SI(0.86e6, "A/m"),
exchange_coupling=SI(13.0e-12, "J/m"),
llg_gamma_G=SI(0.2211e6, "m/A s"),
llg_damping=SI(0.2),
llg_normalisationfactor=SI(0.001e12, "1/s"))
# Create the simulation object
sim = nmag.Simulation("1d", do_demag=False)
# Creates the mesh from the layer structure
mesh_file_name = '1d.nmesh'
mesh_lists = unidmesher.mesh_1d(layers, discretization)
unidmesher.write_mesh(mesh_lists, out=mesh_file_name)
# Load the mesh
sim.load_mesh(mesh_file_name, [("Py", mat_Py)], unit_length=mesh_unit)
sim.set_m(m0) # Set the initial magnetisation
# Save the exchange field and the magnetisation once at the beginning
# of the simulation for comparison with finmag
np.savetxt("H_exc_nmag.txt", sim.get_subfield("H_exch_Py"))
np.savetxt("m0_nmag.txt", sim.get_subfield("m_Py"))
| 1,637 | 31.76 | 70 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/exchange/test_exchange_compare_magpar.py
|
import os
import dolfin as df
import numpy as np
from finmag.field import Field
from finmag.util import magpar
from finmag.energies import Exchange
from finmag.util.helpers import vector_valued_function
#df.parameters["allow_extrapolation"] = True
# REL_TOLERANCE = 3e-6 #passes with 'normal magpar'
REL_TOLERANCE = 9e-8 # needs higher accuracy patch
# for saved files to pass
# install magpar via finmag/install/magpar.sh to get this.
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def test_three_dimensional_problem():
results = three_dimensional_problem()
assert np.nanmax(results["rel_diff"]) < REL_TOLERANCE
def three_dimensional_problem():
x_max = 10e-9
y_max = 1e-9
z_max = 1e-9
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(x_max, y_max, z_max), 40, 2, 2)
V = df.VectorFunctionSpace(mesh, 'Lagrange', 1)
Ms = 8.6e5
m0_x = "pow(sin(0.2*x[0]*1e9), 2)"
m0_y = "0"
m0_z = "pow(cos(0.2*x[0]*1e9), 2)"
m = Field(V, value=vector_valued_function(
(m0_x, m0_y, m0_z), V, normalise=True))
C = 1.3e-11
u_exch = Exchange(C)
u_exch.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms))
finmag_exch = u_exch.compute_field()
magpar_result = os.path.join(MODULE_DIR, 'magpar_result', 'test_exch')
nodes, magpar_exch = magpar.get_field(magpar_result, 'exch')
## Uncomment the line below to invoke magpar to compute the results,
## rather than using our previously saved results.
# nodes, magpar_exch = magpar.compute_exch_magpar(m, A=C, Ms=Ms)
print magpar_exch
# Because magpar have changed the order of the nodes!!!
tmp = df.Function(V)
tmp_c = mesh.coordinates()
mesh.coordinates()[:] = tmp_c * 1e9
finmag_exch, magpar_exch, \
diff, rel_diff = magpar.compare_field(
mesh.coordinates(), finmag_exch,
nodes, magpar_exch)
return dict(m0=m.get_numpy_array_debug(),
mesh=mesh,
exch=finmag_exch,
magpar_exch=magpar_exch,
diff=diff,
rel_diff=rel_diff)
if __name__ == '__main__':
res = three_dimensional_problem()
print "finmag:", res["exch"]
print "magpar:", res["magpar_exch"]
print "rel_diff:", res["rel_diff"]
print "max rel_diff", np.max(res["rel_diff"])
| 2,332 | 26.77381 | 81 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/exchange/test_exchange_field.py
|
import os
import dolfin as df
import numpy as np
from finmag.field import Field
from finmag.energies import Exchange
from finmag.util.helpers import vectors, norm, stats, sphinx_sci as s
import pytest
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
x0 = 0
x1 = 20e-9
xn = 10
Ms = 0.86e6
A = 1.3e-11
table_delim = " " + "=" * 10 + (" " + "=" * 30) * 4 + "\n"
table_entries = " {:<10} {:<30} {:<30} {:<30} {:<30}\n"
def m_gen(r):
x = np.maximum(np.minimum(r[0] / x1, 1.0), 0.0)
mx = (2 * x - 1) * 2 / 3
mz = np.sin(2 * np.pi * x) / 2
my = np.sqrt(1.0 - mx ** 2 - mz ** 2)
return np.array([mx, my, mz])
def start_table():
table = ".. _exchange_table:\n\n"
table += ".. table:: Comparison of the exchange field computed with finmag against nmag and oommf\n\n"
table += table_delim
table += table_entries.format(
# hack because sphinx light table syntax does not allow an empty header
":math:`\,`",
":math:`\\subn{\\Delta}{test}`",
":math:`\\subn{\\Delta}{max}`",
":math:`\\bar{\\Delta}`",
":math:`\\sigma`")
table += table_delim
return table
def setup_finmag():
mesh = df.IntervalMesh(xn, x0, x1)
coords = np.array(zip(* mesh.coordinates()))
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
m = Field(S3)
m.set_with_numpy_array_debug(m_gen(coords).flatten())
exchange = Exchange(A)
exchange.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms))
H_exc = df.Function(S3)
H_exc.vector()[:] = exchange.compute_field()
return dict(m=m, H=H_exc, table=start_table())
def teardown_finmag(finmag):
finmag["table"] += table_delim
with open(os.path.join(MODULE_DIR, "table.rst"), "w") as f:
f.write(finmag["table"])
@pytest.fixture
def finmag(request):
finmag = request.cached_setup(setup=setup_finmag,
teardown=teardown_finmag, scope="module")
return finmag
def test_against_nmag(finmag):
REL_TOLERANCE = 2e-14
m_ref = np.genfromtxt(os.path.join(MODULE_DIR, "m0_nmag.txt"))
m_computed = vectors(finmag["m"].get_numpy_array_debug())
assert m_ref.shape == m_computed.shape
H_ref = np.genfromtxt(os.path.join(MODULE_DIR, "H_exc_nmag.txt"))
H_computed = vectors(finmag["H"].vector().array())
assert H_ref.shape == H_computed.shape
assert m_ref.shape == H_ref.shape
m_cross_H_ref = np.cross(m_ref, H_ref)
m_cross_H_computed = np.cross(m_computed, H_computed)
diff = np.abs(m_cross_H_ref - m_cross_H_computed)
rel_diff = diff / max([norm(v) for v in m_cross_H_ref])
finmag["table"] += table_entries.format(
"nmag", s(REL_TOLERANCE, 0), s(np.max(rel_diff)), s(np.mean(rel_diff)), s(np.std(rel_diff)))
print "comparison with nmag, m x H, relative difference:"
print stats(rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
def test_against_oommf(finmag):
REL_TOLERANCE = 8e-2
from finmag.util.oommf import mesh, oommf_uniform_exchange
from finmag.util.oommf.comparison import oommf_m0, finmag_to_oommf
oommf_mesh = mesh.Mesh((xn, 1, 1), size=(x1, 1e-12, 1e-12))
oommf_exc = oommf_uniform_exchange(oommf_m0(m_gen, oommf_mesh), Ms, A).flat
finmag_exc = finmag_to_oommf(finmag["H"], oommf_mesh, dims=1)
assert oommf_exc.shape == finmag_exc.shape
diff = np.abs(oommf_exc - finmag_exc)
rel_diff = diff / \
np.sqrt(
np.max(oommf_exc[0] ** 2 + oommf_exc[1] ** 2 + oommf_exc[2] ** 2))
finmag["table"] += table_entries.format(
"oommf", s(REL_TOLERANCE, 0), s(np.max(rel_diff)), s(np.mean(rel_diff)), s(np.std(rel_diff)))
print "comparison with oommf, H, relative_difference:"
print stats(rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == '__main__':
f = setup_finmag()
test_against_nmag(f)
test_against_oommf(f)
teardown_finmag(f)
| 3,924 | 30.150794 | 106 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/run_nmag.py
|
import nmag
import numpy as np
from nmag import SI, at
Ms = 0.86e6
K1 = 520e3
a = (1, 0, 0)
x1 = y1 = z1 = 20
# same as in bar.geo file
def m_gen(r):
x = np.maximum(np.minimum(r[0] / x1, 1.0), 0.0) # x, y and z as a fraction
y = np.maximum(np.minimum(r[1] / y1, 1.0), 0.0) # between 0 and 1 in the
z = np.maximum(np.minimum(r[2] / z1, 1.0), 0.0)
mx = (2 - y) * (2 * x - 1) / 4
mz = (2 - y) * (2 * z - 1) / 4
my = np.sqrt(1 - mx ** 2 - mz ** 2)
return np.array([mx, my, mz])
def generate_anisotropy_data(anis, name='anis'):
# Create the material
mat_Py = nmag.MagMaterial(name="Py",
Ms=SI(Ms, "A/m"),
anisotropy=anis)
# Create the simulation object
sim = nmag.Simulation(name, do_demag=False)
# Load the mesh
sim.load_mesh("bar.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9, "m"))
# Set the initial magnetisation
sim.set_m(lambda r: m_gen(np.array(r) * 1e9))
#sim.advance_time(SI(1e-12, 's') )
# Save the exchange field and the magnetisation once at the beginning
# of the simulation for comparison with finmag
np.savetxt("H_%s_nmag.txt" % name, sim.get_subfield("H_anis_Py"))
np.savetxt("m0_nmag.txt", sim.get_subfield("m_Py"))
if __name__ == "__main__":
# define uniaxial_anisotropy
anis = nmag.uniaxial_anisotropy(
axis=[1, 0, 0], K1=SI(520e3, "J/m^3"), K2=SI(230e3, "J/m^3"))
generate_anisotropy_data(anis)
cubic = nmag.cubic_anisotropy(axis1=[1, 0, 0], axis2=[0, 1, 0],
K1=SI(520e3, "J/m^3"),
K2=SI(230e3, "J/m^3"),
K3=SI(123e3, "J/m^3"))
generate_anisotropy_data(cubic, name='cubic_anis')
| 1,781 | 31.4 | 79 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/conftest.py
|
import os
import numpy as np
import dolfin as df
from finmag.field import Field
from finmag.util.meshes import from_geofile
from finmag.energies import UniaxialAnisotropy, CubicAnisotropy
from finmag.util.helpers import sphinx_sci as s
import pytest
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def finmag(request):
finmag = request.cached_setup(setup=setup,
teardown=teardown, scope="session")
return finmag
Ms = 0.86e6
K1 = 520e3
K2 = 230e3
K3 = 123e3
u1 = (1, 0, 0)
u2 = (0, 1, 0)
x1 = y1 = z1 = 20
# same as in bar.geo file
def m_gen(r):
x = np.maximum(np.minimum(r[0] / x1, 1.0), 0.0) # x, y and z as a fraction
y = np.maximum(np.minimum(r[1] / y1, 1.0), 0.0) # between 0 and 1 in the
z = np.maximum(np.minimum(r[2] / z1, 1.0), 0.0)
mx = (2 - y) * (2 * x - 1) / 4
mz = (2 - y) * (2 * z - 1) / 4
my = np.sqrt(1 - mx ** 2 - mz ** 2)
return np.array([mx, my, mz])
def setup(K2=K2):
print "Running finmag..."
mesh = from_geofile(os.path.join(MODULE_DIR, "bar.geo"))
coords = np.array(zip(* mesh.coordinates()))
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
m = Field(S3)
m.set_with_numpy_array_debug(m_gen(coords).flatten())
S1 = df.FunctionSpace(mesh, "Lagrange", 1)
Ms_cg = Field(df.FunctionSpace(mesh, 'CG', 1), Ms)
anisotropy = UniaxialAnisotropy(K1, u1, K2=K2)
anisotropy.setup(m, Ms_cg, unit_length=1e-9)
H_anis = df.Function(S3)
H_anis.vector()[:] = anisotropy.compute_field()
return dict(m=m, H=H_anis, S3=S3, table=start_table())
def setup_cubic():
print "Running finmag..."
mesh = from_geofile(os.path.join(MODULE_DIR, "bar.geo"))
coords = np.array(zip(* mesh.coordinates()))
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3)
m = Field(S3)
m.set_with_numpy_array_debug(m_gen(coords).flatten())
S1 = df.FunctionSpace(mesh, "Lagrange", 1)
Ms_cg = Field(df.FunctionSpace(mesh, 'CG', 1), Ms)
anisotropy = CubicAnisotropy(u1=u1, u2=u2, K1=K1, K2=K2, K3=K3)
anisotropy.setup(m, Ms_cg, unit_length=1e-9)
H_anis = Field(S3)
H_anis.set_with_numpy_array_debug(anisotropy.compute_field())
return dict(m=m, H=H_anis.f, S3=S3, table=start_table())
def teardown(finmag):
write_table(finmag)
table_delim = " " + "=" * 10 + (" " + "=" * 30) * 4 + "\n"
table_entries = " {:<10} {:<30} {:<30} {:<30} {:<30}\n"
def start_table():
table = ".. _anis_table:\n\n"
table += ".. table:: Comparison of the anisotropy field computed with finmag against nmag, oommf and magpar\n\n"
table += table_delim
table += table_entries.format(
# hack because sphinx light table syntax does not allow an empty header
":math:`\,`",
":math:`\\subn{\\Delta}{test}`",
":math:`\\subn{\\Delta}{max}`",
":math:`\\bar{\\Delta}`",
":math:`\\sigma`")
table += table_delim
return table
def write_table(finmag):
finmag["table"] += table_delim
with open(os.path.join(MODULE_DIR, "table.rst"), "w") as f:
f.write(finmag["table"])
def table_entry(name, tol, rel_diff):
return table_entries.format(
name, s(tol, 0),
s(np.max(rel_diff)), s(np.mean(rel_diff)), s(np.std(rel_diff)))
| 3,299 | 29 | 116 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/retired-test_anis_nmag.py
|
import numpy as np
import conftest
import os
from finmag.util.helpers import vectors, stats
def test_against_nmag(finmag):
# FIXME: why the tolerance is so large?
REL_TOLERANCE = 7e-2
m_ref = np.genfromtxt(os.path.join(conftest.MODULE_DIR, "m0_nmag.txt"))
m_computed = vectors(finmag["m"].get_numpy_array_debug())
assert m_ref.shape == m_computed.shape
H_ref = np.genfromtxt(os.path.join(conftest.MODULE_DIR, "H_anis_nmag.txt"))
H_computed = vectors(finmag["H"].vector().array())
assert H_ref.shape == H_computed.shape
assert m_ref.shape == H_ref.shape
mxH_ref = np.cross(m_ref, H_ref)
mxH_computed = np.cross(m_computed, H_computed)
diff = np.abs(mxH_computed - mxH_ref)
rel_diff = diff / \
np.sqrt(np.max(mxH_ref[0] ** 2 + mxH_ref[1] ** 2 + mxH_ref[2] ** 2))
print "comparison with nmag, m x H, difference:"
print stats(diff)
print "comparison with nmag, m x H, relative difference:"
print stats(rel_diff)
finmag["table"] += conftest.table_entry("nmag", REL_TOLERANCE, rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == "__main__":
finmag = conftest.setup()
test_against_nmag(finmag)
conftest.teardown(finmag)
| 1,232 | 29.825 | 79 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/retired-test_cubic_anis_nmag.py
|
import numpy as np
import conftest
import os
from finmag.util.helpers import vectors, stats
def test_cubic_against_nmag(finmag=conftest.setup_cubic()):
REL_TOLERANCE = 1e-6
m_ref = np.genfromtxt(os.path.join(conftest.MODULE_DIR, "m0_nmag.txt"))
m_computed = vectors(finmag["m"].get_numpy_array_debug())
assert m_ref.shape == m_computed.shape
H_ref = np.genfromtxt(
os.path.join(conftest.MODULE_DIR, "H_cubic_anis_nmag.txt"))
H_computed = vectors(finmag["H"].vector().array())
assert H_ref.shape == H_computed.shape
assert m_ref.shape == H_ref.shape
mxH_ref = np.cross(m_ref, H_ref)
mxH_computed = np.cross(m_computed, H_computed)
print mxH_ref
print mxH_computed
diff = np.abs(mxH_computed - mxH_ref)
rel_diff = diff / \
np.sqrt(np.max(mxH_ref[0] ** 2 + mxH_ref[1] ** 2 + mxH_ref[2] ** 2))
print "comparison with nmag, m x H, difference:"
print stats(diff)
print "comparison with nmag, m x H, relative difference:"
print stats(rel_diff)
finmag["table"] += conftest.table_entry("nmag", REL_TOLERANCE, rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == "__main__":
finmag = conftest.setup_cubic()
test_cubic_against_nmag(finmag)
conftest.teardown(finmag)
| 1,285 | 29.619048 | 76 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/anis_all.py
|
import conftest as test
if __name__ == "__main__":
from test_anis_magpar import test_against_magpar
from test_anis_nmag import test_against_nmag
from test_anis_oommf import test_against_oommf
finmag = test.setup(K2=0)
test_against_magpar(finmag)
test_against_oommf(finmag)
finmag = test.setup()
test_against_nmag(finmag)
test.teardown(finmag)
| 384 | 21.647059 | 52 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/test_cubic_anis_oommf.py
|
import numpy as np
import conftest
from finmag.util.oommf.comparison import oommf_m0, finmag_to_oommf
from finmag.util.oommf import mesh, oommf_cubic_anisotropy
from finmag.util.helpers import stats
def test_against_oommf(finmag=conftest.setup_cubic()):
REL_TOLERANCE = 7e-2
oommf_mesh = mesh.Mesh(
(20, 20, 20), size=(conftest.x1, conftest.y1, conftest.z1))
# FIXME: why our result is three times of oommf's??
oommf_anis = oommf_cubic_anisotropy(m0=oommf_m0(conftest.m_gen, oommf_mesh),
Ms=conftest.Ms, K1=conftest.K1, K2=conftest.K2, u1=conftest.u1, u2=conftest.u2).flat
finmag_anis = finmag_to_oommf(finmag["H"], oommf_mesh, dims=3)
assert oommf_anis.shape == finmag_anis.shape
diff = np.abs(oommf_anis - finmag_anis)
print 'diff', diff
rel_diff = diff / \
np.sqrt(
(np.max(oommf_anis[0] ** 2 + oommf_anis[1] ** 2 + oommf_anis[2] ** 2)))
print "comparison with oommf, H, relative_difference:"
print stats(rel_diff)
finmag["table"] += conftest.table_entry("oommf", REL_TOLERANCE, rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == "__main__":
finmag = conftest.setup_cubic()
test_against_oommf(finmag)
conftest.teardown(finmag)
| 1,284 | 34.694444 | 124 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/test_anis_oommf.py
|
import numpy as np
import conftest
from finmag.util.oommf.comparison import oommf_m0, finmag_to_oommf
from finmag.util.oommf import mesh, oommf_uniaxial_anisotropy
from finmag.util.helpers import stats
def test_against_oommf():
finmag=conftest.setup(K2=0)
REL_TOLERANCE = 9e-2
oommf_mesh = mesh.Mesh(
(20, 20, 20), size=(conftest.x1, conftest.y1, conftest.z1))
oommf_anis = oommf_uniaxial_anisotropy(oommf_m0(conftest.m_gen, oommf_mesh),
conftest.Ms, conftest.K1, conftest.u1).flat
finmag_anis = finmag_to_oommf(finmag["H"], oommf_mesh, dims=3)
assert oommf_anis.shape == finmag_anis.shape
diff = np.abs(oommf_anis - finmag_anis)
rel_diff = diff / \
np.sqrt(
(np.max(oommf_anis[0] ** 2 + oommf_anis[1] ** 2 + oommf_anis[2] ** 2)))
print "comparison with oommf, H, relative_difference:"
print stats(rel_diff)
finmag["table"] += conftest.table_entry("oommf", REL_TOLERANCE, rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == "__main__":
finmag = conftest.setup(K2=0)
test_against_oommf(finmag)
conftest.teardown(finmag)
| 1,171 | 32.485714 | 86 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/anisotropy/test_anis_magpar.py
|
import os.path
import numpy as np
import conftest
import finmag.util.magpar as magpar
from finmag.util.helpers import stats
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def test_against_magpar():
finmag=conftest.setup(K2=0)
REL_TOLERANCE = 5e-7
magpar_result = os.path.join(MODULE_DIR, 'magpar_result', 'test_anis')
magpar_nodes, magpar_anis = magpar.get_field(magpar_result, 'anis')
## Uncomment the lines below to invoke magpar to compute the results,
## rather than using our previously saved results.
# magpar_nodes, magpar_anis = magpar.compute_anis_magpar(finmag["m"],
# K1=conftest.K1, a=conftest.u1, Ms=conftest.Ms)
_, _, diff, rel_diff = magpar.compare_field(
finmag["S3"].mesh().coordinates(), finmag["H"].vector().array(),
magpar_nodes, magpar_anis)
print "comparison with magpar, H, relative_difference:"
print stats(rel_diff)
finmag["table"] += conftest.table_entry("magpar", REL_TOLERANCE, rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == "__main__":
finmag = conftest.setup(K2=0)
test_against_magpar(finmag)
conftest.teardown(finmag)
| 1,184 | 31.916667 | 78 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/demag/run_nmag.py
|
import os
import numpy as np
import nmag
from nmag import SI
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
# create simulation object
sim = nmag.Simulation()
# define magnetic material
Py = nmag.MagMaterial(name='Py', Ms=SI(1.0, 'A/m'))
# load mesh
sim.load_mesh("sphere.nmesh.h5", [('main', Py)], unit_length=SI(1e-9, 'm'))
# set initial magnetisation
sim.set_m([1, 0, 0])
# set external field
sim.set_H_ext([0, 0, 0], SI('A/m'))
H = sim.get_subfield('H_demag')
np.savetxt("H_demag_nmag.txt", H)
| 514 | 19.6 | 75 |
py
|
finmag
|
finmag-master/src/finmag/tests/comparison/demag/test_demag_field.py
|
import os
import numpy as np
import dolfin as df
from finmag.field import Field
from finmag.energies import Demag
from finmag.util.meshes import from_geofile
from finmag.util.helpers import stats, sphinx_sci as s
from finmag.util import magpar
from finmag.util.magpar import compare_field_directly, compute_demag_magpar
import pytest
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
table_delim = " " + "=" * 10 + (" " + "=" * 30) * 4 + "\n"
table_entries = " {:<10} {:<30} {:<30} {:<30} {:<30}\n"
def setup_finmag():
mesh = from_geofile(os.path.join(MODULE_DIR, "sphere.geo"))
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1)
m = Field(S3)
m.set(df.Constant((1, 0, 0)))
Ms = 1
demag = Demag()
demag.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), Ms), unit_length=1e-9)
H = demag.compute_field()
return dict(m=m, H=H, Ms=Ms, S3=S3, table=start_table())
def teardown_finmag(finmag):
finmag["table"] += table_delim
with open(os.path.join(MODULE_DIR, "table.rst"), "w") as f:
f.write(finmag["table"])
def start_table():
table = ".. _demag_table:\n\n"
table += ".. table:: Summary of comparison of the demag field\n\n"
table += table_delim
table += table_entries.format(
# hack because sphinx light table syntax does not allow an empty header
":math:`\,`",
":math:`\\subn{\\Delta}{test}`",
":math:`\\subn{\\Delta}{max}`",
":math:`\\bar{\\Delta}`",
":math:`\\sigma`")
table += table_delim
return table
@pytest.fixture
def finmag(request):
finmag = request.cached_setup(setup=setup_finmag, teardown=teardown_finmag,
scope="module")
return finmag
def test_using_analytical_solution(finmag):
""" Expecting (-1/3, 0, 0) as a result. """
REL_TOLERANCE = 2e-2
H = finmag["H"].reshape((3, -1))
H_ref = np.zeros(H.shape)
H_ref[0] -= 1.0 / 3.0
diff = np.abs(H - H_ref)
rel_diff = diff / \
np.sqrt(np.max(H_ref[0] ** 2 + H_ref[1] ** 2 + H_ref[2] ** 2))
finmag["table"] += table_entries.format(
"analytical", s(REL_TOLERANCE, 0), s(np.max(rel_diff)), s(np.mean(rel_diff)), s(np.std(rel_diff)))
print "comparison with analytical results, H, relative_difference:"
print stats(rel_diff)
assert np.max(rel_diff) < REL_TOLERANCE
#Remove the following nmag test
# The error originates from the new mesh being slightly different
# from the old mesh for which the test reference data was computed.
#
# We speculate that this is from a new version of netgen, relative
# to the tests.
#
# The Nmag test code is not available, but the results stored as a text
# file, so we cannot easily update the results. As we have a large number
# of other tests (and a working comparison with magpar), we remove this
# test now.
#
#
# def retired_test_using_nmag(finmag):
# REL_TOLERANCE = 5e-5
#
# H = finmag["H"].reshape((3, -1))
# H_nmag = np.array(
# zip(* np.genfromtxt(os.path.join(MODULE_DIR, "H_demag_nmag.txt"))))
# diff = np.abs(H - H_nmag)
# rel_diff = diff / \
# np.sqrt(np.max(H_nmag[0] ** 2 + H_nmag[1] ** 2 + H_nmag[2] ** 2))
#
# finmag["table"] += table_entries.format(
# "nmag", s(REL_TOLERANCE, 0), s(np.max(rel_diff)), s(np.mean(rel_diff)), s(np.std(rel_diff)))
# print "comparison with nmag, H, relative_difference:"
# print stats(rel_diff)
#
# # Compare nmag with analytical solution
# H_ref = np.zeros(H_nmag.shape)
# H_ref[0] -= 1.0 / 3.0
#
# nmag_diff = np.abs(H_nmag - H_ref)
# nmag_rel_diff = nmag_diff / \
# np.sqrt(np.max(H_ref[0] ** 2 + H_ref[1] ** 2 + H_ref[2] ** 2))
# finmag["table"] += table_entries.format(
# "nmag/an.", "", s(np.max(nmag_rel_diff)), s(np.mean(nmag_rel_diff)), s(np.std(nmag_rel_diff)))
# print "comparison beetween nmag and analytical solution, H, relative_difference:"
# print stats(nmag_rel_diff)
#
# # rel_diff beetween finmag and nmag
# assert np.max(rel_diff) < REL_TOLERANCE
def test_using_magpar(finmag):
REL_TOLERANCE = 10.0
magpar_result = os.path.join(MODULE_DIR, 'magpar_result', 'test_demag')
magpar_nodes, magpar_H = magpar.get_field(magpar_result, 'demag')
## Uncomment the line below to invoke magpar to compute the results,
## rather than using our previously saved results.
# magpar_nodes, magpar_H = magpar.compute_demag_magpar(finmag["m"], Ms=finmag["Ms"])
_, _, diff, rel_diff = compare_field_directly(
finmag["S3"].mesh().coordinates(), finmag["H"],
magpar_nodes, magpar_H)
finmag["table"] += table_entries.format(
"magpar", s(REL_TOLERANCE, 0), s(np.max(rel_diff)), s(np.mean(rel_diff)), s(np.std(rel_diff)))
print "comparison with magpar, H, relative_difference:"
print stats(rel_diff)
# Compare magpar with analytical solution
H_magpar = magpar_H.reshape((3, -1))
H_ref = np.zeros(H_magpar.shape)
H_ref[0] -= 1.0 / 3.0
magpar_diff = np.abs(H_magpar - H_ref)
magpar_rel_diff = magpar_diff / \
np.sqrt(np.max(H_ref[0] ** 2 + H_ref[1] ** 2 + H_ref[2] ** 2))
finmag["table"] += table_entries.format(
"magpar/an.", "", s(np.max(magpar_rel_diff)), s(np.mean(magpar_rel_diff)), s(np.std(magpar_rel_diff)))
print "comparison beetween magpar and analytical solution, H, relative_difference:"
print stats(magpar_rel_diff)
# rel_diff beetween finmag and magpar
assert np.max(rel_diff) < REL_TOLERANCE
if __name__ == "__main__":
f = setup_finmag()
Hx, Hy, Hz = f["H"].reshape((3, -1))
print "Expecting (Hx, Hy, Hz) = (-1/3, 0, 0)."
print "demag field x-component:\n", stats(Hx)
print "demag field y-component:\n", stats(Hy)
print "demag field z-component:\n", stats(Hz)
# test_using_analytical_solution(f)
# test_using_nmag(f)
test_using_magpar(f)
teardown_finmag(f)
| 5,958 | 33.445087 | 110 |
py
|
finmag
|
finmag-master/src/finmag/native/init.py
|
"""
Provides the symbols from the finmag native extension module.
Importing this module will first compile the finmag extension module, then
load all of its symbols into this module's namespace.
"""
from ..util.native_compiler import make_modules as _make_modules
_make_modules()
| 282 | 27.3 | 74 |
py
|
finmag
|
finmag-master/src/finmag/native/__init__.py
|
# FinMag - a thin layer on top of FEniCS to enable micromagnetic multi-physics simulations
# Copyright (C) 2012 University of Southampton
# Do not distribute
#
# CONTACT: [email protected]
#
# AUTHOR(S) OF THIS FILE: Dmitri Chernyshenko ([email protected])
from init import *
| 289 | 31.222222 | 90 |
py
|
finmag
|
finmag-master/src/finmag/example/sphere_inside_airbox.py
|
import dolfin as df
from finmag.field import Field
from finmag.sim.sim import sim_with
from finmag.util.meshes import sphere_inside_box
from finmag.util.helpers import scalar_valued_dg_function
import numpy as np
def sphere_inside_airbox(r_sphere=5.0, r_shell=10.0, l_box=50.0, maxh_sphere=2.0, maxh_shell=None, maxh_box=10.0, center_sphere=[0, 0, 0], m_init=[1, 0, 0], Ms=8.6e5, A=13e-12, **kwargs):
"""
Create a Simulation object of a sphere inside a box.
The saturation magnetisation of the region outside the
sphere is set to a very low value so that it effectively
appears to be non-magnetic ('air'). However, the demag
field can be sampled in this region and represents the
stray field of the sphere.
*Arguments*
r_shere:
Radius of the sphere.
r_shell:
Radius of the 'shell' enclosing the sphere. The region
between the sphere and the shell will not be meshed.
Everything between the spherical shell and the outer
edges of the box is considered 'air'.
l_box:
The edge length of the box.
maxh_sphere:
Mesh discretization of the sphere.
maxh_box:
Mesh discretization of the box (i.e. the 'air' region).
maxh_shell:
This value determines how finely the inner border of the
'air' region which surrounds the sphere is discretized.
Default: same as the enclosed sphere.
center_sphere:
Center of the inner sphere (default: (0, 0, 0). The box
is always centered at the origin, so this can be used to
shift the sphere relative to the box.
m_init:
Initial magnetisation of the sphere (is normalised
automatically).
Ms:
Saturation magnetisation of the sphere.
A:
Exchange coupling constant of the sphere.
All remaining keyword arguments are passed on to the `sim_with`
command which is used to create the Simulation object.
*Returns*
A Simulation object representing the sphere inside the airbox.
"""
mesh = sphere_inside_box(r_sphere=r_sphere, r_shell=r_shell, l_box=l_box,
maxh_sphere=maxh_sphere, maxh_box=maxh_box,
maxh_shell=maxh_shell, center_sphere=center_sphere)
# Create a Simulation object using this mesh with a tiny Ms in the "air"
# region
def Ms_pyfun(pt):
if np.linalg.norm(pt) <= 0.5 * (r_sphere + r_shell):
return Ms
else:
return 1.
Ms_field = Field(df.FunctionSpace(mesh, 'DG', 0), Ms_pyfun)
def fun_region_marker(pt):
if np.linalg.norm(pt - center_sphere) <= 0.5 * (r_sphere + r_shell):
return "sphere"
else:
return "air"
sim = sim_with(mesh, Ms_field, m_init=m_init, A=A,
unit_length=1e-9, name='sphere_inside_airbox', **kwargs)
sim.mark_regions(fun_region_marker)
return sim
| 2,953 | 27.960784 | 187 |
py
|
finmag
|
finmag-master/src/finmag/example/macrospin.py
|
import dolfin as df
from finmag import Simulation, sim_with
from finmag.energies.zeeman import Zeeman
def macrospin(Ms=0.86e6, m_init=(1, 0, 0), H_ext=(0, 0, 1e6), alpha=0.1,
name='macrospin'):
"""
Minimal mesh with two vertices (1 nm apart). No anisotropy,
exchange coupling or demag is present so that magnetic moments at
the two vertices behave identical under the influence of the
external field. (Ideally, we would only have a single vertex but
Dolfin doesn't support this.)
Default values for the arguments:
Ms = 0.86e6 (saturation magnetisation in A/m)
m_init = (1, 0, 0) (initial magnetisation pointing along the x-axis)
H_ext = (0, 0, 1e6) (external field in A/m)
alpha = 0.1 (Gilbert damping coefficient)
"""
mesh = df.UnitIntervalMesh(1)
sim = Simulation(mesh, Ms=Ms, unit_length=1e-9, name=name)
sim.alpha = alpha
sim.set_m(m_init)
sim.add(Zeeman(H_ext))
return sim
def macrospin_interval(Ms=0.86e6, m_init=(1, 0, 0), H_ext=(0, 0, 1e6), alpha=0.1, name='macrospin'):
"""
1d mesh (= interval) with two vertices which are 1 nm apart.
No anisotropy, exchange coupling or demag is present so that
magnetic moments at the vertices behave identical under the
influence of the external field. The damping constant has the
value alpha=0.1.
Default values for the arguments:
Ms = 0.86e6 (saturation magnetisation in A/m)
m_init = (1, 0, 0) (initial magnetisation pointing along the x-axis)
H_ext = (0, 0, 1e6) (external field in A/m)
alpha = 0.1 (Gilbert damping coefficient)
"""
mesh = df.UnitIntervalMesh()
sim = sim_with(mesh, Ms=1e6, m_init=(1, 0, 0), alpha=alpha,
unit_length=1e-9, H_ext=H_ext, A=None, demag_solver=None, name=name)
return sim
def macrospin_box(Ms=0.86e6, m_init=(1, 0, 0), H_ext=(0, 0, 1e6), alpha=0.1, name='macrospin'):
"""
Cubic mesh of length 1 nm along each edge, with eight vertices
located in the corners of the cube.
No anisotropy, exchange coupling or demag is present so that
magnetic moments at the vertices behave identical under the
influence of the external field.
Default values for the arguments:
Ms = 0.86e6 (saturation magnetisation in A/m)
m_init = (1, 0, 0) (initial magnetisation pointing along the x-axis)
H_ext = (0, 0, 1e6) (external field in A/m)
alpha = 0.1 (Gilbert damping coefficient)
"""
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = sim_with(mesh, Ms=0.86e6, alpha=alpha, unit_length=1e-9,
A=None, H_ext=H_ext, m_init=(1, 0, 0), name=name)
return sim
| 2,767 | 30.454545 | 100 |
py
|
finmag
|
finmag-master/src/finmag/example/bar.py
|
"""
This module provides a few 'standard' simulations that are used
repeatedly in the documentation/manual.
They generally return a simulation object.
"""
import dolfin as df
import finmag
def bar(name='bar', demag_solver_type=None):
"""Py bar with dimensions 30x30x100nm, initial field
pointing in (1,0,1) direction.
Same as example 2 in Nmag manual.
This function returns a simulation object that is 'ready to go'.
Useful commands to run this for a minute::
times = numpy.linspace(0, 3.0e-11, 6 + 1)
for t in times:
# Integrate
sim.run_until(t)
"""
xmin, ymin, zmin = 0, 0, 0 # one corner of cuboid
xmax, ymax, zmax = 30, 30, 100 # other corner of cuboid
# number of subdivisions (use ~2nm edgelength)
nx, ny, nz = 15, 15, 50
mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax), nx, ny, nz)
sim = finmag.sim_with(mesh, Ms=0.86e6, alpha=0.5, unit_length=1e-9,
A=13e-12, m_init=(1, 0, 1), name=name,
demag_solver_type=demag_solver_type)
return sim
def barmini(name='barmini', mark_regions=False, demag_solver_type=None):
"""Py bar with dimensions 3x3x10nm, initial field
pointing in (1,0,1) direction.
Same as example 2 in Nmag manual, but much smaller (and faster).
This function returns a simulation object that is 'ready to go'.
If `mark_regions` is True, the mesh will be subdivided vertically
into two regions which are markes as 'top' and 'bottom'.
Useful commands to run this for a couple of seconds:
times = numpy.linspace(0, 3.0e-11, 6 + 1)
for t in times:
# Integrate
sim.run_until(t)
"""
xmin, ymin, zmin = 0, 0, 0 # one corner of cuboid
xmax, ymax, zmax = 3, 3, 10 # other corner of cuboid
# number of subdivisions (use ~2nm edgelength)
nx, ny, nz = 2, 2, 4
mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax), nx, ny, nz)
sim = finmag.sim_with(mesh, Ms=0.86e6, alpha=0.5, unit_length=1e-9,
A=13e-12, m_init=(1, 0, 1), name=name,
demag_solver_type=demag_solver_type)
if mark_regions:
def fun_regions(pt):
return 'bottom' if (pt[2] <= 5.0) else 'top'
sim.mark_regions(fun_regions)
return sim
| 2,410 | 30.723684 | 89 |
py
|
finmag
|
finmag-master/src/finmag/example/__init__.py
|
# FinMag - a thin layer on top of FEniCS to enable micromagnetic multi-physics simulations
# Copyright (C) 2012 University of Southampton
# Do not distribute
#
# CONTACT: [email protected]
#
# AUTHOR(S) OF THIS FILE: Hans Fangohr
from bar import bar, barmini
from nanowire import nanowire
from sphere_inside_airbox import sphere_inside_airbox
import normal_modes
| 367 | 29.666667 | 90 |
py
|
finmag
|
finmag-master/src/finmag/example/nanowire.py
|
"""
This module provides a few 'standard' simulations that are used
repeatedly in the documentation/manual.
They generally return a simulation object.
"""
import dolfin as df
import finmag
from math import sin, cos, pi
def nanowire(lx=100, ly=10, lz=3, nx=30, ny=3, nz=1, name='nanowire'):
"""
Permalloy nanowire with head-to-head domain wall. The nanowire
has dimensions lx, ly, lz and discretization nx, ny, nz along
the three coordinate axes.
"""
A = 13e-12
Ms = 8e5
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(lx, ly, lz), nx, ny, nz)
S1 = df.FunctionSpace(mesh, 'CG', 1)
S3 = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
def m_init_fun(pt):
x, y, z = pt
return [cos(x*pi/lx), sin(x*pi/lx), 0]
sim = finmag.sim_with(mesh, Ms=Ms, m_init=m_init_fun, unit_length=1e-9, A=A)
return sim
| 864 | 25.212121 | 80 |
py
|
finmag
|
finmag-master/src/finmag/example/normal_modes/disk.py
|
import finmag
import dolfin as df
import os
from finmag.util.mesh_templates import Nanodisk
def disk(d=60, h=10, maxh=5.0, relaxed=True, name='normal_modes_nanodisk', A=13e-12, H_ext_relax=[1e5, 1e3, 0], H_ext_ringdown=[1e5, 0, 0],
demag_solver='FK', demag_solver_type=None, force_relaxation=False):
"""
Permalloy nanodisk with diameter d=60 nm, height h=10 nm and mesh
discretisation maxh=5.0. An external field of strength 100 kA/m is
applied along the x-axis, with a small (1 kA/m) y-component for
the relaxation which is then removed for the ringdown phase.
"""
# I don't know it's suitable to move the global definition to local one
# just try to make the cython happy?
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
if d == 60 and h == 10 and maxh == 5.0:
# Use precomputed standard mesh
mesh = df.Mesh(
os.path.join(MODULE_DIR, 'disk__d_60__h_10__maxh_5.xml.gz'))
else:
mesh = Nanodisk(d=d, h=h).create_mesh(maxh=maxh)
# Material parameters for Permalloy
Ms = 8e5
m_init = [1, 0, 0]
alpha_relax = 1.0
sim = finmag.normal_mode_simulation(mesh, Ms, m_init, alpha=alpha_relax, unit_length=1e-9, A=A, H_ext=H_ext_relax,
demag_solver=demag_solver, demag_solver_type=demag_solver_type, name=name)
if relaxed:
if not force_relaxation and (d == 60 and h == 10 and maxh == 5.0):
sim.restart(os.path.join(MODULE_DIR, 'disk_relaxed.npz'))
else:
sim.relax()
alpha_ringdown = 0.01
t_end = 1e-9
save_ndt_every = 1e-11
save_m_every = 1e-11
m_snapshots_filename = 'snapshots/m_ringdown.npy'
# Pre-define parameters for the 'run_ringdown()' method so that
# the user can just say: 'sim.run_ringdown()' and it does
# something sensible.
def ringdown(t_end=1e-9, alpha=alpha_ringdown, H_ext=H_ext_ringdown,
reset_time=True, clear_schedule=True,
save_ndt_every=save_ndt_every, save_vtk_every=None, save_m_every=save_m_every,
vtk_snapshots_filename=None, m_snapshots_filename=m_snapshots_filename,
overwrite=False):
sim.run_ringdown(
t_end=t_end, alpha=alpha, H_ext=H_ext, reset_time=reset_time,
clear_schedule=clear_schedule, save_ndt_every=save_ndt_every,
save_vtk_every=None, save_m_every=save_m_every,
vtk_snapshots_filename=None, m_snapshots_filename=m_snapshots_filename,
overwrite=overwrite)
sim.ringdown = ringdown
return sim
| 2,611 | 40.460317 | 139 |
py
|
finmag
|
finmag-master/src/finmag/example/normal_modes/__init__.py
|
# FinMag - a thin layer on top of FEniCS to enable micromagnetic multi-physics simulations
# Copyright (C) 2012 University of Southampton
# Do not distribute
#
# CONTACT: [email protected]
#
# AUTHOR(S) OF THIS FILE: Maximilian Albert
from disk import disk
| 261 | 28.111111 | 90 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim.py
|
from __future__ import division
import os
import time
import inspect
import logging
import itertools
import sys
import dolfin as df
import numpy as np
import cProfile
import pstats
from aeon import timer
from finmag.field import Field
from finmag.physics.llg import LLG
from finmag.physics.llg_stt import LLG_STT
from finmag.physics.llb.sllg import SLLG
from finmag.sim import sim_details
from finmag.sim import sim_relax
from finmag.sim import sim_savers
from finmag.util.meshes import mesh_volume, mesh_size_plausible, \
describe_mesh_size, plot_mesh, plot_mesh_with_paraview
from finmag.util.fileio import Tablewriter, FieldSaver
from finmag.util import helpers
from finmag.util.vtk_saver import VTKSaver
from finmag.sim.hysteresis import hysteresis as hyst, hysteresis_loop as hyst_loop
from finmag.sim import sim_helpers, magnetisation_patterns
from finmag.drivers.llg_integrator import llg_integrator
from finmag.drivers.sundials_integrator import SundialsIntegrator
from finmag.scheduler import scheduler
from finmag.util.pbc2d import PeriodicBoundary1D, PeriodicBoundary2D
from finmag.energies import Exchange, Zeeman, TimeZeeman, Demag, UniaxialAnisotropy, DMI, MacroGeometry
# used for parallel testing
#from finmag.native import cvode_petsc, llg_petsc
log = logging.getLogger(name="finmag")
class Simulation(object):
"""
Unified interface to finmag's micromagnetic simulations capabilities.
Attributes:
t the current simulation time
"""
# see comment at end of file on 'INSTANCE'
instance_counter_max = 0
instances = {}
@timer.method
def __init__(self, mesh, Ms, unit_length=1, name='unnamed', kernel='llg', integrator_backend="sundials", pbc=None, average=False, parallel=False):
"""Simulation object.
*Arguments*
mesh : a dolfin mesh
Ms : Magnetisation saturation (in A/m) of the material.
unit_length: the distance (in metres) associated with the
distance 1.0 in the mesh object.
name : the Simulation name (used for writing data files, for examples)
pbc : Periodic boundary type: None or '2d'
kernel : 'llg', 'sllg' or 'llg_stt'
average : take the cell averaged effective field, only for test, will delete it if doesn't work.
"""
# Store the simulation name and a 'sanitized' version of it which
# contains only alphanumeric characters and underscores. The latter
# will be used as a prefix for .log/.ndt files etc.
self.name = name
#log.debug("__init__:sim-object '{}' refcount 1={}".format(self.name, sys.getrefcount(self)))
self.sanitized_name = helpers.clean_filename(name)
self.logfilename = self.sanitized_name + '.log'
self.ndtfilename = self.sanitized_name + '.ndt'
self.logging_handler = helpers.start_logging_to_file(
self.logfilename, mode='w', level=logging.DEBUG)
#log.debug("__init__:sim-object '{}' refcount 30={}".format(self.name, sys.getrefcount(self)))
# instance booking
self.instance_id = Simulation.instance_counter_max
Simulation.instance_counter_max += 1
assert self.instance_id not in Simulation.instances.keys()
Simulation.instances[self.instance_id] = self
# Create a Tablewriter object for ourselves which will be used
# by various methods to save the average magnetisation at given
# timesteps.
self.tablewriter = Tablewriter(self.ndtfilename, self, override=True)
# Note that we pass the simulation object ("self") to the Tablewrite in the line above, and
# that the table writer stores a reference. This is just a cyclic reference. If we want
# the garbage collection to be able to collect this simulation object, we need to remove
# that cyclic reference. This is what the 'delete()' method attempts to do.
#log.debug("__init__:sim-object '{}' refcount 31={}".format(self.name, sys.getrefcount(self)))
self.tablewriter.add_entity('E_total', {
'unit': '<J>',
'get': lambda sim: sim.total_energy(),
'header': 'E_total'})
self.tablewriter.add_entity('H_total', {
'unit': '<A/m>',
'get': lambda sim: helpers.average_field(sim.effective_field()),
'header': ('H_total_x', 'H_total_y', 'H_total_z')})
#log.debug("__init__:sim-object '{}' refcount 32={}".format(self.name, sys.getrefcount(self)))
log.info("Creating Sim object name='{}', instance_id={} (rank={}/{}).".format(
self.name, self.instance_id, df.MPI.rank(df.mpi_comm_world()), df.MPI.size(df.mpi_comm_world())))
log.debug(" Total number of Sim objects in this session: {}".format(self.instances_alive_count()))
log.info(mesh)
self.pbc = pbc
if pbc == '2d':
log.debug(
'Setting 2d periodic boundary conditions (in the xy-plane).')
self.pbc = PeriodicBoundary2D(mesh)
elif pbc == '1d':
log.debug(
'Setting 1d periodic boundary conditions (along the x-axis)')
self.pbc = PeriodicBoundary1D(mesh)
elif pbc != None:
raise ValueError("Argument 'pbc' must be one of None, '1d', '2d'.")
#log.debug("__init__:sim-object '{}' refcount 35={}".format(self.name, sys.getrefcount(self)))
if not mesh_size_plausible(mesh, unit_length):
log.warning(
"The mesh is {}.".format(describe_mesh_size(mesh, unit_length)))
log.warning(
"unit_length is set to {}. Are you sure this is correct?".format(unit_length))
#log.debug("__init__:sim-object '{}' refcount 50={}".format(self.name, sys.getrefcount(self)))
self.mesh = mesh
self.unit_length = unit_length
self.integrator_backend = integrator_backend
self._integrator = None
self.S1 = df.FunctionSpace(
mesh, "Lagrange", 1, constrained_domain=self.pbc)
self.S3 = df.VectorFunctionSpace(
mesh, "Lagrange", 1, dim=3, constrained_domain=self.pbc)
#log.debug("__init__:sim-object '{}' refcount 40={}".format(self.name, sys.getrefcount(self)))
if kernel == 'llg':
self.llg = LLG(
self.S1, self.S3, average=average, unit_length=unit_length)
elif kernel == 'sllg':
self.llg = SLLG(self.S1, self.S3, unit_length=unit_length)
elif kernel == 'llg_stt':
self.llg = LLG_STT(self.S1, self.S3, unit_length=unit_length)
else:
raise ValueError("kernel must be one of llg, sllg or llg_stt.")
#log.debug("__init__:sim-object '{}' refcount 41={}".format(self.name, sys.getrefcount(self)))
self.Ms = Ms
self.kernel = kernel
self.Volume = mesh_volume(mesh)
self.scheduler = scheduler.Scheduler()
self.callbacks_at_scheduler_events = []
self.domains = df.CellFunction("uint", self.mesh)
self.domains.set_all(0)
self.region_id = 0
#log.debug("__init__:sim-object '{}' refcount 80={}".format(self.name, sys.getrefcount(self)))
# XXX TODO: this separation between vtk_savers and
# field_savers is artificial and should/will be removed once
# we have a robust, unified field saving mechanism.
self.vtk_savers = {}
self.field_savers = {}
self._render_scene_indices = {}
#log.debug("__init__:sim-object '{}' refcount 85={}".format(self.name, sys.getrefcount(self)))
self.scheduler_shortcuts = {
'eta': sim_helpers.eta,
'ETA': sim_helpers.eta,
'plot_relaxation': sim_helpers.plot_relaxation,
'render_scene': Simulation._render_scene_incremental,
'save_averages': sim_helpers.save_ndt,
'save_field': sim_savers._save_field_incremental,
'save_m': sim_savers._save_m_incremental,
'save_ndt': sim_helpers.save_ndt,
'save_restart_data': sim_helpers.save_restart_data,
'save_vtk': sim_savers.save_vtk, # <- this line creates a reference to the simulation object. Why?
'switch_off_H_ext': Simulation.switch_off_H_ext,
}
#log.debug("__init__:sim-object '{}' refcount 86={}".format(self.name, sys.getrefcount(self)))
# At the moment, we can only have cvode as the driver, and thus do
# time development of a system. We may have energy minimisation at some
# point (the driver would be an optimiser), or something else.
self.driver = 'cvode'
# let's use 1e-6 as default and we can change it later
self.reltol = 1e-6
self.abstol = 1e-6
#log.debug("__init__:sim-object '{}' refcount 88={}".format(self.name, sys.getrefcount(self)))
self.parallel = parallel
if self.parallel:
self.m_petsc = self.llg._m_field.petsc_vector()
#df.parameters.reorder_dofs_serial = True
#log.debug("__init__:sim-object '{}' refcount 100={}".format(self.name, sys.getrefcount(self)))
def shutdown(self):
"""Attempt to clear all cyclic dependencies and close all files.
The simulation object is unusable after this has been called, but
should be garbage collected if going out of scope subsequently.
Returns the number of references to self -- in my tests in March 2015,
this number was 4 when all cyclic references were removed, and thus
the next GC did work."""
log.info("Shutting down Simulation object {}".format(self.__str__()))
# instance book keeping
assert self.instance_id in Simulation.instances.keys()
# remove reference to this simulation object from dictionary
del Simulation.instances[self.instance_id]
log.debug("{} other Simulation instances alive.".format(
self.instances_alive_count()))
# now start to remove (potential) references to 'self':
log.debug(" shutdown(): 1-refcount {} for {}".format(sys.getrefcount(self), self.name))
self.tablewriter.delete_entity_get_methods()
#'del self.tablewriter' would be sufficient?
log.debug(" shutdown(): 2-refcount {} for {}".format(sys.getrefcount(self), self.name))
del self.tablewriter.sim
log.debug(" shutdown(): 3-refcount {} for {}".format(sys.getrefcount(self), self.name))
self.clear_schedule()
log.debug(" shutdown(): 4-refcount {} for {}".format(sys.getrefcount(self), self.name))
del self.scheduler
log.debug(" shutdown(): 5-refcount {} for {}".format(sys.getrefcount(self), self.name))
del self.scheduler_shortcuts
log.debug(" shutdown(): 6-refcount {} for {}".format(sys.getrefcount(self), self.name))
self.close_logfile()
log.debug(" shutdown(): 7-refcount {} for {}".format(sys.getrefcount(self), self.name))
return sys.getrefcount(self)
def instances_delete_all_others(self):
for id_ in sorted(Simulation.instances.keys()):
if id_ != None: # can happen if instances have been deleted
if id_ != self.instance_id: # do not delete ourselves, here
sim = Simulation.instances[id_]
sim.shutdown()
del sim
@staticmethod
def instances_list_all():
log.info("Showing all Simulation object instances:")
for id_ in sorted(Simulation.instances.keys()):
if id_ != None: # can happen if instances have been deleted
log.info(" sim instance_id={}: name='{}'".format(id_, Simulation.instances[id_].name))
@staticmethod
def instances_delete_all():
log.info("instances_delete_all() starting:")
if len(Simulation.instances) == 0:
log.debug(" no instances found")
return # no objects exist
else:
for id_ in sorted(Simulation.instances.keys()):
sim = Simulation.instances[id_]
sim.shutdown()
del sim
log.debug("instances_delete_all() ending")
def instances_alive_count(self):
return sum([1 for id_ in Simulation.instances.keys() if id_ != None])
def __del__(self):
print "Simulation object about to be destroyed."
def __str__(self):
"""String briefly describing simulation object"""
return "finmag.Simulation(name='%s', instance_id=%s) with %s" % (self.name, self.instance_id, self.mesh)
def __get_m(self):
"""The unit magnetisation"""
return self.llg._m_field.get_numpy_array_debug()
def set_m(self, value, normalise=True, **kwargs):
"""
Set the magnetisation (if `normalise` is True, it is automatically
normalised to unit length).
`value` can have any of the forms accepted by the function
'finmag.util.helpers.vector_valued_function' (see its
docstring for details).
You can call this method anytime during the simulation. However, when
providing a numpy array during time integration, the use of
the attribute m instead of this method is advised for performance
reasons and because the attribute m doesn't normalise the vector.
"""
# TODO: Remove debug flag again once we are sure that re-initialising
# the integrator doesn't cause a performance overhead.
debug = kwargs.pop('debug', True)
self.llg.set_m(value, normalise=normalise, **kwargs)
if self.has_integrator():
self.reinit_integrator(debug=debug)
m = property(__get_m, set_m)
@property
def Ms(self):
return self._Ms
@Ms.setter
def Ms(self, value):
self._Ms = Field(df.FunctionSpace(self.mesh, 'DG', 0), value)
self.llg.Ms = self._Ms
# XXX TODO: Do we also need to reset Ms in the interactions or is this
# automatically done by the llg or effective field?!?
@property
def m_field(self):
return self.llg.m_field
@property
def m_average(self):
"""
Compute and return the average magnetisation over the entire
mesh, according to the formula :math:`\\langle m \\rangle =
\\frac{1}{V} \int m \: \mathrm{d}V`
"""
return self.llg.m_average
# @property
# def _m(self):
# return self.llg._m
def save_m_in_region(self, region, name='unnamed'):
self.region_id += 1
helpers.mark_subdomain_by_function(
region, self.mesh, self.region_id, self.domains)
self.dx = df.Measure("dx")[self.domains]
if name == 'unnamed':
name = 'region_' + str(self.region_id)
region_id = self.region_id
self.tablewriter.entities[name] = {
'unit': '<>',
'get': lambda sim: sim.llg.m_average_fun(dx=self.dx(region_id)),
'header': (name + '_m_x', name + '_m_y', name + '_m_z')}
self.tablewriter.update_entity_order()
@property
def t(self):
"""
Returns the current simulation time.
"""
if hasattr(self, "integrator"):
return self.integrator.cur_t # the real thing
return 0.0
@property
def dmdt_max(self):
"""
Gets dmdt values for each mesh node. Finds the max of
the L2 Norms. Returns (x,y,z) components of dmdt, where
this max occurs.
"""
# FIXME:error here
dmdts = self.llg.dmdt.reshape((3, -1))
norms = np.sqrt(np.sum(dmdts ** 2, axis=0))
index = norms.argmax()
dmdt_x = dmdts[0][index]
dmdt_y = dmdts[1][index]
dmdt_z = dmdts[2][index]
return np.array([dmdt_x, dmdt_y, dmdt_z])
@property
def dmdt(self):
"""
Returns dmdt for all mesh nodes.
*** What is the best format (e.g. numpy of dolfin) for this? ***
"""
return self.llg.dmdt
def add(self, interaction, with_time_update=None):
"""
Add an interaction (such as Exchange, Anisotropy, Demag).
*Arguments:*
interaction
The interaction to be added.
with_time_update (optional)
A function of the form f(t), which accepts a time step
`t` as its only single parameter and updates the internal
state of the interaction accordingly.
"""
self.llg.effective_field.add(interaction, with_time_update)
if isinstance(interaction, TimeZeeman):
# The following line ensures that the field value is updated
# correctly whenever the time integration reaches a scheduler
# "checkpoint" (i.e. whenever integrator.advance_time(t) finishes
# successfully).
self.callbacks_at_scheduler_events.append(interaction.update)
energy_name = 'E_{}'.format(interaction.name)
field_name = 'H_{}'.format(interaction.name)
self.tablewriter.add_entity(energy_name, {
'unit': '<J>',
'get': lambda sim: sim.get_interaction(interaction.name).compute_energy(),
'header': energy_name})
self.tablewriter.add_entity(field_name, {
'unit': '<A/m>',
'get': lambda sim: sim.get_interaction(interaction.name).average_field(),
'header': (field_name + '_x', field_name + '_y', field_name + '_z')})
def effective_field(self):
"""
Compute and return the effective field.
"""
return self.llg.effective_field.compute(self.t)
def total_energy(self):
"""
Compute and return the total energy of all fields present in
the simulation.
"""
return self.llg.effective_field.total_energy()
def compute_energy(self, name="total"):
"""
Compute and return the energy contribution from a specific
interaction (Exchange, Demag, Zeeman, etc.). If the simulation
does not contain an interaction with this name, a value of
zero is returned.
*Arguments*
name: string
The name of the interaction for which the energy should be
computed, or 'total' for the total energy present in the
simulation (this is the default if no argument is given).
"""
if name.lower() == 'total':
res = self.total_energy()
else:
interaction = self.get_interaction(name)
res = interaction.compute_energy()
return res
def has_interaction(self, interaction_name):
"""
Returns True if an interaction with the given name exists, and False otherwise.
*Arguments*
interaction_name: string
Name of the interaction.
"""
return self.llg.effective_field.exists(interaction_name)
def interactions(self):
""" Return the names of the known interactions. """
return self.llg.effective_field.all()
def get_interaction(self, interaction_name):
"""
Returns the interaction with the given name
*Arguments*
interaction_name: string
Name of the interaction.
*Returns*
The matching interaction object. If no or more than one matching
interaction is found, a ValueError is raised.
"""
return self.llg.effective_field.get(interaction_name)
def get_interaction_list(self):
"""
Returns a list of interaction names.
*Returns*
A list of strings, each string corresponding to the name of one interaction.
"""
return self.llg.effective_field.all()
def remove_interaction(self, interaction_type):
"""
Remove the interaction of the given type.
*Arguments*
interaction_type: string
The allowed types are those finmag knows about by classname, for
example: 'Demag', 'Exchange', 'UniaxialAnisotropy', 'Zeeman'.
"""
log.debug("Removing interaction '{}' from simulation '{}'".format(
interaction_type, self.name))
# remove this interaction from TableWriter entities
E_name = "E_{}".format(interaction_type)
H_name = "E_{}".format(interaction_type)
self.tablewriter.delete_entity_get_method(E_name)
self.tablewriter.delete_entity_get_method(H_name)
return self.llg.effective_field.remove(interaction_type)
def set_H_ext(self, H_ext):
"""
Convenience function to set the external field.
"""
try:
H = self.get_interaction("Zeeman")
H.set_value(H_ext)
except KeyError:
H = Zeeman(H_ext)
self.add(H)
def switch_off_H_ext(self, remove_interaction=False):
"""
Convenience function to switch off the external field.
If `remove_interaction` is True (the default), the Zeeman
interaction will be completely removed from the Simulation
class, which should make the time integration run faster.
Otherwise its value is just set to zero.
"""
if remove_interaction:
dbg_str = "(removing Zeeman interaction)"
self.remove_interaction("Zeeman")
else:
dbg_str = "(setting value to zero)"
H = self.get_interaction("Zeeman")
H.set_value([0, 0, 0])
log.debug("Switching off external field {}".format(dbg_str))
def get_field_as_dolfin_function(self, field_type, region=None):
"""
Returns the field of the interaction of the given type or of the
magnetisation as a dolfin function.
*Arguments*
field_type: string
The allowed types are those finmag knows about by classname, for
example: 'Demag', 'Exchange', 'UniaxialAnisotropy', 'Zeeman',
as well as 'm' which stands for the normalised magnetisation.
region:
Some identifier that uniquely identifies a mesh region. This required
that the method `mark_regions` has been called previously so that the
simulation knows about the regions and their IDs.
*Returns*
A dolfin.Function representing the given field. If no or more than one
matching field is found, a ValueError is raised.
"""
if field_type == 'm':
field = self.llg._m_field.f
else:
field = self.llg.effective_field.get_dolfin_function(field_type)
res = field
if region:
# XXX TODO: The function space V_region was created using a 'restriction'.
# This means that the underlying mesh of the function space is
# still the full mesh. However, dolfin functions in V_region will
# only have degrees of freedom corresponding to the specific region.
# Strangely, however, if we construct a function such as 'field' below
# and ask for its vector, it seems to contain elements that don't make
# sense. Need to debug this, but for now we go the route below and
# explicitly construct a function space on the submesh for the region
# and interpolate into that.
V_region = self._get_region_space(region)
#field_restr = df.interpolate(field, V_region)
#res = field_restr
# Define a new function space on the submesh belonging to the region and interpolate
# the field into it. I would have thought that this is precisely what the restricted
# function spaces are intended for in dolfin, but the previous lines don't seem to
# work as intended, so I'm using this intermediate fix for now.
submesh = self.get_submesh(region)
if (V_region.ufl_element().family() != 'Lagrange'):
raise NotImplementedError(
"XXX The following lines assume that we have a CG1 function space. Fix this!!")
if (V_region.ufl_element().value_shape() != (3,)):
raise NotImplementedError(
"This functioality is currently only implemented for 3-vector fields.")
V_submesh = df.VectorFunctionSpace(submesh, 'CG', 1, dim=3)
f_submesh = df.interpolate(field, V_submesh)
res = f_submesh
return res
def _get_region_space(self, region=None):
if region:
try:
V_region = self.region_spaces[region]
except AttributeError:
raise RuntimeError(
"No regions defined in mesh. Please call 'mark_regions' first to define some.")
except KeyError:
raise ValueError("Region not defined: '{}'. Allowed values: {}".format(
region, self.region_ids.keys()))
else:
V_region = self.S3
return V_region
def _get_region_id(self, region=None):
if region:
try:
region_id = self.region_ids[region]
except AttributeError:
raise RuntimeError(
"No regions defined in mesh. Please call 'mark_regions' first to define some.")
except KeyError:
raise ValueError("Region not defined: '{}'. Allowed values: {}".format(
region, self.region_ids.keys()))
return region_id
def probe_field(self, field_type, pts, region=None):
"""
Probe the field of type `field_type` at point(s) `pts`, where
the point coordinates must be specified in mesh coordinates.
See the documentation of the method get_field_as_dolfin_function
to know which ``field_type`` is allowed, and helpers.probe for the
shape of ``pts``.
"""
return helpers.probe(self.get_field_as_dolfin_function(field_type, region=region), pts)
def probe_field_along_line(self, field_type, pt_start, pt_end, N=100, region=None):
"""
Probe the field of type `field_type` at `N` equidistant points
along a straight line connecting `pt_start` and `pt_end`.
Returns a pair `(pts, vals)` where `pts` is the list of probing
points and `vals` is the list of probed values.
See the documentation of the method get_field_as_dolfin_function
to know which ``field_type`` is allowed.
Example:
probe_field_along_line('m', [-200, 0, 0], [200, 0, 0], N=200)
"""
field = self.get_field_as_dolfin_function(field_type, region=region)
return helpers.probe_along_line(field, pt_start, pt_end, N)
def has_integrator(self):
return (self._integrator != None)
def _get_integrator(self):
if not self.has_integrator():
self.create_integrator()
assert self.has_integrator()
return self._integrator
def _set_integrator(self, value):
self._integrator = value
integrator = property(_get_integrator, _set_integrator)
def create_integrator(self, backend=None, **kwargs):
if backend is not None:
self.integrator_backend = backend
if not self.has_integrator():
if self.parallel:
# HF, the reason for commenting out the line below is that
# cython fails to compile the file otherwise. Will all be
# fixed when the parallel sundials is completed. Sep 2014
raise Exception(
"The next line has been deactivated - fix to proceed with parallel")
#self._integrator = cvode_petsc.CvodeSolver(self.llg.sundials_rhs_petsc, 0, self.m_petsc, self.reltol, self.abstol)
elif self.kernel == 'llg_stt':
self._integrator = SundialsIntegrator(
self.llg, self.llg.dy_m, method="bdf_diag", **kwargs)
elif self.kernel == 'sllg':
self._integrator = self.llg
else:
self._integrator = llg_integrator(
self.llg, self.llg._m_field, backend=self.integrator_backend,
reltol=self.reltol, abstol=self.abstol, **kwargs)
# HF: the following code works only for sundials, i.e. not for
# scipy.integrate.vode.
# self.tablewriter.add_entity( 'steps', {
# 'unit': '<1>',
# 'get': lambda sim: sim.integrator.stats()['nsteps'],
# 'header': 'steps'})
self.tablewriter.modify_entity_get_method(
'steps', lambda sim: sim.integrator.stats()['nsteps'])
# self.tablewriter.add_entity('last_step_dt', {
# 'unit': '<1>',
# 'get': lambda sim: sim.integrator.stats()['hlast'],
# 'header': 'last_step_dt'})
self.tablewriter.modify_entity_get_method(
'last_step_dt', lambda sim: sim.integrator.stats()['hlast'])
# self.tablewriter.add_entity('dmdt', {
# 'unit': '<A/ms>',
# 'get': lambda sim: sim.dmdt_max,
# 'header': ('dmdt_x', 'dmdt_y', 'dmdt_z')})
self.tablewriter.modify_entity_get_method(
'dmdt', lambda sim: sim.dmdt_max)
else:
import ipdb; ipdb.set_trace()
log.warning(
"Cannot create integrator - exists already: {}".format(self._integrator))
return self._integrator
def set_tol(self, reltol=1e-6, abstol=1e-6):
"""
Set the tolerences of the default integrator.
"""
self.reltol = reltol
self.abstol = abstol
if self.has_integrator():
if self.parallel:
#self.integrator.set_options(reltol, abstol)
pass
else:
self.integrator.integrator.set_scalar_tolerances(reltol, abstol)
def advance_time(self, t):
"""
The lower-level counterpart to run_until, this runs without a schedule.
"""
log.debug("Advancing time to t = {} s.".format(t))
self.integrator.advance_time(t)
# The following line is necessary because the time integrator may
# slightly overshoot the requested end time, so here we make sure
# that the field values represent that requested time exactly.
self.llg.effective_field.update(t)
def run_until(self, t):
"""
Run the simulation until the given time `t` is reached.
"""
log.info("Simulation will run until t = {:.2g} s.".format(t))
self.t_max = t
# Define function that stops integration and add it to scheduler. The
# at_end parameter is required because t can be zero, which is
# considered as False for comparison purposes in scheduler.add.
def call_to_end_integration():
return False
self.scheduler.add(call_to_end_integration, at=t, at_end=True)
self.scheduler.run(self.integrator, self.callbacks_at_scheduler_events)
if self.parallel:
# print self.llg._m_field.f.vector().array()
# TODO: maybe this is not necessary, check it later.
pass
# self.llg._m_field.f.vector().set_local(self.integrator.y_np)
# The following line is necessary because the time integrator may
# slightly overshoot the requested end time, so here we make sure
# that the field values represent that requested time exactly.
self.llg.effective_field.update(t)
log.info("Simulation has reached time t = {:.2g} s.".format(self.t))
relax = sim_relax.relax
save_restart_data = sim_helpers.save_restart_data
def restart(self, filename=None, t0=None):
"""If called, we look for a filename of type sim.name + '-restart.npz',
and load it. The magnetisation in the restart file will be assigned to
self._m. If this is from a cvode time integration run, it will also
initialise (create) the integrator with that m, and the time at which the
restart data was saved.
The time can be overriden with the optional parameter t0 here.
The method will fail if no restart file exists.
"""
if filename == None:
filename = sim_helpers.canonical_restart_filename(self)
log.debug("Loading restart data from {}. ".format(filename))
data = sim_helpers.load_restart_data(filename)
if not data['driver'] in ['cvode']:
log.error("Requested unknown driver `{}` for restarting. Known: {}.".format(
data["driver"], "cvode"))
raise NotImplementedError(
"Unknown driver `{}` for restarting.".format(data["driver"]))
self.llg._m_field.set_with_numpy_array_debug(data['m'])
self.reset_time(data["simtime"] if (t0 == None) else t0)
log.info("Reloaded and set m (<m>=%s) and time=%s from %s." %
(self.llg.m_average, self.t, filename))
def reset_time(self, t0):
"""
Reset the internal clock time of the simulation to `t0`.
This also adjusts the internal time of the scheduler and time integrator.
"""
# WW: Is it good to create a new integrator and with the name of reset_time? this
# is a bit confusing and dangerous because the user doesn't know a new integrator
# is created and the other setting that the user provided such as the tolerances
# actually doesn't have influence at all.
self.integrator = llg_integrator(self.llg, self.llg._m_field,
backend=self.integrator_backend, t0=t0)
self.set_tol(self.reltol, self.abstol)
self.scheduler.reset(t0)
assert self.t == t0 # self.t is read from integrator
# Include magnetisation initialisation functions.
initialise_helix_2D = magnetisation_patterns.initialise_helix_2D
initialise_skyrmions = magnetisation_patterns.initialise_skyrmions
initialise_skyrmion_hexlattice_2D = magnetisation_patterns.initialise_skyrmion_hexlattice_2D
initialise_vortex = magnetisation_patterns.initialise_vortex
save_averages = sim_helpers.save_ndt
save_ndt = sim_helpers.save_ndt
hysteresis = hyst
hysteresis_loop = hyst_loop
skyrmion_number = sim_helpers.skyrmion_number
skyrmion_number_density_function = sim_helpers.skyrmion_number_density_function
def __get_pins(self):
return self.llg.pins
def __set_pins(self, nodes):
pinlist = []
if hasattr(nodes, '__call__'):
coords = self.mesh.coordinates()
for i, c in enumerate(coords):
if nodes(c):
pinlist.append(i)
pinlist = np.array(pinlist)
self.llg.pins = pinlist
else:
self.llg.pins = nodes
pins = property(__get_pins, __set_pins)
@property
def do_precession(self):
return self.llg.do_precession
@do_precession.setter
def do_precession(self, value):
self.llg.do_precession = value
@property
def alpha(self):
"""
The damping constant :math:`\\alpha`.
It is stored as a scalar valued df.Function. However, it can be set
using any type accepted by the function
:py:func:`finmag.util.helpers.scalar_valued_function`.
"""
return self.llg.alpha
@alpha.setter
def alpha(self, value):
self.llg.set_alpha(value)
def __get_gamma(self):
return self.llg.gamma
def __set_gamma(self, value):
self.llg.gamma = value
gamma = property(__get_gamma, __set_gamma)
def __get_dt(self):
return self.llg.dt
def __set_dt(self, value):
self.llg.dt = value
dt = property(__get_dt, __set_dt)
def __get_T(self):
return self.llg.T
def __set_T(self, value):
self.llg.T = value
T = property(__get_T, __set_T)
run_normal_modes_computation = sim_helpers.run_normal_modes_computation
# TODO: Remove debug flag again once we are sure that re-initialising the integrator
# doesn't cause a performance overhead.
def reinit_integrator(self, debug=True):
"""
If an integrator is already present in the simulation, call
its reinit() method. Otherwise do nothing.
"""
if self.has_integrator():
self.integrator.reinit(debug=debug)
else:
log.warning("Integrator reinit was requested, but no integrator "
"is present in the simulation!")
def set_stt(self, current_density, polarisation, thickness, direction,
Lambda=2, epsilonprime=0.0, with_time_update=None):
"""
Activate the computation of the Slonczewski spin-torque term
in the LLG.
*Arguments*
- Current density in A/m^2 as a number, dolfin function or expression.
- Polarisation is between 0 and 1. It is defined as P = (x-y)/(x+y),
where x and y are the fractions of spin up/down electrons).
- Thickness of the free layer in m.
- Direction of the polarisation as a triple (is automatically
normalised to unit length).
- Lambda: the Lambda parameter in the Slonczewski/Xiao spin-torque term
- epsilonprime: the strength of the secondary spin transfer term
- with_time_update:
A function of the form J(t), which accepts a time step `t`
as its only argument and returns the new current density.
N.B.: For efficiency reasons, the return value is currently
assumed to be a number, i.e. J is assumed to be spatially
constant (and only varying with time).
"""
self.llg.use_slonczewski(current_density, polarisation, thickness,
direction, Lambda=Lambda, epsilonprime=epsilonprime,
with_time_update=with_time_update)
def toggle_stt(self, new_state=None):
"""
Toggle the computation of the Slonczewski spin-torque term.
You can optionally pass in a new state.
"""
if new_state:
self.llg.do_slonczewski = new_state
else:
self.llg.do_slonczewski = not self.llg.do_slonczewski
def clear_schedule(self):
self.scheduler.clear()
self.scheduler.reset(self.t)
def schedule(self, func, *args, **kwargs):
"""
Register a function that should be called during the simulation.
To un-schedule this function later, store the return value `item`
of this function and call sim.unschedule(item) later. Alternatively,
you can call `sim.clear_schedule`, which unregisters *all* scheduled
functions.
By default, the schedule operates on simulation time expressed in
seconds. Use either the `at` keyword argument to define a single
point in time at which your function is called, or use the `every`
keyword to specify an interval between subsequent calls to your
function. When specifying the interval, you can optionally use the
`after` keyword to delay the first execution of your function.
Additionally, you can set the `at_end` option to `True` (default
is `False`) to have your function called at the end of a simulation
stage (e.g. when the run_until() command has reached its end time,
or when the relax() command has reached relaxation). This can be
combined with `at` and `every`.
Note that if the internal simulation time is not zero (i.e.. if the
simulation has already run for some time) then using the 'every'
keyword will implicitly set 'after' to the current simulation time,
so that the event repeats in regular intervals from the current time
onwards). If this is undesired, you should explicitly provide 'after'
(which is interpreted as an 'absolute' time, i.e. not as an offset to
the current simulation time).
You can also schedule actions using real time instead of simulation
time by setting the `realtime` option to True. In this case you can
use the `after` keyword on its own.
The function func(sim) you provide should expect the simulation object
as its first argument. All arguments to the 'schedule' function (except
the special ones 'at', 'every', 'at_end' and 'realtime' mentioned
above) will be passed on to this function.
If func is a string, it will be looked up in self.scheduler_shortcuts,
which includes 'save_restart_data', 'save_ndt', 'save_vtk' and
'save_field'. For example, to save a vtk snapshot of the magnetisation
every nanosecond, use:
sim.schedule('save_vtk', every=1e-9, filename='m.pvd')
and to save the magnetisation to a .npy file every 2 nanoseconds, use:
sim.schedule('save_field', 'm', every=2e-9, filename='m.npy')
In both of these cases, a suffix representing the number of
the current snapshot will be added automatically, e.g.:
'm_00000.npy', 'm_000001.npy', etc.
"""
if isinstance(func, str):
if func in self.scheduler_shortcuts:
if func == 'save_vtk':
# This is a special case which needs some pre-processing
# as we need to open a .pvd file first.
filename = kwargs.pop('filename', None)
overwrite = kwargs.pop('overwrite', False)
try:
# Check whether a vtk_saver for this filename already exists; this is
# necessary to if 'save_vtk' is scheduled multiple times with the same
# filename.
vtk_saver = self._get_vtk_saver(
filename=filename, overwrite=False)
except IOError:
# If none exists, create a new one.
vtk_saver = self._get_vtk_saver(
filename=filename, overwrite=overwrite)
def aux_save(sim):
sim_savers._save_m_to_vtk(vtk_saver)
func = aux_save
func = lambda sim: sim_savers._save_m_to_vtk(sim, vtk_saver)
elif func == "eta" or func == "ETA":
eta = self.scheduler_shortcuts[func]
started = time.time()
func = lambda sim: eta(sim, when_started=started)
else:
func = self.scheduler_shortcuts[func]
else:
msg = "Scheduling keyword '%s' unknown. Known values are %s" \
% (func, self.scheduler_shortcuts.keys())
log.error(msg)
raise KeyError(msg)
try:
func_args = inspect.getargspec(func).args
except TypeError:
# This can happen when running the binary distribution, since compiled
# functions cannot be inspected. Not a great problem, though, because
# this will result in an error once the scheduled function is called,
# even though it would be preferable to catch this early.
func_args = None
if func_args != None:
illegal_argnames = ['at', 'after', 'every', 'at_end', 'realtime']
for kw in illegal_argnames:
if kw in func_args:
raise ValueError(
"The scheduled function must not use any of the following "
"argument names: {}".format(illegal_argnames))
at = kwargs.pop('at', None)
every = kwargs.pop('every', None)
after = kwargs.pop('after', self.t if (every != None) else None)
at_end = kwargs.pop('at_end', False)
realtime = kwargs.pop('realtime', False)
scheduled_item = self.scheduler.add(func, [self] + list(args), kwargs,
at=at, at_end=at_end, every=every,
after=after, realtime=realtime)
return scheduled_item
def unschedule(self, item):
"""
Unschedule a previously scheduled callback function. The
argument `item` should be the object returned by the call to
sim.schedule(...) which scheduled that function.
"""
self.scheduler._remove(item)
def snapshot(self, filename="", directory="", force_overwrite=False):
"""
Deprecated. Use 'save_vtk' instead.
"""
log.warning("Method 'snapshot' is deprecated. Use 'save_vtk' instead.")
self.vtk(self, filename, directory, force_overwrite)
def _get_vtk_saver(self, filename=None, overwrite=False):
if filename == None:
filename = self.sanitized_name + '.pvd'
if self.vtk_savers.has_key(filename) and (overwrite == False):
# Retrieve an existing VTKSaver for appending data
s = self.vtk_savers[filename]
else:
# Create a new VTKSaver and store it for later re-use
s = VTKSaver(filename, overwrite=overwrite)
self.vtk_savers[filename] = s
return s
save_m = sim_helpers.save_m
save_field = sim_savers.save_field
save_vtk = sim_savers.save_vtk
save_field_to_vtk = sim_savers.save_field_to_vtk
length_scales = sim_details.length_scales
mesh_info = sim_details.mesh_info
def render_scene(self, outfile=None, region=None, **kwargs):
"""
This is a convenience wrapper around the helper function
`finmag.util.visualization.render_paraview_scene`. It saves
the current magnetisation to a temporary file and uses
`render_paraview_scene` to plot it. All keyword arguments
are passed on to `render_paraview_scene`; see its docstring
for details (one useful option is `outfile`, which can be used
to save the resulting image to a png or jpg file).
Returns the IPython.core.display.Image produced by
`render_paraview_scene`.
"""
from finmag.util.visualization import render_paraview_scene
field_name = kwargs.get('field_name', 'm')
with helpers.TemporaryDirectory() as tmpdir:
filename = os.path.join(
tmpdir, 'paraview_scene_{}.pvd'.format(self.name))
self.save_field_to_vtk(
field_name=field_name, filename=filename, region=region)
return render_paraview_scene(filename, outfile=outfile, **kwargs)
def _render_scene_incremental(self, filename, **kwargs):
# XXX TODO: This should be tidied up by somehow combining it
# with the other incremental savers. We should have a more
# general mechanism which abstracts out the functionality of
# incremental saving.
try:
cur_index = self._render_scene_indices[filename]
except KeyError:
self._render_scene_indices[filename] = 0
cur_index = 0
basename, ext = os.path.splitext(filename)
outfilename = basename + '_{:06d}'.format(cur_index) + ext
self.render_scene(outfile=outfilename, **kwargs)
self._render_scene_indices[filename] += 1
def plot_mesh(self, region=None, use_paraview=True, **kwargs):
"""
Plot the mesh associated with the given region (or the entire mesh
if `region` is `None`).
This is a convenience function which internally calls either
`finmag.util.helpers.plot_mesh_with_paraview` (if the argument
`use_paraview` is True) or `finmag.util.hepers.plot_mesh`
(otherwise), where the latter uses Matplotlib to plot the mesh.
All keyword arguments are passed on to the respective helper
function that is called internally.
"""
mesh = self.get_submesh(region)
if use_paraview:
return plot_mesh_with_paraview(mesh, **kwargs)
else:
return plot_mesh(mesh, **kwargs)
def close_logfile(self):
"""
Stop logging to the logfile associated with this simulation object.
This closes the file and removed the associated logging
handler from the 'finmag' logger. Note that logging to other
files (in particular the global logfile) is not affected.
"""
if hasattr(self.logging_handler, 'stream'):
log.info("Closing logging_handler {} for sim object {}".format(self.logging_handler, self.name))
self.logging_handler.stream.close()
log.removeHandler(self.logging_handler)
self.logging_handler = None
else:
log.info("No stream found for logging_handler {} for sim object {}".format(self.logging_handler, self.name))
def plot_dynamics(self, components='xyz', **kwargs):
from finmag.util.plot_helpers import plot_dynamics
ndt_file = kwargs.pop('ndt_file', self.ndtfilename)
if not os.path.exists(ndt_file):
raise RuntimeError(
"File was not found: '{}'. Did you forget to schedule saving the averages to a .ndt file before running the simulation?".format(ndt_file))
return plot_dynamics(ndt_file, components=components, **kwargs)
def plot_dynamics_3d(self, **kwargs):
from finmag.util.plot_helpers import plot_dynamics_3d
ndt_file = kwargs.pop('ndt_file', self.ndtfilename)
if not os.path.exists(ndt_file):
raise RuntimeError(
"File was not found: '{}'. Did you forget to schedule saving the averages to a .ndt file before running the simulation?".format(ndt_file))
return plot_dynamics_3d(ndt_file, **kwargs)
def mark_regions(self, fun_regions):
"""
Mark certain subdomains of the mesh.
The argument `fun_regions` should be a callable of the form
(x, y, z) --> region_id
which takes the coordinates of a mesh point as input and returns
the region_id for this point. Here `region_id` can be anything
(it doesn't need to be an integer).
"""
from distutils.version import LooseVersion
if LooseVersion(df.__version__) >= LooseVersion('1.5.0'):
raise RuntimeError("Marking mesh regions is currently not supported with dolfin >= 1.5 due to an API change with respect to 1.4.")
# Determine all region identifiers and associate each of them with a unique integer.
# XXX TODO: This is probably quite inefficient since we loop over all mesh nodes.
# Can this be improved?
all_ids = set([fun_regions(pt) for pt in self.mesh.coordinates()])
self.region_ids = dict(itertools.izip(all_ids, xrange(len(all_ids))))
# Create the CellFunction which marks the different mesh regions with
# integers
self.region_markers = df.CellFunction('size_t', self.mesh)
for region_id, i in self.region_ids.items():
class Domain(df.SubDomain):
def inside(self, pt, on_boundary):
return fun_regions(pt) == region_id
subdomain = Domain()
subdomain.mark(self.region_markers, i)
def create_restricted_space(region_id):
i = self.region_ids[region_id]
restriction = df.Restriction(self.region_markers, i)
V_restr = df.VectorFunctionSpace(restriction, 'CG', 1, dim=3)
return V_restr
# Create a restricted VectorFunctionSpace for each region
try:
self.region_spaces = {
region_id: create_restricted_space(region_id) for region_id in self.region_ids}
except AttributeError:
raise RuntimeError("Marking mesh regions is only supported for dolfin > 1.2.0. "
"You may need to install a nightly snapshot (e.g. via an Ubuntu PPA). "
"See http://fenicsproject.org/download/snapshot_releases.html for details.")
get_submesh = sim_helpers.get_submesh
def set_zhangli(self, J_profile=(1e10, 0, 0), P=0.5, beta=0.01, using_u0=False, with_time_update=None):
"""
Activates the computation of the zhang-li spin-torque term in the LLG.
*Arguments*
`J_profile` can have any of the forms accepted by the function
'finmag.util.helpers.vector_valued_function' (see its
docstring for details).
if using_u0 = True, the factor of 1/(1+beta^2) will be dropped.
"""
self.llg.use_zhangli(
J_profile=J_profile, P=P, beta=beta, using_u0=using_u0, with_time_update=with_time_update)
def profile(self, statement, filename=None, N=20, sort='cumulative'):
"""
Profile execution of the given statement and display timing
results of the `N` slowest functions. The statement should
be in exactly the same form as if the function was called on
the simulation object directly. Examples:
sim.profile('relax()')
sim.profile('run_until(1e-9)')
The profiling results are saved to a file with name `filename`
(default: 'SIMULATION_NAME.prof'). You can call 'runsnake' on
the generated file to visualise the profiled results in a
graphical way.
"""
if filename is None:
filename = self.name + '.prof'
cProfile.run('sim.' + statement, filename=filename, sort=sort)
p = pstats.Stats(filename)
p.sort_stats(sort).print_stats(N)
log.info("Saved profiling results to file '{filename}'. "
"Call 'runsnake {filename}' to visualise the data "
"in a graphical way.".format(filename=filename))
def sim_with(mesh, Ms, m_init, alpha=0.5, unit_length=1, integrator_backend="sundials",
A=None, K1=None, K1_axis=None, H_ext=None, demag_solver='FK', demag_solver_type=None,
nx=None, ny=None, spacing_x=None, spacing_y=None, demag_solver_params={}, D=None,
name="unnamed", pbc=None, sim_class=Simulation):
"""
Create a Simulation instance based on the given parameters.
This is a convenience function which allows quick creation of a
common simulation type where at most one exchange/anisotropy/demag
interaction is present and the initial magnetisation is known.
By default, a generic Simulation object will be returned, but the
argument `sim_class` can be used to create a more
specialised type of simulation, e.g. a NormalModeSimulation.
If a value for any of the optional arguments A, K1 (and K1_axis),
or demag_solver are provided then the corresponding exchange /
anisotropy / demag interaction is created automatically and added
to the simulation. For example, providing the value A=13.0e-12 in
the function call is equivalent to:
exchange = Exchange(A)
sim.add(exchange)
The arguments `nx`, `ny`, `spacing_x`, `spacing_y` refer to the Demag
interaction. If specified, they allow to create a "macro-geometry"
where the demag field is computed as if there were repeated copies
of the mesh present on either side of the sample. The copies are
assumed to be arranged in a grid with `nx` tiles in x-direction and
`ny` tiles in y-direction, with the actual simulation tile in the
centre (in particular, both `nx` and `ny` should be odd numbers; by
default they are both 1). The spacing between neighbouring tiles is
specified by `spacing_x` and `spacing_y` (default: the tiles touch
with no gap between them).
The argument `demag_solver_params` can be used to configure the demag solver
(if the chosen solver class supports this). Example with the 'FK' solver:
demag_solver_params = {'phi_1_solver': 'cg', phi_1_preconditioner: 'ilu'}
See the docstring of the individual solver classes (e.g. finmag.energies.demag.FKDemag)
for more information on possible parameters.
"""
sim = sim_class(mesh, Ms, unit_length=unit_length,
integrator_backend=integrator_backend,
name=name, pbc=pbc)
sim.set_m(m_init)
sim.alpha = alpha
# If any of the optional arguments are provided, initialise
# the corresponding interactions here:
if A is not None:
sim.add(Exchange(A))
if (K1 != None and K1_axis is None) or (K1 is None and K1_axis != None):
log.warning(
"Not initialising uniaxial anisotropy because only one of K1, "
"K1_axis was specified (values given: K1={}, K1_axis={}).".format(
K1, K1_axis))
if K1 != None and K1_axis != None:
sim.add(UniaxialAnisotropy(K1, K1_axis))
if H_ext != None:
sim.add(Zeeman(H_ext))
if D != None:
sim.add(DMI(D))
if demag_solver != None:
mg = MacroGeometry(nx=nx, ny=ny, dx=spacing_x, dy=spacing_y)
demag = Demag(solver=demag_solver, macrogeometry=mg,
solver_type=demag_solver_type, parameters=demag_solver_params)
sim.add(demag)
else:
log.debug("Not adding demag to simulation '{}'".format(sim.name))
log.debug("Successfully created simulation '{}'".format(sim.name))
return sim
# Instance accounting
"""28 March 2015: running jenkins tests has started to fail some weeks
ago wiht an error message about too many open files. We find that the
simulation specific log-handler files are not closed. If we run many
simulations in the same python session, the number of open files
increases. It is not clear whether this is the problem, but that is the current working assumption.
Part of the problem is that self.close_logfile() is never called, and
thus the file is not closed.
As part of the investigation, we found that the simulation objects
also are not garbage collected. [Marijan reported memory problems when
he has many simulation objects created in a for-loop.] This is due to
other references to the simulation object existing when it goes out of
scope. For example, the Table writer functions have a reference to the
simulation object. We thus have cyclic references, and therefore the
garbage collection never removes the simulation objects, and thus
__del__(self) is never called.
As long as we stick to passing a reference to the simulation object
around in our code, we can not close the logfile automatically in the
__del__ method, because the delete method never executes due to the
cyclic references. We want to stick to using references to the
simulation object as this is very convenient and allows writing the
most generic code (i.e. use user-defined functions that get the
simulation object passed as an argument).
Sticking to this approach, we need an additional function to 'delete'
the simulation object. What this actually needs to do is to remove the
cyclic references so that the object can be garbage collected when it
goes out of scope. (The same function might as well close the logfile
handler, thus addressing the original problem.)
This commit introduced a method Simulation.shutdown() which provides
this functionality and (at least for simple examples) removes cyclic
references from the simulation object.
It also provides other goodies that will hopefully allow us to monitor
the existence of 'un-garbage-collected' simulation objects, and
convenience functions to shut them down, for example as part of our
test suite. This is hopeful thinking at the moment and needs more
testing to see that it delivers.
"""
| 60,159 | 39.026613 | 154 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim_savers.py
|
import finmag
from finmag.util.vtk_saver import VTKSaver
from finmag.util.fileio import FieldSaver
#-------------------------------------------------------------------------
# npy savers
#-------------------------------------------------------------------------
def _save_field_incremental(sim, field_name, filename=None, overwrite=False):
save_field(
sim, field_name, filename, incremental=True, overwrite=overwrite)
def _save_m_incremental(sim, filename=None, overwrite=False):
save_field(sim, 'm', filename, incremental=True, overwrite=overwrite)
def _get_field_saver(sim, field_name, filename=None, overwrite=False, incremental=False):
if filename is None:
filename = '{}_{}.npy'.format(sim.sanitized_name, field_name.lower())
if not filename.endswith('.npy'):
filename += '.npy'
s = None
if sim.field_savers.has_key(filename) and sim.field_savers[filename].incremental == incremental:
s = sim.field_savers[filename]
if s is None:
s = FieldSaver(filename, overwrite=overwrite, incremental=incremental)
sim.field_savers[filename] = s
return s
def save_field(sim, field_name, filename=None, incremental=False, overwrite=False, region=None):
"""
Save the given field data to a .npy file.
*Arguments*
field_name : string
The name of the field to be saved. This should be either 'm'
or the name of one of the interactions present in the
simulation (e.g. Demag, Zeeman, Exchange, UniaxialAnisotropy).
filename : string
Output filename. If not specified, a default name will be
generated automatically based on the simulation name and the
name of the field to be saved. If a file with the same name
already exists, an exception of type IOError will be raised.
incremental : bool
region:
Some identifier that uniquely identifies a mesh region. This required
that the method `mark_regions` has been called previously so that the
simulation knows about the regions and their IDs.
"""
field_data = sim.get_field_as_dolfin_function(field_name, region=region)
field_saver = _get_field_saver(
sim, field_name, filename, incremental=incremental, overwrite=overwrite)
field_saver.save(field_data.vector().array())
#-------------------------------------------------------------------------
# Scene rendering
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
# VTK savers
#-------------------------------------------------------------------------
def _save_m_to_vtk(sim, vtk_saver):
vtk_saver.save_field(sim.llg._m_field.f, sim.t)
def _save_field_to_vtk(sim, field_name, vtk_saver, region=None):
field_data = sim.get_field_as_dolfin_function(
field_name, region=region)
field_data.rename(field_name, field_name)
vtk_saver.save_field(field_data, sim.t)
def save_vtk(sim, filename=None, overwrite=False, region=None):
"""
Save the magnetisation to a VTK file.
"""
sim.save_field_to_vtk(
'm', filename=filename, overwrite=overwrite, region=region)
def save_field_to_vtk(sim, field_name, filename=None, overwrite=False, region=None):
"""
Save the field with the given name to a VTK file.
"""
vtk_saver = sim._get_vtk_saver(filename=filename, overwrite=overwrite)
_save_field_to_vtk(sim, field_name, vtk_saver, region=region)
| 3,517 | 33.490196 | 100 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim_helpers_test.py
|
import os
import pytest
import numpy as np
import dolfin as df
import sim_helpers
from datetime import datetime, timedelta
from distutils.version import LooseVersion
from finmag import Simulation
from finmag.example import barmini
from finmag.util.meshes import nanodisk
from finmag.drivers.llg_integrator import llg_integrator
from finmag.util.helpers import assert_number_of_files
from finmag.util.fileio import Tablereader
def test_can_read_restart_file(tmpdir):
os.chdir(str(tmpdir))
sim = barmini()
sim.run_until(1e-21) # create integrator
sim_helpers.save_restart_data(sim)
data = sim_helpers.load_restart_data(sim)
assert data['simname'] == sim.name
assert data['simtime'] == sim.t
assert data['stats'] == sim.integrator.stats()
assert np.all(data['m'] == sim.integrator.llg.m_numpy)
# writing and reading the data should take less than 10 seconds
assert datetime.now() - data['datetime'] < timedelta(0, 10)
def test_try_to_restart_a_simulation(tmpdir):
os.chdir(str(tmpdir))
t0 = 10e-12
t1 = 20e-12
# Create simulation, integrate until t0, save restart data,
# and integrate until t1.
sim1 = barmini()
sim1.run_until(t0)
print("Stats for sim1 at t = {} s:\n{}.".format(
sim1.t, sim1.integrator.stats()))
sim_helpers.save_restart_data(sim1)
sim1.run_until(t1)
print("Stats for sim1 at t = {} s:\n{}.".format(
sim1.t, sim1.integrator.stats()))
# Bring new simulation object into previously saved
# state (which is at t0)...
data = sim_helpers.load_restart_data(sim1)
sim2 = barmini()
sim2.set_m(data['m'])
sim2.integrator = llg_integrator(sim2.llg, sim2.llg.m_field,
backend=sim2.integrator_backend, t0=data['simtime'])
# ... and integrate until t1.
sim2.run_until(t1)
print("Stats for sim2 at t = {} s:\n{}.".format(
sim2.t, sim2.integrator.stats()))
# Check that we have the same data in both simulation objects.
print "Time for sim1: {} s, time for sim2: {} s.".format(sim1.t, sim2.t)
assert abs(sim1.t - sim2.t) < 1e-16
print "Average magnetisation for sim1:\n\t{}\nfor sim2:\n\t{}.".format(
sim1.m_average, sim2.m_average)
assert np.allclose(sim1.m, sim2.m, atol=5e-6, rtol=1e-8)
# Check that sim2 had less work to do, since it got the
# results up to t0 for free.
stats1 = sim1.integrator.stats()
stats2 = sim2.integrator.stats()
assert stats2['nsteps'] < stats1['nsteps']
def test_create_backup_if_file_exists():
# remove file
testfilename = 'tmp-testfile.txt'
if os.path.exists(testfilename):
os.remove(testfilename)
backupfilename = 'tmp-testfile.txt.backup'
if os.path.exists(backupfilename):
os.remove(backupfilename)
assert os.path.exists(testfilename) == False
assert os.path.exists(backupfilename) == False
# create file
os.system('echo "Hello World" > ' + testfilename)
assert os.path.exists(testfilename) == True
assert open(testfilename).readline()[:-1] == "Hello World"
assert os.path.exists(backupfilename) == False
sim_helpers.create_backup_file_if_file_exists(testfilename)
assert os.path.exists(backupfilename) == True
assert open(backupfilename).readline()[:-1] == "Hello World"
assert open(backupfilename).read() == open(testfilename).read()
def test_run_normal_modes_computation(tmpdir):
os.chdir(str(tmpdir))
sim = barmini(name='barmini')
# XXX TODO: Do we need stopping keywords?
#sim.run_normal_modes_computation(alpha_relax=1.0, alpha_precess=0.01, t_end=10e-9, save_ndt_every=1e-11, save_vtk_every=None, )
params_relax = {
'alpha': 1.0,
'H_ext': [1e3, 0, ],
'save_ndt_every': None,
'save_vtk_every': None,
'save_npy_every': None,
'save_relaxed_state': True,
'filename': None
}
params_precess = {
'alpha': 0.0,
'H_ext': [1e3, 0, 0],
't_end': 1e-10,
'save_ndt_every': 1e-11,
'save_vtk_every': 3e-11,
'save_npy_every': 2e-11,
'filename': None,
}
sim.run_normal_modes_computation(params_relax, params_precess)
# XXX TODO: We should change the filename of the .ndt file to 'barmini_precess.ndt'
# once different filenames for .ndt files are supported.
f = Tablereader('barmini.ndt')
ts, mx, my, mz = f['time', 'm_x', 'm_y', 'm_z']
assert(len(ts) == 11)
assert_number_of_files('*_relaxed.npy', 1)
assert_number_of_files('*_relaxed.pvd', 1)
assert_number_of_files('*_relaxed*.vtu', 1)
assert_number_of_files('*_precess.pvd', 1)
assert_number_of_files('*_precess*.vtu', 4)
assert_number_of_files('*_precess*.npy', 6)
def test_create_non_existing_parent_directories(tmpdir):
os.chdir(str(tmpdir))
dirs = ['foo1/bar',
os.path.join(str(tmpdir), 'foo2', 'bar', 'baz'),
'',
os.curdir]
for d in dirs:
sim_helpers.create_non_existing_parent_directories(
os.path.join(d, 'filename.txt'))
assert(os.path.exists(os.path.abspath(d)))
def test_save_restart_data_creates_non_existing_directories(tmpdir):
os.chdir(str(tmpdir))
sim = barmini()
sim.run_until(0.0)
sim.save_restart_data('foo/restart_data.npz')
assert(os.path.exists('foo'))
@pytest.mark.xfail(reason='dolfin 1.5')
def test_get_submesh(tmpdir):
os.chdir(str(tmpdir))
sim = barmini(mark_regions=True)
mesh_full = sim.get_submesh(None)
mesh_top = sim.get_submesh('top')
mesh_bottom = sim.get_submesh('bottom')
with pytest.raises(ValueError):
mesh_full = sim.get_submesh('foo')
id_top = sim.region_ids['top']
id_bottom = sim.region_ids['bottom']
submesh_top = df.SubMesh(sim.mesh, sim.region_markers, id_top)
submesh_bottom = df.SubMesh(sim.mesh, sim.region_markers, id_bottom)
assert(mesh_full.num_vertices() == sim.mesh.num_vertices())
assert(mesh_top.num_vertices() == submesh_top.num_vertices())
assert(mesh_bottom.num_vertices() == submesh_bottom.num_vertices())
def test_skyrmion_number():
"""
Test to see if the skyrmion number density function helper integrated over
a mesh yields the same result as the skyrmion number function itself. Also
test that they both give sane values by testing on a system with a finite
number of skyrmions.
"""
# Create simulation object with four skyrmions in it.
mesh = df.RectangleMesh(df.Point(-100, -100), df.Point(100, 100), 50, 50)
sim = Simulation(mesh, 1e5, unit_length=1e-9)
skCentres = np.array([[0, 0], [-50, 70], [40, -80], [70, 70]])
sim.initialise_skyrmions(skyrmionRadius=30, centres=skCentres)
# Obtain skyrmion number and skyrmion number density, and test them.
skX = sim.skyrmion_number()
skX_density_function = sim.skyrmion_number_density_function()
skX_integral = df.assemble(skX_density_function * df.dx)
assert(abs(skX - skX_integral) < 1e-10)
assert(abs(skX - 4) < 3e-1) # There are four skyrmions here...
# Repeat for a 3D mesh
mesh3D = df.BoxMesh(df.Point(-100, -100, -5), df.Point(100, 100, 5), 50, 50, 5)
sim3D = Simulation(mesh3D, 1e5, unit_length=1e-9)
skCentres3D = np.array(
[[0, 0, 0], [-50, 70, 0], [40, -80, 0], [70, 70, 0]])
sim3D.initialise_skyrmions(skyrmionRadius=30, centres=skCentres3D)
skX_3D = sim3D.skyrmion_number()
assert(abs(skX_3D - 4) < 4e-1) # There are four skyrmions here...
# Test using another geometry (a nanodisk)
meshNanodisk = nanodisk(d=100, h=10, maxh=3.0, save_result=False)
simNanodisk = Simulation(meshNanodisk, Ms=1e5, unit_length=1e-9)
# Initialise with a theoretical skyrmion, which should have skyrmion number as 1.
simNanodisk.initialise_skyrmions(skyrmionRadius=50)
skX_nanodisk = simNanodisk.skyrmion_number()
assert(abs(skX_nanodisk - 1) < 5e-2)
| 7,978 | 34.780269 | 132 |
py
|
finmag
|
finmag-master/src/finmag/sim/normal_mode_sim.py
|
import os
import re
import types
import logging
import numpy as np
import dolfin as df
from finmag.sim.sim import Simulation, sim_with
from finmag.normal_modes.eigenmodes import eigensolvers
from finmag.util import helpers
from finmag.util.fft import \
compute_power_spectral_density, find_peak_near_frequency, _plot_spectrum, \
export_normal_mode_animation_from_ringdown
from finmag.normal_modes.deprecated.normal_modes_deprecated import \
compute_eigenproblem_matrix, compute_generalised_eigenproblem_matrices, \
export_normal_mode_animation, plot_spatially_resolved_normal_mode, \
compute_tangential_space_basis, mf_mult
from past.builtins import basestring
log = logging.getLogger(name="finmag")
class NormalModeSimulation(Simulation):
"""
Thin wrapper around the Simulation class to make normal mode
computations using the ringdown method more convenient.
"""
def __init__(self, *args, **kwargs):
super(NormalModeSimulation, self).__init__(*args, **kwargs)
# Internal variables to store parameters/results of the ringdown method
self.m_snapshots_filename = None
self.t_step_ndt = None
self.t_step_m = None
# The following are used to cache computed spectra (potentially for
# various mesh regions)
self.psd_freqs = {}
self.psd_mx = {}
self.psd_my = {}
self.psd_mz = {}
# Internal variables to store parameters/results of the (generalised)
# eigenvalue method
self.eigenfreqs = None
self.eigenvecs = None
# Internal variables to store the matrices which define the generalised
# eigenvalue problem
self.A = None
self.M = None
self.D = None
# XXX TODO: Remove me once we get rid of the option 'use_real_matrix'
self.use_real_matrix = None
# in the method 'compute_normal_modes()' below.
# Define a few eigensolvers which can be conveniently accesses using
# strings
self.predefined_eigensolvers = {
'scipy_dense': eigensolvers.ScipyLinalgEig(),
'scipy_sparse': eigensolvers.ScipySparseLinalgEigs(sigma=0.0, which='LM'),
'slepc_krylovschur': eigensolvers.SLEPcEigensolver(
problem_type='GNHEP', method_type='KRYLOVSCHUR', which='SMALLEST_MAGNITUDE')
}
def run_ringdown(self, t_end, alpha, H_ext=None, reset_time=True, clear_schedule=True,
save_ndt_every=None, save_vtk_every=None, save_m_every=None,
vtk_snapshots_filename=None, m_snapshots_filename=None,
overwrite=False):
"""
Run the ringdown phase of a normal modes simulation, optionally saving
averages, vtk snapshots and magnetisation snapshots to the respective
.ndt, .pvd and .npy files. Note that by default existing snapshots will
not be overwritten. Use `overwrite=True` to achieve this.
Also note that `H_ext=None` has the same effect as `H_ext=[0, 0, 0]`, i.e.
any existing external field will be switched off during the ringdown phase.
If you would like to have a field applied during the ringdown, you need to
explicitly provide it.
This function essentially wraps up the re-setting of parameters such as
the damping value, the external field and the scheduled saving of data
into a single convenient function call, thus making it less likely to
forget any settings.
The following snippet::
sim.run_ringdown(t_end=10e-9, alpha=0.02, H_ext=[1e5, 0, 0],
save_m_every=1e-11, m_snapshots_filename='sim_m.npy',
save_ndt_every=1e-12)
is equivalent to::
sim.clear_schedule()
sim.alpha = 0.02
sim.reset_time(0.0)
sim.set_H_ext([1e5, 0, 0])
sim.schedule('save_ndt', every=save_ndt_every)
sim.schedule('save_vtk', every=save_vtk_every, filename=vtk_snapshots_filename)
sim.run_until(10e-9)
"""
if reset_time:
self.reset_time(0.0)
if clear_schedule:
self.clear_schedule()
self.alpha = alpha
if H_ext == None:
if self.has_interaction('Zeeman'):
log.warning("Found existing Zeeman field (for the relaxation "
"stage). Switching it off for the ringdown. "
"If you would like to keep it, please specify the "
"argument 'H_ext' explicitly.")
self.set_H_ext([0, 0, 0])
else:
self.set_H_ext(H_ext)
if save_ndt_every:
self.schedule('save_ndt', every=save_ndt_every)
log.debug("Setting self.t_step_ndt = {}".format(save_ndt_every))
self.t_step_ndt = save_ndt_every
def schedule_saving(which, every, filename, default_suffix):
try:
dirname, basename = os.path.split(filename)
if dirname != '' and not os.path.exists(dirname):
os.makedirs(dirname)
except AttributeError:
dirname = os.curdir
basename = self.name + default_suffix
outfilename = os.path.join(dirname, basename)
self.schedule(
which, every=every, filename=outfilename, overwrite=overwrite)
if which == 'save_m':
# Store the filename so that we can later compute normal modes
# more conveniently
self.m_snapshots_filename = outfilename
if save_vtk_every:
schedule_saving(
'save_vtk', save_vtk_every, vtk_snapshots_filename, '_m.pvd')
if save_m_every:
schedule_saving(
'save_m', save_m_every, m_snapshots_filename, '_m.npy')
log.debug("Setting self.t_step_m = {}".format(save_m_every))
self.t_step_m = save_m_every
self.t_ini_m = self.t
self.t_end_m = t_end
self.run_until(t_end)
def _compute_spectrum(self, use_averaged_m=False, mesh_region=None, **kwargs):
try:
if self.psd_freqs[mesh_region, use_averaged_m] != None and \
self.psd_mx[mesh_region, use_averaged_m] != None and \
self.psd_my[mesh_region, use_averaged_m] != None and \
self.psd_mz[mesh_region, use_averaged_m] != None:
# We can use the cached results since the spectrum was computed
# before.
return
except KeyError:
# No computations for these values of (mesh_region,
# use_averaged_m) have been performed before. We're going
# to do them below.
pass
if use_averaged_m:
log.warning("Using the averaged magnetisation to compute the "
"spectrum is not recommended because this is likely "
"to miss certain symmetric modes.")
if mesh_region != None:
# TODO: we might still be able to compute this if the
# user saved the averaged magnetisation in the
# specified region to the .ndt file. We should check that.
log.warning("Ignoring argument 'mesh_region' because "
"'use_averaged_m' was set to True.")
filename = self.ndtfilename
else:
if self.m_snapshots_filename is None:
log.warning(
"The spatially averaged magnetisation was not saved "
"during run_ringdown, thus it cannot be used to compute "
"the spectrum. Falling back to using the averaged "
"magnetisation (which is not recommended because it "
"is likely to miss normal modes which have certain "
"symmetries!).")
if mesh_region != None:
log.warning("Ignoring argument 'mesh_region' because the "
"spatially resolved magnetisation was not "
"saved during the ringdown.")
filename = self.ndtfilename
else:
# Create a wildcard pattern so that we can read the files using
# 'glob'.
filename = re.sub('\.npy$', '*.npy', self.m_snapshots_filename)
log.debug(
"Computing normal mode spectrum from file(s) '{}'.".format(filename))
# Derive a sensible value of t_step, t_ini and t_end. Use the value
# in **kwargs if one was provided, or else the one specified (or
# derived) during a previous call of run_ringdown().
t_step = kwargs.pop('t_step', None)
t_ini = kwargs.pop('t_ini', None)
t_end = kwargs.pop('t_end', None)
if t_step == None:
if use_averaged_m:
t_step = self.t_step_ndt
else:
t_step = self.t_step_m
if t_ini == None and not use_averaged_m:
t_ini = self.t_ini_m
if t_end == None and not use_averaged_m:
t_end = self.t_end_m
# XXX TODO: Use t_step_npy if computing the spectrum from .npy files.
if t_step == None:
raise ValueError(
"No sensible default for 't_step' could be determined. "
"(It seems like 'run_ringdown()' was not run, or it was not "
"given a value for its argument 'save_ndt_every'). Please "
"call sim.run_ringdown() or provide the argument 't_step' "
"explicitly.")
if mesh_region != None:
# If a mesh region is specified, restrict computation of the
# spectrum to the corresponding mesh vertices.
submesh = self.get_submesh(mesh_region)
try:
# Legacy syntax (for dolfin <= 1.2 or so).
# TODO: This should be removed in the future once dolfin 1.3 is
# released!
parent_vertex_indices = submesh.data().mesh_function(
'parent_vertex_indices').array()
except RuntimeError:
# This is the correct syntax now, see:
# http://fenicsproject.org/qa/185/entity-mapping-between-a-submesh-and-the-parent-mesh
parent_vertex_indices = submesh.data().array(
'parent_vertex_indices', 0)
kwargs['restrict_to_vertices'] = parent_vertex_indices
psd_freqs, psd_mx, psd_my, psd_mz = \
compute_power_spectral_density(
filename, t_step=t_step, t_ini=t_ini, t_end=t_end, **kwargs)
self.psd_freqs[mesh_region, use_averaged_m] = psd_freqs
self.psd_mx[mesh_region, use_averaged_m] = psd_mx
self.psd_my[mesh_region, use_averaged_m] = psd_my
self.psd_mz[mesh_region, use_averaged_m] = psd_mz
def plot_spectrum(self, t_step=None, t_ini=None, t_end=None, subtract_values='first',
components="xyz", log=False, xlim=None, ticks=5, figsize=None, title="",
outfilename=None, use_averaged_m=False, mesh_region=None):
"""
Plot the normal mode spectrum of the simulation. If
`mesh_region` is not None, restricts the computation to mesh
vertices in that region (which must have been specified with
`sim.mark_regions` before).
This is a convenience wrapper around the function
finmag.util.fft.plot_power_spectral_density. It accepts the
same keyword arguments, but provides sensible defaults for
some of them so that it is more convenient to use. For
example, `ndt_filename` will be the simulation's .ndt file by
default, and t_step will be taken from the value of the
argument `save_ndt_every` when sim.run_ringdown() was run.
The default method to compute the spectrum is the one described
in [1], which uses a spatially resolved Fourier transform
to compute the local power spectra and then integrates these over
the sample (which yields the total power over the sample at each
frequency). This is the recommended way to compute the spectrum,
but it requires the spatially resolved magnetisation to be saved
during the ringdown (provide the arguments `save_m_every` and
`m_snapshots_filename` to `sim.run_ringdown()` to achieve this).
An alternative method (used when `use_averaged_m` is True) simply
computes the Fourier transform of the spatially averaged magnetisation
and plots that. However, modes with certain symmetries (which are
quite common) will not be detected by this method, so it is not
recommended to use it. It will be used as a fallback, however,
if the spatially resolved magnetisation was not saved during the
ringdown phase.
[1] McMichael, Stiles, "Magnetic normal modes of nanoelements", J Appl Phys 97 (10), 10J901, 2005.
"""
self._compute_spectrum(t_step=t_step, t_ini=t_ini, t_end=t_end,
subtract_values=subtract_values, use_averaged_m=use_averaged_m, mesh_region=mesh_region)
fig = _plot_spectrum(self.psd_freqs[mesh_region, use_averaged_m],
self.psd_mx[mesh_region, use_averaged_m],
self.psd_my[mesh_region, use_averaged_m],
self.psd_mz[mesh_region, use_averaged_m],
components=components, log=log, xlim=xlim,
ticks=ticks, figsize=figsize, title=title,
outfilename=outfilename)
return fig
def _get_psd_component(self, component, mesh_region, use_averaged_m):
try:
res = {'x': self.psd_mx[mesh_region, use_averaged_m],
'y': self.psd_my[mesh_region, use_averaged_m],
'z': self.psd_mz[mesh_region, use_averaged_m]
}[component]
except KeyError:
raise ValueError(
"Argument `component` must be exactly one of 'x', 'y', 'z'.")
return res
def find_peak_near_frequency(self, f_approx, component=None, use_averaged_m=False, mesh_region=None):
"""
XXX TODO: Write me!
The argument `use_averaged_m` has the same meaning as in the `plot_spectrum`
method. See its documentation for details.
"""
if component is None:
log.warning("Please specify the 'component' argument (which "
"determines the magnetization component in which "
"to search for a peak.")
return
if f_approx is None:
raise TypeError("Argument 'f_approx' must not be None.")
if not isinstance(component, types.StringTypes):
raise TypeError("Argument 'component' must be of type string.")
self._compute_spectrum(
use_averaged_m=use_averaged_m, mesh_region=mesh_region)
psd_cmpnt = self._get_psd_component(
component, mesh_region, use_averaged_m)
return find_peak_near_frequency(f_approx, self.psd_freqs[mesh_region, use_averaged_m], psd_cmpnt)
def find_all_peaks(self, component, use_averaged_m=False, mesh_region=None):
"""
Return a list all peaks in the spectrum of the given magnetization component.
"""
self._compute_spectrum(
use_averaged_m=use_averaged_m, mesh_region=mesh_region)
freqs = self.psd_freqs[mesh_region, use_averaged_m]
all_peaks = sorted(list(set([self.find_peak_near_frequency(
x, component=component, use_averaged_m=use_averaged_m, mesh_region=mesh_region) for x in freqs])))
return all_peaks
def plot_peak_near_frequency(self, f_approx, component, mesh_region=None, use_averaged_m=False, **kwargs):
"""
Convenience function for debugging which first finds a peak
near the given frequency and then plots the spectrum together
with a point marking the detected peak.
Internally, this calls `sim.find_peak_near_frequency` and
`sim.plot_spectrum()` and accepts all keyword arguments
supported by these two functions.
"""
peak_freq, peak_idx = self.find_peak_near_frequency(
f_approx, component, mesh_region=mesh_region)
psd_cmpnt = self._get_psd_component(
component, mesh_region, use_averaged_m)
fig = self.plot_spectrum(use_averaged_m=use_averaged_m, **kwargs)
fig.gca().plot(self.psd_freqs[mesh_region, use_averaged_m][
peak_idx] / 1e9, psd_cmpnt[peak_idx], 'bo')
return fig
def export_normal_mode_animation_from_ringdown(self, npy_files, f_approx=None, component=None,
peak_idx=None, outfilename=None, directory='',
t_step=None, scaling=0.2, dm_only=False,
num_cycles=1, num_frames_per_cycle=20,
use_averaged_m=False):
"""
XXX TODO: Complete me!
If the exact index of the peak in the FFT array is known, e.g.
because it was computed via `sim.find_peak_near_frequency()`,
then this can be given as the argument `peak_index`.
Otherwise, `component` and `f_approx` must be given and these
are passed on to `sim.find_peak_near_frequency()` to determine
the exact location of the peak.
The output filename can be specified via `outfilename`. If this
is None then a filename of the form 'normal_mode_N__xx.xxx_GHz.pvd'
is generated automatically, where N is the peak index and xx.xx
is the frequency of the peak (as returned by the function
`sim.find_peak_near_frequency()`).
*Arguments*:
f_approx: float
Find and animate peak closest to this frequency. This is
ignored if 'peak_idx' is given.
component: str
The component (one of 'x', 'y', 'z') of the FFT spectrum
which should be searched for a peak. This is ignored if
peak_idx is given.
peak_idx: int
The index of the peak in the FFT spectrum. This can be
obtained by calling `sim.find_peak_near_frequency()`.
Alternatively, if the arguments `f_approx` and `component`
are given then this index is computed automatically. Note
that if `peak_idx` is given the other two arguments are
ignored.
use_averaged_m: bool
Determines the method used to compute the spectrum. See
the method `plot_spectrum()` for details.
"""
self._compute_spectrum(use_averaged_m=use_averaged_m)
if peak_idx is None:
if f_approx is None or component is None:
raise ValueError(
"Please specify either 'peak_idx' or both 'f_approx' and 'component'.")
peak_freq, peak_idx = self.find_peak_near_frequency(
f_approx, component)
else:
if f_approx != None:
log.warning(
"Ignoring argument 'f_approx' because 'peak_idx' was specified.")
if component != None:
log.warning(
"Ignoring argument 'component' because 'peak_idx' was specified.")
# XXX TODO: Currently mesh regions are not supported, so we must
# use None here. Can we fix this?!?
peak_freq = self.psd_freqs[None, use_averaged_m][peak_idx]
if outfilename is None:
if directory is '':
raise ValueError(
"Please specify at least one of the arguments 'outfilename' or 'directory'")
outfilename = 'normal_mode_{}__{:.3f}_GHz.pvd'.format(
peak_idx, peak_freq / 1e9)
outfilename = os.path.join(directory, outfilename)
if t_step == None:
if (self.t_step_ndt != None) and (self.t_step_m != None) and \
(self.t_step_ndt != self.t_step_m):
log.warning(
"Values of t_step for previously saved .ndt and .npy data differ! ({} != {}). Using t_step_ndt, but please double-check this is what you want.".format(self.t_step_ndt, self.t_step_m))
t_step = t_step or self.t_step_ndt
export_normal_mode_animation_from_ringdown(npy_files, outfilename, self.mesh, t_step,
peak_idx, dm_only=dm_only, num_cycles=num_cycles,
num_frames_per_cycle=num_frames_per_cycle)
def assemble_eigenproblem_matrices(self, filename_mat_A=None, filename_mat_M=None, use_generalized=False,
force_recompute_matrices=False, check_hermitian=False,
differentiate_H_numerically=True, use_real_matrix=True):
if use_generalized:
if (self.A == None or self.M == None) or force_recompute_matrices:
df.tic()
self.A, self.M, _, _ = compute_generalised_eigenproblem_matrices(
self, frequency_unit=1e9, filename_mat_A=filename_mat_A, filename_mat_M=filename_mat_M,
check_hermitian=check_hermitian, differentiate_H_numerically=differentiate_H_numerically)
log.debug("Assembling the eigenproblem matrices took {}".format(
helpers.format_time(df.toc())))
else:
log.debug(
'Re-using previously computed eigenproblem matrices.')
else:
if self.D == None or (self.use_real_matrix != use_real_matrix) or force_recompute_matrices:
df.tic()
self.D = compute_eigenproblem_matrix(
self, frequency_unit=1e9, differentiate_H_numerically=differentiate_H_numerically,
dtype=(float if use_real_matrix else complex))
self.use_real_matrix = use_real_matrix
log.debug("Assembling the eigenproblem matrix took {}".format(
helpers.format_time(df.toc())))
else:
log.debug('Re-using previously computed eigenproblem matrix.')
def _extend_to_full_mesh(self, w):
"""
The argument `w` should be a vector representing a dolfin Function
on the mesh belonging to the simulation class. If we are using
periodic boundary conditions then `w` may have fewer elements than
there are mesh nodes (because some nodes will be identified). This
helper function extends `w` to a 'full' vector which has one element
for each mesh node.
"""
# XXX TODO: This is a mess; we should accept a dolfin Function instead of a numpy array w
# and extract its function space and dofmap from that directly. Or even better,
# this should all be handled in the Field class.
n = len(self.llg.S1.dofmap().dofs())
dim = len(w.ravel()) // n
assert(len(w.ravel()) == dim * n)
w.shape = (-1, n)
# XXX TODO: The following line assumes that a function with vector shape m x n has the
# same dofmap as one with shape 1 x n, which is probably not true in general.
# But hopefully this will be solved with the Field class.
v2d = df.vertex_to_dof_map(self.llg.S1)
w_extended = w[:, v2d[range(self.mesh.num_vertices())]]
return w_extended.ravel()
def compute_normal_modes(self, n_values=10, solver='scipy_sparse',
discard_negative_frequencies=True,
filename_mat_A=None, filename_mat_M=None,
use_generalized=False, force_recompute_matrices=False,
check_hermitian=False, differentiate_H_numerically=True,
use_real_matrix=True):
"""
Compute the eigenmodes of the simulation by solving a generalised
eigenvalue problem and return the computed eigenfrequencies and
eigenvectors. The simulation must be relaxed for this to yield
sensible results.
All keyword arguments not mentioned below are directly passed on
to `scipy.sparse.linalg.eigs`, which is used internally to solve
the generalised eigenvalue problem.
*Arguments*
n_values:
The number of eigenmodes to compute (returns the
`n_values` smallest ones).
solver:
The type of eigensolver to use. This should be an instance of
one of the Eigensolver classes defined in the module
`finmag.normal_modes.eigenmodes.eigensolvers`. For convenience,
there are also some predefined options which can be accessed
using the strings "scipy_dense", "scipy_sparse" and
"slepc_krylovschur".
Examples:
ScipyLinalgEig()
ScipySparseLinalgEigs(sigma=0.0, which='LM', tol=1e-8)
SLEPcEigensolver(problem_type='GNHEP', method_type='KRYLOVSCHUR', which='SMALLEST_MAGNITUDE', tol=1e-8, maxit=400)
discard_negative_frequencies:
For every eigenmode there is usually a corresponding mode
with the negative frequency which otherwise looks exactly
the same (at least in sufficiently symmetric situations).
If `discard_negative_frequencies` is True then these are
discarded. Use this at your own risk, however, since you
might miss genuinely different eigenmodes. Default is
False.
filename_mat_A:
filename_mat_M:
If given (default: None), the matrices A and M which
define the generalised eigenvalue problem are saved to
files with the specified names. This can be useful for
debugging or later post-processing to avoid having to
recompute these matrices.
use_generalized:
If True (default: False), compute the eigenmodes using the
formulation as a generalised eigenvalue problem instead of
an ordinary one.
force_recompute_matrices:
If False (the default), the matrices defining the
generalised eigenvalue problem are not recomputed if they
have been computed before (this dramatically speeds up
repeated computation of eigenmodes). Set to True to
force recomputation.
check_hermitian:
If True, check whether the matrix A used in the generalised
eigenproblem is Hermitian and print a warning if this is not
the case. This is a temporary debugging flag which is likely
to be removed again in the future. Default value: False.
differentiate_H_numerically:
If True (the default), compute the derivative of the effective
field numerically. If False, use a more efficient method. The
latter is much faster, but leads to numerical inaccuracies so
it is only recommended for testing large systems.
use_real_matrix:
This argument only applies if `use_generalised` is False. In this
case, if `use_real_matrix` is True (the default), passes a matrix
with real instead of complex entries to the solver. This is
recommended as it reduces the computation time considerably.
This option is for testing purposes only and will be removed in
the future.
*Returns*
A triple (omega, eigenvectors, rel_errors), where omega is a list of
the `n_values` smallest eigenfrequencies, `eigenvectors` is a rectangular
array whose rows are the corresponding eigenvectors (in the same order),
and rel_errors are the relative errors of each eigenpair, defined as
follows:
rel_err = ||A*v - omega*M*v||_2 / ||omega*v||_2
NOTE: Previously, the eigenvectors would be returned in the *columns*
of `w`, but this has changed in the interface!
"""
if isinstance(solver, basestring):
try:
solver = self.predefined_eigensolvers[solver]
except KeyError:
raise ValueError("Unknown eigensolver: '{}'".format(solver))
if use_generalized and isinstance(solver, eigensolvers.SLEPcEigensolver):
raise TypeError("Using the SLEPcEigensolver with a generalised "
"eigenvalue problemis not currently implemented.")
self.assemble_eigenproblem_matrices(
filename_mat_A=filename_mat_A, filename_mat_M=filename_mat_M, use_generalized=use_generalized,
force_recompute_matrices=force_recompute_matrices, check_hermitian=check_hermitian,
differentiate_H_numerically=differentiate_H_numerically, use_real_matrix=use_real_matrix)
if discard_negative_frequencies:
# If negative frequencies should be discarded, we need to compute
# twice as many as the user requested
n_values *= 2
if use_generalized:
# omega, eigenvecs = compute_normal_modes_generalised(self.A, self.M, n_values=n_values, discard_negative_frequencies=discard_negative_frequencies,
# tol=tol, sigma=sigma, which=which, v0=v0, ncv=ncv,
# maxiter=maxiter, Minv=Minv, OPinv=OPinv, mode=mode)
omega, eigenvecs, rel_errors = solver.solve_eigenproblem(
self.A, self.M, num=n_values)
else:
# omega, eigenvecs = compute_normal_modes(self.D, n_values, sigma=0.0, tol=tol, which='LM')
# omega = np.real(omega) # any imaginary part is due to numerical
# inaccuracies so we ignore them
omega, eigenvecs, rel_errors = solver.solve_eigenproblem(
self.D, None, num=n_values)
if use_real_matrix:
# Eigenvalues are complex due to the missing factor of 1j in
# the matrix with real entries. Here we correct for this.
omega = 1j * omega
eigenvecs_extended = np.array(
[self._extend_to_full_mesh(w) for w in eigenvecs])
eigenvecs = eigenvecs_extended
# Sanity check: frequencies should occur in +/- pairs
pos_freqs = filter(lambda x: x >= 0, omega)
neg_freqs = filter(lambda x: x <= 0, omega)
#kk = min(len(pos_freqs), len(neg_freqs))
for (freq1, freq2) in zip(pos_freqs, neg_freqs):
if not np.isclose(freq1.real, -freq2.real, rtol=1e-8):
log.error(
"Frequencies should occur in +/- pairs, but computed: {:f} / {:f}".format(freq1, freq2))
# Another sanity check: frequencies should be approximately real
for freq in omega:
if not abs(freq.imag / freq) < 1e-4:
log.warning(
'Frequencies should be approximately real, but computed: {:f}'.format(freq))
if discard_negative_frequencies:
pos_freq_indices = [
i for (i, freq) in enumerate(omega) if freq >= 0]
omega = omega[pos_freq_indices]
eigenvecs = eigenvecs[pos_freq_indices]
log.debug(
"Relative errors of computed eigensolutions: {}".format(rel_errors))
self.eigenfreqs = omega
self.eigenvecs = eigenvecs
self.rel_errors = rel_errors
return omega, eigenvecs, rel_errors
def export_eigenmode_animations(self, modes, dm_only=False, directory='', create_movies=True, directory_movies=None, num_cycles=1, num_snapshots_per_cycle=20, scaling=0.2, save_h5=False, **kwargs):
"""
Export animations for multiple eigenmodes.
The first argument `modes` can be either an integer (to export
the first N modes) or a list of integers (to export precisely
specified modes).
If `dm_only` is `False` (the default) then the "full" eigenmode
of the form m0+dm(t) will be exported (where m0 is the relaxed
equilibrium state and dm(t) is the small time-varying eigenmode
excitation). If `dm_only` is `True` then only the part dm(t)
will be exported.
The animations will be saved in VTK format (as .pvd files) and
stored in separate subfolders of the given `directory` (one
subfolder for each eigenmode).
If `create_movies` is `True` (the default) then each animation
will in addition be automatically converted to a movie file
in .avi format and stored in the directory `dirname_movies`.
(If the latter is `None` (the default), then the movies will
be stored in `directory` as well).
This function accepts all keyword arguments understood by
`finmag.util.visualization.render_paraview_scene()`, which
can be used to control aspects such as the camera position
or whether to add glyphs etc. in the exported movie files.
"""
# Make sure that `modes` is a list of integers
if not hasattr(modes, '__len__'):
modes = range(modes)
# Export eigenmode animations
for k in modes:
try:
freq = self.eigenfreqs[k]
except IndexError:
log.error("Could not export eingenmode animation for mode "
"#{}. Index exceeds range of comptued modes.".format(k))
continue
mode_descr = 'normal_mode_{:02d}__{:.3f}_GHz'.format(k, freq)
vtk_filename = os.path.join(
directory, mode_descr, mode_descr + '.pvd')
self.export_normal_mode_animation(
k, filename=vtk_filename, dm_only=dm_only, num_cycles=num_cycles,
num_snapshots_per_cycle=num_snapshots_per_cycle, scaling=scaling,
save_h5=save_h5, **kwargs)
# Some good default values for movie files
default_kwargs = {
'representation': 'Surface',
'add_glyphs': True,
'trim_border': False,
'colormap': 'coolwarm',
}
# Update default values with the kwargs explicitly given by the
# user
default_kwargs.update(kwargs)
if create_movies:
directory_movies = directory_movies or directory
helpers.pvd2avi(vtk_filename, os.path.join(
directory_movies, mode_descr + '.avi'), **default_kwargs)
def export_normal_mode_animation(self, k, filename=None, directory='', dm_only=False, num_cycles=1, num_snapshots_per_cycle=20, scaling=0.2, save_h5=False, **kwargs):
"""
XXX TODO: Complete me!
Export an animation of the `k`-th eigenmode, where the value of `k`
refers to the index of the corresponding mode frequency and eigenvector
in the two arrays returnd by `sim.compute_normal_modes`. If that method
was called multiple times the results of the latest call are used.
"""
if self.eigenfreqs is None or self.eigenvecs is None:
log.debug(
"Could not find any precomputed eigenmodes. Computing them now.")
self.compute_normal_modes(max(k, 10))
if filename is None:
if directory is '':
raise ValueError(
"Please specify at least one of the arguments 'filename' or 'directory'")
filename = 'normal_mode_{}__{:.3f}_GHz.pvd'.format(
k, self.eigenfreqs[k])
filename = os.path.join(directory, filename)
basename, suffix = os.path.splitext(filename)
# Export VTK animation
if suffix == '.pvd':
pvd_filename = filename
elif suffix in ['.jpg', '.avi']:
pvd_filename = basename + '.pvd'
else:
raise ValueError(
"Filename must end in one of the following suffixes: .pvd, .jpg, .avi.")
m = self._extend_to_full_mesh(self.m)
export_normal_mode_animation(self.mesh, m, self.eigenfreqs[k], self.eigenvecs[k],
pvd_filename, num_cycles=num_cycles,
num_snapshots_per_cycle=num_snapshots_per_cycle,
scaling=scaling, dm_only=dm_only, save_h5=save_h5)
# Export image files
if suffix == '.jpg':
jpg_filename = filename
elif suffix == '.avi':
jpg_filename = basename + '.jpg'
else:
jpg_filename = None
if jpg_filename != None:
from finmag.util.visualization import render_paraview_scene
render_paraview_scene(pvd_filename, outfile=jpg_filename, **kwargs)
# Convert image files to movie
if suffix == '.avi':
movie_filename = filename
helpers.pvd2avi(pvd_filename, outfile=movie_filename)
# Return the movie if it was created
res = None
if suffix == '.avi':
from IPython.display import HTML
from base64 import b64encode
video = open(movie_filename, "rb").read()
video_encoded = b64encode(video)
#video_tag = '<video controls alt="test" src="data:video/x-m4v;base64,{0}">'.format(video_encoded)
#video_tag = '<a href="files/{0}">Link to video</a><br><br><video controls alt="test" src="data:video.mp4;base64,{1}">'.format(movie_filename, video_encoded)
# video_tag = '<a href="files/{0}" target="_blank">Link to video</a><br><br><embed src="files/{0}"/>'.format(movie_filename) # --> kind of works
# video_tag = '<a href="files/{0}" target="_blank">Link to video</a><br><br><object data="files/{0}" type="video.mp4"/>'.format(movie_filename) # --> kind of works
# video_tag = '<a href="files/{0}" target="_blank">Link to
# video</a><br><br><embed src="files/{0}"/>'.format(basename +
# '.avi') # --> kind of works
# Display a link to the video
video_tag = '<a href="files/{0}" target="_blank">Link to video</a>'.format(
basename + '.avi')
return HTML(data=video_tag)
def plot_spatially_resolved_normal_mode(self, k, slice_z='z_max', components='xyz', region=None,
figure_title=None, yshift_title=0.0,
plot_powers=True, plot_phases=True, xticks=None, yticks=None,
num_power_colorbar_ticks=None, num_phase_colorbar_ticks=5,
colorbar_fmt='%.2e',
cmap_powers='coolwarm', cmap_phases='circular4', vmin_powers=0.0,
show_axis_labels=True, show_axis_frames=True,
show_colorbars=True, figsize=None, outfilename=None, dpi=None):
"""
Plot a spatially resolved profile of the k-th normal mode as
computed by `sim.compute_normal_modes()`.
*Returns*
A `matplotlib.Figure` containing the plot.
See the docstring of the function
`finmag.normal_modes.deprecated.normal_modes.plot_spatially_resolved_normal_mode`
for details about the meaning of the arguments.
"""
if self.eigenvecs is None:
log.warning("No eigenvectors have been computed. Please call "
"`sim.compute_normal_modes()` to do so.")
m = self._extend_to_full_mesh(self.m)
if region == None:
submesh = self.mesh
w = self.eigenvecs[k]
else:
# Restrict m and the eigenvector array to the submesh
# TODO: This is messy and should be factored out into helper routines.
#
# XXX TODO: If we are using PBCs then we need to extend the vectors w1, w2
# to 'full' vectors on the whole mesh (currently they are missing
# the dofs that are identified).
submesh = self.get_submesh(region)
restr = helpers.restriction(self.mesh, submesh)
m = restr(m.reshape(3, -1)).ravel()
w1, w2 = self.eigenvecs[k].reshape(2, -1)
w1_restr = restr(w1)
w2_restr = restr(w2)
w = np.concatenate([w1_restr, w2_restr]).reshape(2, -1)
fig = plot_spatially_resolved_normal_mode(
submesh, m, w, slice_z=slice_z, components=components,
figure_title=figure_title, yshift_title=yshift_title,
plot_powers=plot_powers, plot_phases=plot_phases,
xticks=xticks, yticks=yticks,
num_power_colorbar_ticks=num_power_colorbar_ticks,
num_phase_colorbar_ticks=num_phase_colorbar_ticks,
colorbar_fmt=colorbar_fmt,
cmap_powers=cmap_powers, cmap_phases=cmap_phases, vmin_powers=vmin_powers,
show_axis_labels=show_axis_labels, show_axis_frames=show_axis_frames,
show_colorbars=show_colorbars, figsize=figsize,
outfilename=outfilename, dpi=dpi)
return fig
def normal_mode_simulation(mesh, Ms, m_init, **kwargs):
"""
Same as `sim_with` (it accepts the same keyword arguments apart from
`sim_class`), but returns an instance of `NormalModeSimulation`
instead of `Simulation`.
"""
# Make sure we don't inadvertently create a different kind of simulation
kwargs.pop('sim_class', None)
return sim_with(mesh, Ms, m_init, sim_class=NormalModeSimulation, **kwargs)
| 42,241 | 45.831486 | 203 |
py
|
finmag
|
finmag-master/src/finmag/sim/hysteresis_test.py
|
import dolfin as df
import numpy as np
import pytest
import os
from glob import glob
from finmag import sim_with
from finmag.example import barmini
from finmag.util.plot_helpers import plot_hysteresis_loop
ONE_DEGREE_PER_NS = 17453292.5 # in rad/s
H = 0.2e6 # maximum external field strength in A/m
initial_direction = np.array([1.0, 0.01, 0.0])
N = 5
def test_hysteresis(tmpdir):
os.chdir(str(tmpdir))
sim = barmini()
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
H_ext_list = [(1, 0, 0), (2, 0, 0), (3, 0, 0), (4, 0, 0)]
N = len(H_ext_list)
# Run a relaxation and save a vtk snapshot at the end of each stage;
# this should result in three .vtu files (one for each stage).
sim1 = sim_with(mesh, Ms=1e6, m_init=(0.8, 0.2, 0), alpha=1.0,
unit_length=1e-9, A=None, demag_solver=None)
sim1.schedule('save_vtk', at_end=True, filename='barmini_hysteresis.pvd')
res1 = sim1.hysteresis(H_ext_list=H_ext_list)
assert(len(glob('barmini_hysteresis*.vtu')) == N)
assert(res1 == None)
# Run a relaxation with a non-trivial `fun` argument and check
# that we get a list of return values.
sim2 = sim_with(mesh, Ms=1e6, m_init=(0.8, 0.2, 0), alpha=1.0,
unit_length=1e-9, A=None, demag_solver=None)
res2 = sim2.hysteresis(H_ext_list=H_ext_list,
fun=lambda sim: sim.m_average[0])
assert(len(res2) == N)
@pytest.mark.requires_X_display
def test_hysteresis_loop_and_plotting(tmpdir):
"""
Call the hysteresis loop with various combinations for saving
snapshots and check that the correct number of vtk files have been
produced. Also check that calling the plotting function works
(although the output image isn't verified).
"""
os.chdir(str(tmpdir))
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = sim_with(mesh, Ms=1e6, m_init=(0.8, 0.2, 0), alpha=1.0,
unit_length=1e-9, A=None, demag_solver=None)
H_vals, m_vals = \
sim.hysteresis_loop(H, initial_direction, N, stopping_dmdt=10)
# Check that the magnetisation values are as trivial as we expect
# them to be ;-)
assert(np.allclose(m_vals, [1.0 for _ in xrange(2 * N)], atol=1e-4))
# This only tests whether the plotting function works without
# errors. It currently does *not* check that it produces
# meaningful results (and the plot is quite boring for the system
# above anyway).
plot_hysteresis_loop(H_vals, m_vals, infobox=["param_A = 23", ("param_B", 42)],
title="Hysteresis plot test", xlabel="H_ext", ylabel="m_avg",
figsize=(5, 4), infobox_loc="bottom left",
filename='test_plot.pdf')
# Test multiple filenames, too
plot_hysteresis_loop(
H_vals, m_vals, filename=['test_plot.pdf', 'test_plot.png'])
| 2,923 | 37.986667 | 86 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim_test.py
|
import dolfin as df
import numpy as np
import finmag
import itertools
import textwrap
import logging
import pytest
import os
import sh
import matplotlib.pyplot as plt
from glob import glob
from distutils.version import LooseVersion
from finmag import sim_with, Simulation, set_logging_level, normal_mode_simulation
from finmag.normal_modes.eigenmodes import eigensolvers
from finmag.example import barmini
from math import sqrt, cos, sin, pi
from finmag.util.helpers import assert_number_of_files, vector_valued_function, logging_status_str, fnormalise
from finmag.util.meshes import nanodisk, plot_mesh_with_paraview, mesh_volume, from_csg
from finmag.util.mesh_templates import EllipticalNanodisk, Sphere
from finmag.sim import sim_helpers
from finmag.energies import Zeeman, TimeZeeman, Exchange, UniaxialAnisotropy, DMI
from finmag.util.fileio import Tablereader
from finmag.util.ansistrm import ColorizingStreamHandler
from finmag.util.macrospin import make_analytic_solution
from finmag.example.macrospin import macrospin
from finmag.util.consts import gamma
logger = logging.getLogger("finmag")
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def num_interactions(sim):
"""
Helper function to determine the number of interactions present in
the Simulation.
"""
return len(sim.interactions())
class TestSimulation(object):
@classmethod
def setup_class(cls):
# N.B.: The mesh and simulation are only created once for the
# entire test class and are re-used in each test method for
# efficiency. Thus they should be regarded as read-only and
# not be changed in any test method, otherwise there may be
# unpredicted bugs or errors in unrelated test methods!
cls.mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 5, 5, 5)
cls.sim = sim_with(cls.mesh, Ms=8.6e5, m_init=(1, 0, 0), alpha=1.0,
unit_length=1e-9, A=13.0e-12, demag_solver='FK')
cls.sim.relax()
def test_get_interaction(self):
sim = sim_with(self.mesh, Ms=8.6e5, m_init=(1, 0, 0), alpha=1.0,
unit_length=1e-9, A=13.0e-12, demag_solver='FK')
# These should just work
sim.get_interaction('Exchange')
sim.get_interaction('Demag')
with pytest.raises(KeyError):
sim.get_interaction('foobar')
exch = Exchange(A=13e-12, name='foobar')
sim.add(exch)
assert exch == sim.get_interaction('foobar')
def test_compute_energy(self):
sim = sim_with(self.mesh, Ms=8.6e5, m_init=(1, 0, 0), alpha=1.0,
unit_length=1e-9, A=13.0e-12, demag_solver='FK')
# These should just work
sim.compute_energy('Exchange')
sim.compute_energy('Demag')
sim.compute_energy('Total')
sim.compute_energy('total')
# A non-existing interaction should throw an error
with pytest.raises(KeyError):
sim.compute_energy('foobar')
new_exch = Exchange(A=13e-12, name='foo')
sim.add(new_exch)
assert new_exch.compute_energy() == sim.compute_energy('foo')
def test_get_field_as_dolfin_function(self):
"""
Convert the demag field into a dolfin function, evaluate it a all
nodes and check that the resulting vector of the field values is
the same as the one internally stored in the simulation.
"""
fun_demag = self.sim.get_field_as_dolfin_function("Demag")
# Evalute the field function at all mesh vertices. This gives a
# Nx3 array, which we convert back into a 1D array using dolfin's
# convention of arranging coordinates.
v_eval = np.array([fun_demag(c) for c in self.mesh.coordinates()])
v_eval_1d = np.concatenate([v_eval[:, 0], v_eval[:, 1], v_eval[:, 2]])
# Now check that this is essentially the same as vector of the
# original demag interaction.
demag = self.sim.get_interaction("Demag")
v_demag = demag.compute_field()
assert(np.allclose(v_demag, v_eval_1d))
# Note that we cannot use '==' for the comparison above because
# the function evaluation introduced numerical inaccuracies:
logger.debug("Are the vectors identical? "
"{}".format((v_demag == v_eval_1d).all()))
def test_probe_demag_field(self):
N = self.mesh.num_vertices()
coords = self.mesh.coordinates()
# Probe field at all mesh vertices and at the first vertex;
# also convert a 1d version of the probed vector following
# dolfin's coordinate convention.
v_probed = self.sim.probe_field("Demag", coords)
v_probed_1d = np.concatenate([v_probed[:, 0],
v_probed[:, 1],
v_probed[:, 2]])
v0_probed = self.sim.probe_field("Demag", coords[0])
# Create reference vectors at the same positions
v_ref = self.sim.get_interaction("Demag").compute_field()
v0_ref = v_ref[[0, N, 2 * N]]
# Check that the results coincide
print "v0_probed: {}".format(v0_probed)
print "v0_ref: {}".format(v0_ref)
assert(np.allclose(v0_probed, v0_ref))
assert(np.allclose(v_probed_1d, v_ref))
def test_probe_constant_m_at_individual_points(self):
mesh = df.BoxMesh(df.Point(-2, -2, -2), df.Point(2, 2, 2), 5, 5, 5)
m_init = np.array([0.2, 0.7, -0.4])
# normalize the vector for later comparison
m_init /= np.linalg.norm(m_init)
sim = sim_with(
mesh, Ms=8.6e5, m_init=m_init, unit_length=1e-9, demag_solver=None)
# Points inside the mesh where to probe the magnetisation.
probing_pts = [
# We are explicitly using integer coordinates for the first
# point because this used to lead to a very subtle bug.
[0, 0, 0],
[0.0, 0.0, 0.0], # same point again but with float coordinates
[1, 1, -0.5],
[-1.3, 0.02, 0.3]]
# Probe the magnetisation at the given points
m_probed_vals = [sim.probe_field("m", pt) for pt in probing_pts]
# Check that we get m_init everywhere.
for v in m_probed_vals:
assert(np.allclose(v, m_init))
# Probe at point outside the mesh and check
# that the resulting vector is masked.
m_probed_outside = sim.probe_field("m", [5, -6, 1])
assert((np.ma.getmask(m_probed_outside) == True).all())
def test_probe_nonconstant_m_at_individual_points(self):
TOL = 1e-5
unit_length = 1e-9
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1000, 2, 2)
m_init = df.Expression(("cos(x[0]*pi)",
"sin(x[0]*pi)",
"0.0"),
unit_length=unit_length, degree=1)
sim = sim_with(
mesh, Ms=8.6e5, m_init=m_init, unit_length=unit_length, demag_solver=None)
# Probe the magnetisation along two lines parallel to the x-axis.
# We choose the limits just inside the mesh boundaries to prevent
# problems with rounding issues.
xmin = 0.01
xmax = 0.99
y0 = 0.2
z0 = 0.4
pts1 = [[x, 0, 0] for x in np.linspace(xmin, xmax, 20)]
pts2 = [[x, y0, z0] for x in np.linspace(xmin, xmax, 20)]
probing_pts = np.concatenate([pts1, pts2])
# Probe the magnetisation at the given points
m_probed_vals = [sim.probe_field("m", pt) for pt in probing_pts]
# Alternative method using 'probe_field_along_line()'
_, vals1 = sim.probe_field_along_line("m", [xmin, 0, 0], [xmax, 0, 0], N=20)
_, vals2 = sim.probe_field_along_line("m", [xmin, y0, z0], [xmax, y0, z0], N=20)
m_probed_vals2 = np.concatenate([vals1, vals2])
# Check that we get m_init everywhere.
for i in xrange(len(probing_pts)):
m = m_probed_vals[i]
m2 = m_probed_vals2[i]
pt = probing_pts[i]
x = pt[0]
m_expected = np.array([cos(x * pi),
sin(x * pi),
0.0])
assert(np.linalg.norm(m - m_expected) < TOL)
assert(np.linalg.norm(m2 - m_expected) < TOL)
def test_probe_m_on_regular_grid(self, tmpdir):
"""
Another sanity check using the barmini example; probe the
magnetisation on a regular 2D grid inside a plane parallel to the
x/y-plane (with different numbers of probing points in x- and
y-direction).
"""
os.chdir(str(tmpdir))
# Set up the simulation
sim = barmini()
nx = 5
ny = 10
z = 5.0 # use cutting plane in the middle of the cuboid
X, Y = np.mgrid[0:3:nx * 1j, 0:3:ny * 1j]
pts = np.array([[(X[i, j], Y[i, j], z) for j in xrange(ny)]
for i in xrange(nx)])
# Probe the field
res = sim.probe_field('m', pts)
# Check that 'res' has the right shape and values (the field vectors
# should be constant and equal to [1/sqrt(2), 0, 1/sqrt(2)].
assert(res.shape == (nx, ny, 3))
assert(np.allclose(res[..., 0], 1.0 / sqrt(2)))
assert(np.allclose(res[..., 1], 0.0))
assert(np.allclose(res[..., 2], 1.0 / sqrt(2)))
def test_schedule(self, tmpdir):
os.chdir(str(tmpdir))
# Define a function to be scheduled, with one positional and
# one keyword argument.
res = []
def f(sim, tag, optional=None):
res.append((tag, int(sim.t * 1e13), optional))
sim = barmini()
sim.schedule(f, 'tag1', every=2e-13)
sim.schedule(f, 'tag2', optional='foo', every=3e-13)
sim.schedule(f, 'tag3', every=4e-13, optional='bar')
sim.run_until(1.1e-12)
assert(sorted(res) ==
[('tag1', 0, None), ('tag1', 2, None), ('tag1', 4, None),
('tag1', 6, None), ('tag1', 8, None), ('tag1', 10, None),
('tag2', 0, 'foo'), ('tag2', 3, 'foo'),
('tag2', 6, 'foo'), ('tag2', 9, 'foo'),
('tag3', 0, 'bar'), ('tag3', 4, 'bar'), ('tag3', 8, 'bar')])
# The keyword arguments 'at', 'every', 'at_end' and 'realtime'
# are forbidden:
def f_illegal_1(sim, at=None):
pass
def f_illegal_2(sim, after=None):
pass
def f_illegal_3(sim, every=None):
pass
def f_illegal_4(sim, at_end=None):
pass
def f_illegal_5(sim, realtime=None):
pass
with pytest.raises(ValueError):
sim.schedule(f_illegal_1, at=0.0)
with pytest.raises(ValueError):
sim.schedule(f_illegal_2, at=0.0)
with pytest.raises(ValueError):
sim.schedule(f_illegal_3, at=0.0)
with pytest.raises(ValueError):
sim.schedule(f_illegal_4, at=0.0)
with pytest.raises(ValueError):
sim.schedule(f_illegal_5, at=0.0)
def test_save_ndt(self, tmpdir):
os.chdir(str(tmpdir))
sim = barmini()
sim.schedule('save_ndt', every=2e-13)
sim.run_until(1.1e-12)
f = Tablereader('barmini.ndt')
assert(len(f.timesteps()) == 6) # we should have saved 6 time steps
# Also assert that the energy and field terms are written automatically
entities = f.entities()
assert 'E_Exchange' in entities
assert 'H_Exchange_x' in entities
assert 'H_Exchange_y' in entities
assert 'H_Exchange_z' in entities
assert 'E_Demag' in entities
assert 'H_Demag_x' in entities
assert 'H_Demag_y' in entities
assert 'H_Demag_z' in entities
def test_save_restart_data(self, tmpdir):
"""
Simple test to check that we can save restart data via the
Simulation class. Note that this basically just checks that we
can call save_restart_data(). The actual stress-test of the
functionality is in sim_helpers_test.py.
"""
os.chdir(str(tmpdir))
sim = barmini()
# Test scheduled saving of restart data
sim.schedule('save_restart_data', at_end=True)
sim.run_until(1e-13)
d = sim_helpers.load_restart_data('barmini-restart.npz')
assert(d['simtime']) == 1e-13
# Testsaving of restart data using the simulation's own method
sim.run_until(2e-13)
sim.save_restart_data()
d = sim_helpers.load_restart_data('barmini-restart.npz')
assert(d['simtime']) == 2e-13
def test_restart(self, tmpdir):
os.chdir(str(tmpdir))
# Run the simulation for 1 ps; save restart data; reload it
# while resetting the simulation time to 0.5 ps; then run
# again for 1 ps until we have reached 1.5 ps.
sim1 = barmini(name='barmini1')
sim1.schedule('save_ndt', every=1e-13)
sim1.run_until(1e-12)
sim1.save_restart_data('barmini.npz')
sim1.restart('barmini.npz', t0=0.5e-12)
sim1.run_until(1.5e-12)
# Check that the time steps for sim1 are as expected
f1 = Tablereader('barmini1.ndt')
t1 = f1.timesteps()
t1_expected = np.concatenate([np.linspace(0, 1e-12, 11),
np.linspace(0.5e-12, 1.5e-12, 11)])
assert(np.allclose(t1, t1_expected, atol=0))
# Run a second simulation for 2 ps continuously
sim2 = barmini(name='barmini2')
sim2.schedule('save_ndt', every=1e-13)
sim2.run_until(2e-12)
# Check that the time steps for sim1 are as expected
f2 = Tablereader('barmini2.ndt')
t2 = f2.timesteps()
t2_expected = np.linspace(0, 2e-12, 21)
assert(np.allclose(t2, t2_expected, atol=0))
# Check that the magnetisation dynamics of sim1 and sim2 are
# the same and that we end up with the same magnetisation.
for col in ['m_x', 'm_y', 'm_z']:
a = f1[col]
b = f2[col]
# delete the duplicate line due to the restart
a = np.concatenate([a[:10], a[11:]])
assert(np.allclose(a, b))
assert(np.allclose(sim1.m, sim2.m, atol=1e-6))
# Check that resetting the time to zero works (this used to not work
# due to a bug).
sim1.restart('barmini.npz', t0=0.0)
assert(sim1.t == 0.0)
def test_reset_time(self, tmpdir):
"""
Integrate a simple macrospin simulation for a bit, then reset
the time to an earlier point in time and integrate again. We
expect the same magnetisation dynamics as if the simulation
had run for the same length continuously, but the internal
clock times should be different.
"""
os.chdir(str(tmpdir))
# First simulation: run for 50 ps, reset the time to 30 ps and run
# again for 50 ps.
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim1 = Simulation(mesh, Ms=1, name='test_save_ndt', unit_length=1e-9)
sim1.alpha = 0.05
sim1.set_m((1, 0, 0))
sim1.add(Zeeman((0, 0, 1e6)))
sim1.schedule('save_ndt', every=1e-11)
sim1.run_until(5e-11)
sim1.reset_time(3e-11)
sim1.run_until(8e-11)
# Run a second simulation for 100 ps continuously, without
# resetting the time in between.
sim2 = Simulation(mesh, Ms=1, name='test_save_ndt2', unit_length=1e-9)
sim2.alpha = 0.05
sim2.set_m((1, 0, 0))
sim2.add(Zeeman((0, 0, 1e6)))
sim2.schedule('save_ndt', every=1e-11)
sim2.run_until(10e-11)
# Check that the time steps for sim1 are as expected.
a = np.loadtxt('test_save_ndt.ndt')
ta = a[:, 0]
ta_expected = 1e-11 * np.array([0, 1, 2, 3, 4, 5, 3, 4, 5, 6, 7, 8])
assert(np.allclose(ta, ta_expected, atol=0))
# Check that the time steps for sim2 are as expected.
b = np.loadtxt('test_save_ndt2.ndt')
tb = b[:, 0]
tb_expected = 1e-11 * np.arange(10 + 1)
assert(np.allclose(tb, tb_expected, atol=0))
# Delete the duplicate line due to resetting the time
a = np.concatenate([a[:5, :], a[6:, :]])
# Check that the magnetisation dynamics of sim1 and sim2 are the same.
# skip the last one which is the steps in cvode.
# skipping dmdt for the moment
assert(np.allclose(a[:, 1:8], b[:, 1:8], atol=1e-4, rtol=1e-8))
assert(np.allclose(a[:, 12:-1], b[:, 12:-1], atol=1e-4, rtol=1e-8))
# dmdt deviations are large and so would fail with the above relative tolerance.
# Hopefully this is due to the non-reproducible m and dmdt on the i-7's
# If not, this test should be re-written. For the time being, the rel tol
# has been increased.
assert(np.allclose(a[:, 9:11], b[:, 9:11], atol=1e-4, rtol=1))
def test_save_vtk(self, tmpdir):
os.chdir(str(tmpdir))
# Create an empty dummy .pvd file
with open('barmini.pvd', 'w'):
pass
sim = barmini()
with pytest.raises(IOError):
# existing file should not be overwritten
sim.schedule('save_vtk', every=1e-13, overwrite=False)
# sim.run_until(1e-12)
# This time we enforce overwriting
sim = barmini()
sim.schedule('save_vtk', every=1e-13, overwrite=True)
sim.run_until(5e-13)
assert(len(glob('barmini*.vtu')) == 6)
# Schedule saving to different filenames and at various time steps.
sim = barmini()
sim.schedule(
'save_vtk', filename='bar2.pvd', every=1e-13, overwrite=True)
sim.schedule(
'save_vtk', filename='bar2.pvd', at=2.5e-13, overwrite=False)
sim.schedule(
'save_vtk', filename='bar2.pvd', at=4.3e-13, overwrite=False)
sim.schedule(
'save_vtk', filename='bar3.pvd', at=3.5e-13, overwrite=True)
sim.schedule(
'save_vtk', filename='bar3.pvd', every=2e-13, overwrite=True)
sim.schedule(
'save_vtk', filename='bar3.pvd', at=3.8e-13, overwrite=True)
# ... then run the simulation
sim.run_until(5e-13)
# ... also save another vtk snapshot manually
sim.save_vtk(filename='bar3.pvd')
# ... and check that the correct number of files was created
assert(len(glob('bar2*.vtu')) == 8)
assert(len(glob('bar3*.vtu')) == 6)
# Saving another snapshot with overwrite=True should erase existing
# .vtu files
sim.save_vtk(filename='bar3.pvd', overwrite=True)
assert(len(glob('bar3*.vtu')) == 1)
def test_sim_schedule_clear(self, tmpdir):
os.chdir(str(tmpdir))
# Run simulation for a few picoseconds and check that the
# expected vtk files were saved.
sim = barmini()
sim.schedule('save_vtk', every=2e-12)
sim.schedule('save_vtk', at=3e-12)
sim.run_until(5e-12)
assert_number_of_files('barmini.pvd', 1)
assert_number_of_files('barmini*.vtu', 4)
# Clear schedule and continue running; assert that no
# additional files were saved
sim.clear_schedule()
sim.run_until(10e-12)
assert_number_of_files('barmini.pvd', 1)
assert_number_of_files('barmini*.vtu', 4)
# Schedule saving to a different filename and run further
sim.schedule('save_vtk', filename='a.pvd', every=3e-12)
sim.schedule('save_vtk', filename='a.pvd', at=14e-12)
sim.run_until(20e-12)
assert_number_of_files('a.pvd', 1)
assert_number_of_files('a*.vtu', 5)
def test_remove_interaction1(self):
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = Simulation(mesh, Ms=1, unit_length=1e-9)
sim.add(Zeeman((0, 0, 1)))
sim.add(Exchange(13e-12))
assert(num_interactions(sim) == 2)
sim.remove_interaction("Exchange")
assert(num_interactions(sim) == 1)
sim.remove_interaction("Zeeman")
assert(num_interactions(sim) == 0)
# No Zeeman interaction present any more
with pytest.raises(KeyError):
sim.remove_interaction("Zeeman")
def test_remove_interaction2(self):
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = Simulation(mesh, Ms=1, unit_length=1e-9)
# Two different Zeeman interactions present
sim.add(Zeeman((0, 0, 1)))
sim.add(Zeeman((0, 0, 2), name="Zeeman2"))
sim.remove_interaction("Zeeman")
sim.remove_interaction("Zeeman2")
# Adding Zeeman once more will trigger an error. HF would argue that this is okay:
# it seems odd to add and remove interactions like this.
#
# We could in principle allow this (by checking whether currently the get method
# returns NAN for this interaction, or defining a token for NAN to be returned), but
# it seems to increase complexity for a use case that shouldn't really
# exist.
with pytest.raises(AssertionError):
sim.add(Zeeman((0, 0, 1)))
def test_switch_off_H_ext(self):
"""
Simply test that we can call sim.switch_off_H_ext()
"""
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = Simulation(mesh, Ms=1, unit_length=1e-9)
sim.add(Zeeman((1, 2, 3)))
sim.switch_off_H_ext(remove_interaction=False)
H = sim.get_interaction("Zeeman").compute_field()
assert(np.allclose(H, np.zeros_like(H)))
sim.switch_off_H_ext(remove_interaction=True)
assert(num_interactions(sim) == 0)
def test_set_H_ext(self):
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = Simulation(mesh, Ms=1, unit_length=1e-9)
sim.add(Zeeman((1, 2, 3)))
H = sim.get_field_as_dolfin_function('Zeeman').vector().array()
H = sim.probe_field('Zeeman', [0.5e-9, 0.5e-9, 0.5e-9])
assert(np.allclose(H, [1, 2, 3]))
sim.set_H_ext([-4, -5, -6])
H = sim.probe_field('Zeeman', [0.5e-9, 0.5e-9, 0.5e-9])
assert(np.allclose(H, [-4, -5, -6]))
# Try to set H_ext in a simulation that doesn't have a Zeeman
# interaction yet
sim = Simulation(mesh, Ms=1, unit_length=1e-9)
sim.set_H_ext((1, 2, 3)) # this should not raise an error!
H = sim.get_field_as_dolfin_function('Zeeman').vector().array()
H = sim.probe_field('Zeeman', [0.5e-9, 0.5e-9, 0.5e-9])
assert(np.allclose(H, [1, 2, 3]))
def test_set_m(self):
"""
Test to ensure m is not set with illegal values (such a NaNs)
"""
def m_init_nan(pos):
return [np.NaN, 1, 1]
mesh = df.BoxMesh(df.Point(0,0,0), df.Point(1,1,1),1,1,1)
sim = Simulation(mesh, Ms=1e5, unit_length=1e-9)
with pytest.raises(ValueError):
sim.set_m(m_init_nan)
@pytest.mark.skipif("not LooseVersion(df.__version__) < LooseVersion('1.2.0')")
def test_pbc2d_m_init(self):
def m_init_fun(pos):
if pos[0] == 0 or pos[1] == 0:
return [0, 0, 1]
else:
return [0, 0, -1]
mesh = df.UnitSquareMesh(3, 3)
m_init = vector_valued_function(m_init_fun, mesh)
sim = Simulation(mesh, Ms=1, pbc2d=True)
sim.set_m(m_init)
expect_m = np.zeros((3, 16))
expect_m[2, :] = np.array(
[1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1])
expect_m.shape = (48,)
assert np.array_equal(sim.m, expect_m)
def test_set_stt(self, debug=False):
"""
Simple macrospin simulation with STT where the current density
changes sign halfway through the simulation.
"""
import matplotlib.pyplot as plt
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1)
sim = Simulation(
mesh, Ms=8.6e5, unit_length=1e-9, name='macrospin_with_stt')
sim.m = (1, 0, 0)
sim.add(Zeeman([0, 0, 1e5]))
sim.alpha = 0.0 # no damping
def J(t):
return 0.5e11 if (t < 2.5e-9) else -0.5e11
sim.set_stt(0.05e11, 1.0, 2e-9, (0, 0, 1), with_time_update=J)
sim.schedule('save_ndt', every=1e-11)
sim.run_until(5e-9)
ts, xs, ys, zs = np.loadtxt('macrospin_with_stt.ndt').T[:4]
if debug:
fig = plt.figure(figsize=(20, 5))
ax1 = fig.add_subplot(131)
ax1.plot(ts, xs)
ax2 = fig.add_subplot(132)
ax2.plot(ts, ys)
ax3 = fig.add_subplot(133)
ax3.plot(ts, zs)
fig.savefig('macrospin_with_stt.png')
# Assert that the dynamics of m_z are symmetric over time. In
# theory, this should also be true of m_x and m_y, but since
# they oscillate rapidly there is quite a bit of numerical
# inaccuracy, so we're only testing for m_z here.
assert max(abs(zs - zs[::-1])) < 0.005
def test_save_field(self, tmpdir):
os.chdir(str(tmpdir))
sim = barmini()
# Save the magnetisation using the default filename
sim.save_field('m')
sim.save_field('m')
sim.save_field('m')
assert(len(glob('barmini_m*.npy')) == 1)
os.remove('barmini_m.npy')
# Save incrementally
sim.save_field('m', incremental=True)
sim.save_field('m', incremental=True)
sim.save_field('m', incremental=True)
assert(len(glob('barmini_m_[0-9]*.npy')) == 3)
# Check that the 'overwrite' keyword works
sim2 = barmini()
with pytest.raises(IOError):
sim2.save_field('m', incremental=True)
sim2.save_field('m', incremental=True, overwrite=True)
sim2.save_field('m', incremental=True)
assert(len(glob('barmini_m_[0-9]*.npy')) == 2)
sim.save_field('Demag', incremental=True)
assert(os.path.exists('barmini_demag_000000.npy'))
sim.save_field('Demag')
assert(os.path.exists('barmini_demag.npy'))
sim.save_field('Demag', filename='demag.npy', incremental=True)
assert(os.path.exists('demag_000000.npy'))
def test_save_m(self, tmpdir):
"""
Similar test as 'test_save_field', but for the convenience shortcut 'save_m'.
"""
os.chdir(str(tmpdir))
sim = barmini()
# Save the magnetisation using the default filename
sim.save_m()
sim.save_m()
sim.save_m()
assert(len(glob('barmini_m*.npy')) == 1)
os.remove('barmini_m.npy')
# Save incrementally
sim.save_m(incremental=True)
sim.save_m(incremental=True)
sim.save_m(incremental=True)
assert(len(glob('barmini_m_[0-9]*.npy')) == 3)
# Check that the 'overwrite' keyword works
sim2 = barmini()
with pytest.raises(IOError):
sim2.save_m(incremental=True)
sim2.save_m(incremental=True, overwrite=True)
sim2.save_m(incremental=True)
assert(len(glob('barmini_m_[0-9]*.npy')) == 2)
def test_save_field_scheduled(self, tmpdir):
os.chdir(str(tmpdir))
sim = barmini()
sim.schedule('save_field', 'm', every=1e-12)
sim.run_until(2.5e-12)
assert(len(glob('barmini_m_[0-9]*.npy')) == 3)
sim.run_until(5.5e-12)
assert(len(glob('barmini_m_[0-9]*.npy')) == 6)
sim.clear_schedule()
sim.schedule('save_field', 'm', filename='mag.npy', every=1e-12)
sim.run_until(7.5e-12)
assert(len(glob('barmini_m_[0-9]*.npy')) == 6)
assert(len(glob('mag_[0-9]*.npy')) == 3)
def test_sim_sllg(self, do_plot=False):
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(2, 2, 2), 1, 1, 1)
sim = Simulation(mesh, 8.6e5, unit_length=1e-9, kernel='sllg')
alpha = 0.1
sim.alpha = alpha
sim.set_m((1, 0, 0))
sim.T = 0
H0 = 1e5
sim.add(Zeeman((0, 0, H0)))
dt = 1e-12
ts = np.linspace(0, 500 * dt, 100)
precession_coeff = sim.gamma / (1 + alpha ** 2)
mz_ref = []
mz = []
real_ts = []
for t in ts:
sim.run_until(t)
real_ts.append(sim.t)
mz_ref.append(np.tanh(precession_coeff * alpha * H0 * sim.t))
# same as m_average for this macrospin problem
mz.append(sim.m[-1])
mz = np.array(mz)
if do_plot:
import matplotlib.pyplot as plt
ts_ns = np.array(real_ts) * 1e9
plt.plot(ts_ns, mz, "b.", label="computed")
plt.plot(ts_ns, mz_ref, "r-", label="analytical")
plt.xlabel("time (ns)")
plt.ylabel("mz")
plt.title("integrating a macrospin")
plt.legend()
plt.savefig(os.path.join(MODULE_DIR, "test_sllg.png"))
print("Deviation = {}, total value={}".format(
np.max(np.abs(mz - mz_ref)),
mz_ref))
assert np.max(np.abs(mz - mz_ref)) < 8e-7
def test_sim_sllg_time(self):
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(5, 5, 5), 1, 1, 1)
sim = Simulation(mesh, 8.6e5, unit_length=1e-9, kernel='sllg')
sim.alpha = 0.1
sim.set_m((1, 0, 0))
sim.T = 10
assert np.max(sim.T) == 10
ts = np.linspace(0, 1e-9, 1001)
H0 = 1e5
sim.add(Zeeman((0, 0, H0)))
real_ts = []
for t in ts:
sim.run_until(t)
real_ts.append(sim.t)
print("Max Deviation = {}".format(
np.max(np.abs(ts - real_ts))))
assert np.max(np.abs(ts - real_ts)) < 1e-24
@pytest.mark.xfail(reason='dolfin >=1.5')
def test_mark_regions(self, tmpdir):
os.chdir(str(tmpdir))
sim = barmini(mark_regions=True)
sim.save_field_to_vtk(
'Demag', region='bottom', filename='demag_bottom.pvd')
sim.save_field_to_vtk('Demag', region='top', filename='demag_top.pvd')
sim.save_field_to_vtk('Demag', filename='demag_full.pvd')
sim.save_field('Demag', region='bottom', filename='demag_bottom.npy')
sim.save_field('Demag', region='top', filename='demag_top.npy')
sim.save_field('Demag', filename='demag_full.npy')
demag_bottom = np.load('demag_bottom.npy')
demag_top = np.load('demag_top.npy')
demag_full = sim.get_field_as_dolfin_function('Demag').vector().array()
assert len(demag_bottom) < len(demag_full)
assert len(demag_top) < len(demag_full)
id_top = sim.region_ids['top']
id_bottom = sim.region_ids['bottom']
submesh_top = df.SubMesh(sim.mesh, sim.region_markers, id_top)
submesh_bottom = df.SubMesh(sim.mesh, sim.region_markers, id_bottom)
# Check that the retrieved restricted demag field vectors have the
# expected sizes.
assert len(demag_top) == 3 * submesh_top.num_vertices()
assert len(demag_bottom) == 3 * submesh_bottom.num_vertices()
assert len(demag_full) == 3 * sim.mesh.num_vertices()
def test_setting_m_also_sets_the_field(self):
"""
Check that setting 'sim.m' will also set the value for the
underlying field object 'sim.m_field'.
"""
# Create a new simulation
sim = sim_with(self.mesh, Ms=8.6e5, m_init=(1, 0, 0), alpha=1.0,
unit_length=1e-9, A=13.0e-12, demag_solver='FK')
# Set sim.m to a random (normalised) vector
m_random = fnormalise(np.random.random_sample(sim.m.shape))
sim.m = m_random
# Check that both sim.m and sim.m_field have the newly assigned value
assert np.allclose(sim.m, m_random)
assert np.allclose(sim.m_field.f.vector().array(), m_random)
def test_run_until_0_does_not_change_m(self):
"""
Check that calling "sim.run_until(0)" does not affect the value of m.
"""
# Create a new simulation
sim = sim_with(self.mesh, Ms=8.6e5, m_init=(1, 0, 0), alpha=1.0,
unit_length=1e-9, A=13.0e-12, demag_solver='FK')
# Set sim.m to a random vector and run until time 0
m_random = np.random.random_sample(sim.m.shape)
sim.set_m(m_random, normalise=False)
# Check that m is unchanged
assert (sim.m == m_random).all()
# For completeness, check that running until a non-zero time does change m.
sim.run_until(1e-14)
assert not np.allclose(sim.m, m_random)
def test_can_call_save_restart_data_on_a_fresh_simulation_object(self, tmpdir):
"""
Regression test to check that we can call 'sim.save_restart_data()'
on a newly created simulation object (this used to fail because no
time integrator was present).
"""
os.chdir(str(tmpdir))
sim = sim_with(self.mesh, Ms=8.6e5, m_init=(1, 0, 0), alpha=1.0,
unit_length=1e-9, A=13.0e-12, demag_solver='FK')
sim.save_restart_data('my_restart_data.npz')
def test_length_scales(self):
"""
Test that we can call sim.length_scales() without error and it returns a string.
"""
info_string = self.sim.length_scales()
assert isinstance(info_string, str)
def test_sim_with(tmpdir):
"""
Check that we can call sim_with with random values for all parameters.
TODO: This test should arguably be more comprehensive.
"""
os.chdir(str(tmpdir))
mesh = df.UnitCubeMesh(3, 3, 3)
demag_solver_params = {'phi_1_solver': 'cg', 'phi_2_solver': 'cg',
'phi_1_preconditioner': 'ilu', 'phi_2_preconditioner': 'ilu'}
sim = sim_with(mesh, Ms=8e5, m_init=[1, 0, 0], alpha=1.0, unit_length=1e-9, integrator_backend='sundials',
A=13e-12, K1=520e3, K1_axis=[0, 1, 1], H_ext=[0, 0, 1e6], D=6.98e-3, demag_solver='FK',
demag_solver_params=demag_solver_params, name='test_simulation')
def test_timezeeman_is_updated_automatically(tmpdir):
"""
Check that the TimeZeeman.update() method is called automatically
through sim.run_until() so that the field has the correct value at
each time step.
"""
os.chdir(str(tmpdir))
def check_field_value(val):
assert(
np.allclose(H_ext.compute_field().reshape(3, -1).T, val, atol=0, rtol=1e-8))
t_off = 3e-11
t_end = 5e-11
for method_name in ['run_until', 'advance_time']:
sim = barmini()
f = getattr(sim, method_name)
field_expr = df.Expression(("0", "t", "0"), t=0, degree=1)
H_ext = TimeZeeman(field_expr, t_off=t_off)
# this should automatically register H_ext.update(), which is what we
# check next
sim.add(H_ext)
for t in np.linspace(0, t_end, 11):
f(t)
check_field_value([0, t, 0] if t < t_off else [0, 0, 0])
def test_ndt_writing_with_time_dependent_field(tmpdir):
"""
Check that when we save time-dependent field values to a .ndt
file, we actually write the values at the correct time steps (i.e.
the ones requested by the scheduler and not the ones which are
internally used by the time integrator).
"""
os.chdir(str(tmpdir))
TOL = 1e-8
field_expr = df.Expression(("0", "t", "0"), t=0, degree=1)
H_ext = TimeZeeman(field_expr, t_off=2e-11)
sim = barmini()
sim.add(H_ext)
sim.schedule('save_ndt', every=1e-12)
sim.run_until(3e-11)
Hy_expected = np.linspace(0, 3e-11, 31)
Hy_expected[20:] = 0 # should be zero after the field was switched off
f = Tablereader('barmini.ndt')
assert np.allclose(
f.timesteps(), np.linspace(0, 3e-11, 31), atol=0, rtol=TOL)
assert np.allclose(f['H_TimeZeeman_x'], 0, atol=0, rtol=TOL)
assert np.allclose(f['H_TimeZeeman_y'], Hy_expected, atol=0, rtol=TOL)
assert np.allclose(f['H_TimeZeeman_z'], 0, atol=0, rtol=TOL)
#@pytest.mark.skipif("True")
def test_removing_logger_handlers_allows_to_create_many_simulation_objects(tmpdir):
"""
When many simulation objects are created in the same scripts, the
logger will eventually complain about 'too many open files'.
Explicitly removing logger handlers should avoid this problem.
"""
os.chdir(str(tmpdir))
# avoid lots of annoying info/debugging messages
set_logging_level('WARNING')
# Temporarily decrease the soft limit for the maximum number of
# allowed open file descriptors (to make the test run faster and
# ensure reproducibility across different machines).
import resource
soft_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlimit(resource.RLIMIT_NOFILE, (42, hard_limit))
N = 150 # maximum number of simulation objects to create
mesh = df.UnitIntervalMesh(1)
Ms = 8e5
unit_length = 1e-9
def create_loads_of_simulations(N, close_logfiles=False):
"""
Helper function to create lots of simulation objects,
optionally closing previously created logfiles.
"""
for i in xrange(N):
sim = Simulation(mesh, Ms, unit_length)
if close_logfiles:
sim.close_logfile()
# The following should raise an error because lots of loggers are
# created without being deleted again.
with pytest.raises(IOError):
create_loads_of_simulations(N, close_logfiles=False)
# Remove all the file handlers created in the loop above
hdls = list(logger.handlers) # We need a copy of the list because we
# are removing handlers from it below.
for h in hdls:
if isinstance(h, logging.handlers.RotatingFileHandler):
h.stream.close() # this is essential, otherwise the file handler
# will remain open
logger.removeHandler(h)
# The following should work since we explicitly close the logfiles
# before each Simulation object goes out of scope.
create_loads_of_simulations(N, close_logfiles=True)
# Check that no file logging handler is left
# The next line creates an error, presumably because the loop above
# removes too many Handlers
print logging_status_str()
# Restore the maximum number of allowed open file descriptors. Not
# sure this is actually necessary but can't hurt.
resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))
@pytest.mark.skipif("True")
def test_schedule_render_scene(tmpdir):
"""
Check that scheduling 'render_scene' will create incremental snapshots.
Deactivated because it won't run on Jenkins without an X-Server.
"""
os.chdir(str(tmpdir))
sim = barmini()
# Save the magnetisation using the default filename
sim.schedule('render_scene', every=1e-11, filename='barmini_scene.png')
sim.run_until(2.5e-11)
assert(sorted(glob('barmini_scene_[0-9]*.png')) ==
['barmini_scene_000000.png',
'barmini_scene_000001.png',
'barmini_scene_000002.png'])
def test_sim_initialise_vortex(tmpdir, debug=False):
"""
Call sim.initialise_vortex() for a cylindrical sample and a cuboid.
If debug==True, a snapshots is saved for each of them for visual
inspection.
"""
os.chdir(str(tmpdir))
mesh = nanodisk(d=60, h=5, maxh=3.0)
sim = sim_with(mesh, Ms=8e6, m_init=[1, 0, 0], unit_length=1e-9)
def save_debugging_snapshots(sim, basename):
if debug:
sim.save_vtk(basename + '.pvd')
sim.render_scene(outfile=basename + '.png')
sim.initialise_vortex('simple', r=20)
save_debugging_snapshots(sim, 'disk_with_simple_vortex')
# Vortex core is actually bigger than the sample but this shouldn't matter.
sim.initialise_vortex('simple', r=40)
save_debugging_snapshots(sim, 'disk_with_simple_vortex2')
# Try the Feldtkeller profile
sim.initialise_vortex(
'feldtkeller', beta=15, center=(10, 0, 0), right_handed=False)
save_debugging_snapshots(sim, 'disk_with_feldtkeller_vortex')
# Try a non-cylindrical sample, too, and optional arguments.
sim = barmini()
sim.initialise_vortex('simple', r=5, center=(2, 0, 0), right_handed=False)
save_debugging_snapshots(sim, 'barmini_with_vortex')
def test_set_m_after_relaxation(tmpdir):
"""
Check that Simulation.set_m changes the magnetisation for relaxation
even after some integration has taken place.
A system with two obvious stable states for "each spin" is
initialised; one in which the spin points in the +Z direction,
and one in which the spin points in the -Z direction. The
magnetisation is initialised so that the spins point in the +Z
direction when the system is relaxed. After relaxation, the
magnetisation is changed to encourage the reverse behaviour (all
spins pointing in -Z). This test enforces that the an "internal
state" of the magnetisation is not retained between the relaxations.
"""
os.chdir(str(tmpdir))
# Construct a 2D simulation with two obvious optima.
mesh = df.RectangleMesh(df.Point(0, 0), df.Point(1, 1), 1, 1)
sim = finmag.Simulation(mesh, Ms=1, unit_length=1e-9)
sim.add(finmag.energies.UniaxialAnisotropy(1, np.array([0, 0, 1])))
# Set the spins so that they will point in +Z upon relaxation.
sim.set_m((0.1, 0.1, 1))
sim.relax()
assert sim.m_average[2] >= 0.9
# Set the spins again so that they will point in -Z upon relaxation.
print sim.integrator.m
sim.set_m((0.2, 0.2, -1))
print sim.integrator.m
sim.relax()
assert sim.m_average[2] <= -0.9
def test_sim_relax_accepts_filename(tmpdir):
"""
Check that if sim.relax() is given a filename, the relaxed state
is saved to this file.
"""
os.chdir(str(tmpdir))
sim = barmini()
sim.set_m([1, 0, 0])
sim.set_H_ext([1e6, 0, 0])
sim.relax(save_restart_data_as='barmini_relaxed.npz',
save_vtk_snapshot_as='barmini_relaxed.pvd',
stopping_dmdt=10.0)
assert(os.path.exists('barmini_relaxed.npz'))
assert(os.path.exists('barmini_relaxed.pvd'))
# Check that an existing file is overwritten.
os.remove('barmini_relaxed.pvd')
sim.relax(save_restart_data_as='barmini_relaxed.npz',
stopping_dmdt=10.0)
assert(os.path.exists('barmini_relaxed.npz'))
assert(not os.path.exists('barmini_relaxed.pvd'))
# TODO: Separate the plotting code out so that we can run the
# remaining tests without X display. (Max, 20.10.2014)
@pytest.mark.requires_X_display
def test_NormalModeSimulation(tmpdir):
os.chdir(str(tmpdir))
nx = ny = nz = 2
mesh = df.UnitCubeMesh(nx, ny, nz)
sim = normal_mode_simulation(
mesh, Ms=8e5, A=13e-12, m_init=[1, 0, 0], alpha=1.0, unit_length=1e-9, H_ext=[1e5, 1e3, 0], name='sim')
sim.relax(stopping_dmdt=10.0)
t_step = 1e-13
sim.run_ringdown(t_end=1e-12, alpha=0.01, H_ext=[1e5, 0, 0], reset_time=True,
save_ndt_every=t_step, save_m_every=t_step, m_snapshots_filename='foobar/foo_m.npy')
assert(len(glob('foobar/foo_m*.npy')) == 11)
f = Tablereader('sim.ndt')
assert(
np.allclose(f.timesteps(), np.linspace(0, 1e-12, 11), atol=0, rtol=1e-8))
sim.reset_time(1.1e-12) # hack to avoid a duplicate timestep at t=1e-12
sim.run_ringdown(t_end=2e-12, alpha=0.02, H_ext=[1e4, 0, 0], reset_time=False,
save_ndt_every=t_step, save_vtk_every=2 * t_step, vtk_snapshots_filename='baz/sim_m.pvd')
f.reload()
assert(os.path.exists('baz/sim_m.pvd'))
assert(len(glob('baz/sim_m*.vtu')) == 5)
assert(
np.allclose(f.timesteps(), np.linspace(0, 2e-12, 21), atol=0, rtol=1e-8))
sim.plot_spectrum(use_averaged_m=True)
sim.plot_spectrum(use_averaged_m=True, log=True, t_step=1.5e-12,
subtract_values='first', figsize=(16, 6), outfilename='fft_m.png')
# sim.plot_spectrum(use_averaged_m=False)
sim.plot_spectrum(use_averaged_m=False, t_ini=0.0, t_end=1e-12,
subtract_values='average', figsize=(16, 6), outfilename='fft_m_spatially_resolved.png')
assert(os.path.exists('fft_m.png'))
assert(os.path.exists('fft_m_spatially_resolved.png'))
sim.plot_spectrum(
t_step=t_step, use_averaged_m=True, outfilename='fft_m.png')
sim.find_peak_near_frequency(10e9, component='y', use_averaged_m=True)
sim.export_normal_mode_animation_from_ringdown('foobar/foo_m*.npy', peak_idx=2,
outfilename='animations/foo_peak_idx_2.pvd',
num_cycles=1, num_frames_per_cycle=4,
use_averaged_m=True)
sim.export_normal_mode_animation_from_ringdown('foobar/foo_m*.npy', f_approx=0.0, component='y',
outfilename=None, directory='animations',
num_cycles=1, num_frames_per_cycle=4,
use_averaged_m=False)
assert(os.path.exists('animations/foo_peak_idx_2.pvd'))
assert(len(glob('animations/foo_peak_idx_2*.vtu')) == 4)
# Either 'peak_idx' or both 'f_approx' and 'component' must be given
with pytest.raises(ValueError):
sim.export_normal_mode_animation_from_ringdown(
'foobar/foo_m*.npy', f_approx=0)
with pytest.raises(ValueError):
sim.export_normal_mode_animation_from_ringdown(
'foobar/foo_m*.npy', component='x')
# Check that by default snapshots are not overwritten
sim = normal_mode_simulation(
mesh, Ms=8e5, A=13e-12, m_init=[1, 0, 0], alpha=1.0, unit_length=1e-9, H_ext=[1e5, 1e3, 0], name='sim')
with pytest.raises(IOError):
sim.run_ringdown(t_end=1e-12, alpha=0.02, H_ext=[
1e4, 0, 0], save_vtk_every=2e-13, vtk_snapshots_filename='baz/sim_m.pvd')
with pytest.raises(IOError):
sim.run_ringdown(t_end=1e-12, alpha=0.02, H_ext=[
1e4, 0, 0], save_m_every=2e-13, m_snapshots_filename='foobar/foo_m.npy')
@pytest.mark.slow
def test_normal_mode_simulation_with_periodic_boundary_conditions_1x1(tmpdir):
os.chdir(str(tmpdir))
csg_string = textwrap.dedent("""
algebraic3d
solid cube = orthobrick (0, 0, 0; 50, 50, 3) -maxh = 3.0;
solid cyl = cylinder (25, 25, 0; 25, 25, 1; 20);
solid crystal = cube and not cyl;
tlo crystal;
""")
mesh = from_csg(csg_string)
sim = normal_mode_simulation(
mesh, Ms=8e5, m_init=[1, 1, 0], A=13e-12, H_ext=None, unit_length=1e-9, pbc='1d')
sim.relax()
sim.save_vtk('m_relaxed.pvd')
omega, w, relerr = sim.compute_normal_modes(solver='scipy_sparse')
sim.plot_spatially_resolved_normal_mode(0, outfilename='mode_0.png')
sim.plot_spatially_resolved_normal_mode(1, outfilename='mode_1.png')
sim.plot_spatially_resolved_normal_mode(2, outfilename='mode_2.png')
sim.export_eigenmode_animations(
[0, 1, 2], directory='animations', create_movies=False)
@pytest.mark.slow
def test_normal_mode_simulation_with_periodic_boundary_conditions_9x9(tmpdir):
os.chdir(str(tmpdir))
csg_string = textwrap.dedent("""
algebraic3d
solid cube = orthobrick (0, 0, 0; 150, 150, 3) -maxh = 10.0;
solid cylA = cylinder (25, 25, 0; 25, 25, 1; 20);
solid cylB = cylinder (75, 25, 0; 75, 25, 1; 20);
solid cylC = cylinder (125, 25, 0; 125, 25, 1; 20);
solid cylD = cylinder (25, 75, 0; 25, 75, 1; 20);
solid cylE = cylinder (75, 75, 0; 75, 75, 1; 20);
solid cylF = cylinder (125, 75, 0; 125, 75, 1; 20);
solid cylG = cylinder (25, 125, 0; 25, 125, 1; 20);
solid cylH = cylinder (75, 125, 0; 75, 125, 1; 20);
solid cylI = cylinder (125, 125, 0; 125, 125, 1; 20);
solid crystal = cube and not cylA and not cylB and not cylC and not cylD and not cylE and not cylF and not cylG and not cylH and not cylI;
tlo crystal;
""")
mesh = from_csg(csg_string)
sim = normal_mode_simulation(
mesh, Ms=8e5, m_init=[1, 0, 0], A=13e-12, H_ext=None, unit_length=1e-9, pbc='1d')
sim.relax()
sim.save_vtk('m_relaxed.pvd')
omega, w, relerr = sim.compute_normal_modes(solver='scipy_sparse')
sim.plot_spatially_resolved_normal_mode(0, outfilename='mode_0.png')
sim.plot_spatially_resolved_normal_mode(1, outfilename='mode_1.png')
sim.plot_spatially_resolved_normal_mode(2, outfilename='mode_2.png')
sim.export_eigenmode_animations(
[0, 1, 2], directory='animations', create_movies=False)
def test_H_ext_is_set_correcy_in_normal_mode_simulation(tmpdir):
os.chdir(str(tmpdir))
nx = ny = nz = 2
mesh = df.UnitCubeMesh(nx, ny, nz)
def check_H_ext(sim, value):
if value == None:
assert not sim.has_interaction('Zeeman')
else:
zeeman = sim.get_interaction('Zeeman')
assert np.allclose(zeeman.compute_field().reshape(3, -1).T, value)
def run_check(H_ext_1, H_ext_1_check_value, H_ext_2, H_ext_2_check_value):
sim = normal_mode_simulation(
mesh, Ms=8e5, A=13e-12, m_init=[1, 0, 0], alpha=1.0, unit_length=1e-9, H_ext=H_ext_1, name='sim')
check_H_ext(sim, H_ext_1)
sim.run_ringdown(t_end=0.0, alpha=0.01, H_ext=H_ext_2)
check_H_ext(sim, H_ext_2_check_value)
# Check that H_ext=None switches any existing field off during ringdown
run_check([1e5, 1e3, 0], [1e5, 1e3, 0], None, [0, 0, 0])
run_check(None, None, None, None)
def test_compute_normal_modes(tmpdir):
"""
Compute normal modes of a simple disk system and export a couple
of those modes to vtk files.
"""
os.chdir(str(tmpdir))
d = 100
h = 10
maxh = 10.0
alpha = 0.0
m_init = [1, 0, 0]
H_ext = [1e5, 0, 0]
mesh = nanodisk(d, h, maxh)
sim = normal_mode_simulation(
mesh, Ms=8e6, m_init=m_init, alpha=alpha, unit_length=1e-9, A=13e-12, H_ext=H_ext, name='nanodisk')
omega, w, rel_errors = sim.compute_normal_modes(
n_values=10, filename_mat_A='matrix_A.npy', filename_mat_M='matrix_M.npy')
logger.debug("Frequencies found: {}".format(omega))
sim.export_normal_mode_animation(
2, filename='animation/mode_2.pvd', num_cycles=1, num_snapshots_per_cycle=10, scaling=0.1)
sim.export_normal_mode_animation(
5, directory='animation', num_cycles=1, num_snapshots_per_cycle=10, scaling=0.1)
assert(os.path.exists('animation/mode_2.pvd'))
assert(len(glob('animation/mode_2*.vtu')) == 10)
assert(len(glob('animation/normal_mode_5__*_GHz*.pvd')) == 1)
assert(len(glob('animation/normal_mode_5__*_GHz*.vtu')) == 10)
@pytest.mark.slow
@pytest.mark.skipif("True")
def test_compute_eigenmode_animations(tmpdir):
"""
Compute normal modes of a simple disk system and export a couple
of those modes to vtk files.
"""
os.chdir(str(tmpdir))
d = 100
h = 10
maxh = 10.0
alpha = 0.0
m_init = [1, 0, 0]
H_ext = [1e5, 0, 0]
mesh = nanodisk(d, h, maxh)
sim = normal_mode_simulation(
mesh, Ms=8e6, m_init=m_init, alpha=alpha, unit_length=1e-9, A=13e-12, H_ext=H_ext, name='nanodisk')
omega, w, rel_errors = sim.compute_normal_modes(
n_values=10, filename_mat_A='matrix_A.npy', filename_mat_M='matrix_M.npy')
logger.debug("Frequencies found: {}".format(omega))
# Export first 4 eigenmodes without movies
sim.export_eigenmode_animations(
4, directory='animation_01', create_movies=False, num_cycles=1, num_snapshots_per_cycle=10, scaling=0.1)
assert(len(glob('animation_01/*')) == 4)
assert(len(glob('animation_01/*/*.pvd')) == 4)
assert(len(glob('animation_01/*/*.vtu')) == 40)
# Export first 3 eigenmodes with movies
sim.export_eigenmode_animations(3, directory='animation_02', create_movies=True,
num_cycles=1, num_snapshots_per_cycle=3, scaling=0.1)
# 3+3 (3 folders for the eigenmodes and 3 movie files)
assert(len(glob('animation_02/*')) == 6)
assert(len(glob('animation_02/*/*.pvd')) == 3)
assert(len(glob('animation_02/*/*.vtu')) == 9)
assert(len(glob('animation_02/*.avi')) == 3)
# Export 2 specific modes with movies
sim.export_eigenmode_animations([5, 8], directory='animation_03', create_movies=True, directory_movies='movies_03/',
num_cycles=1, num_snapshots_per_cycle=3, scaling=0.1)
assert(len(glob('animation_03/*')) == 2)
assert(len(glob('animation_03/*/*.pvd')) == 2)
assert(len(glob('animation_03/*/*.vtu')) == 6)
assert(len(glob('movies_03/*.avi')) == 2)
def test_compute_normal_modes_with_different_solvers(tmpdir):
"""
Compute normal modes of a simple nanodisk using various representative
eigensolvers (this is far from exhaustive, though).
"""
os.chdir(str(tmpdir))
d = 100
h = 10
maxh = 10.0
alpha = 0.0
m_init = [1, 0, 0]
H_ext = [1e5, 0, 0]
mesh = nanodisk(d, h, maxh)
sim = normal_mode_simulation(
mesh, Ms=8e6, m_init=m_init, alpha=alpha, unit_length=1e-9, A=13e-12, H_ext=H_ext, name='nanodisk')
# Monkey-patch the eigenvalue matrices because we're not
# interested in realistic solutions.
# sim.A = np.diag(np.arange(1, 20+1))
# sim.M = np.eye(20)
# Default solver is used without any extra arguments
omega1, w1, _ = sim.compute_normal_modes(n_values=10)
# Scipy dense non-Hermitian solver
solver2 = eigensolvers.ScipyLinalgEig()
omega2a, w2a, _ = sim.compute_normal_modes(n_values=10, solver=solver2)
omega2b, w2b, _ = sim.compute_normal_modes(
n_values=10, solver="scipy_dense")
# Scipy sparse non-Hermitian solver
solver3 = eigensolvers.ScipySparseLinalgEigs(sigma=0.0, which='LM')
omega3a, w3a, _ = sim.compute_normal_modes(n_values=10, solver=solver3)
omega3b, w3b, _ = sim.compute_normal_modes(
n_values=10, solver="scipy_sparse")
# SLEPc solver
solver4 = eigensolvers.SLEPcEigensolver(
problem_type='GNHEP', method_type='KRYLOVSCHUR', which='SMALLEST_MAGNITUDE')
#omega4a, w4a, _ = sim.compute_normal_modes(n_values=10, solver=solver4)
#omega4b, w4b, _ = sim.compute_normal_modes(n_values=10, solver="slepc_krylovschur")
with pytest.raises(TypeError):
# Cannot currently use the SLEPcEigensolver with a generalised
# eigenvalue problem.
sim.compute_normal_modes(
n_values=10, solver=solver4, use_generalised=True)
# Check that all methods compute the same eigenvalues and eigenvectors
#
# Note: Currently not all of these tests pass but we're not
# really interested in the results, only in the fact that we can
# call these solvers.
# assert(np.allclose(omega2a, omega1))
# assert(np.allclose(omega2b, omega1))
# assert(np.allclose(omega3a, omega1))
# assert(np.allclose(omega3b, omega1))
#assert(np.allclose(omega4a, omega1))
#assert(np.allclose(omega4b, omega1))
def assert_define_same_eigenspaces(vs, ws):
"""
Assert that each pair of vectors in vs and ws defines
is linearly dependent, which means that they define
the same eigenspace.
"""
for v, w in itertools.izip(vs, ws):
# Check that v is a constant multiple of w
a = v / w
assert np.allclose(a, a[0])
#assert_define_same_eigenspaces(w2a, w1)
#assert_define_same_eigenspaces(w2b, w1)
#assert_define_same_eigenspaces(w3a, w1)
#assert_define_same_eigenspaces(w3b, w1)
#assert_define_same_eigenspace(w4a, w1)
#assert_define_same_eigenspace(w4b, w1)
@pytest.mark.requires_X_display
def test_plot_spatially_resolved_normal_modes(tmpdir):
"""
Test plotting of spatially resolved normal mode profiles
"""
os.chdir(str(tmpdir))
from finmag.example.normal_modes import disk
sim = disk()
sim.compute_normal_modes()
fig = sim.plot_spatially_resolved_normal_mode(
k=0, outfilename='mode_00.png')
assert(isinstance(fig, plt.Figure))
@pytest.mark.skipif("True")
@pytest.mark.requires_X_display
def test_output_formats_for_exporting_normal_mode_animations(tmpdir):
os.chdir(str(tmpdir))
d = 100
h = 10
maxh = 10.0
alpha = 0.0
m_init = [1, 0, 0]
H_ext = [1e5, 0, 0]
mesh = nanodisk(d, h, maxh)
sim = normal_mode_simulation(
mesh, Ms=8e6, m_init=m_init, alpha=alpha, unit_length=1e-9, A=13e-12, H_ext=H_ext, name='nanodisk')
omega, _, _ = sim.compute_normal_modes(
n_values=10, filename_mat_A='matrix_A.npy', filename_mat_M='matrix_M.npy')
logger.debug("Frequencies found: {}".format(omega))
sim.export_normal_mode_animation(
0, filename='animation/mode_0.pvd', num_cycles=1, num_snapshots_per_cycle=5, color_by_axis='y')
sim.export_normal_mode_animation(
0, filename='animation/mode_0.jpg', num_cycles=1, num_snapshots_per_cycle=5, color_by_axis='y')
sim.export_normal_mode_animation(
0, filename='animation/mode_0.avi', num_cycles=1, num_snapshots_per_cycle=5, color_by_axis='y')
assert(os.path.exists('animation/mode_0.pvd'))
assert(len(glob('animation/mode_0*.vtu')) == 5)
assert(len(glob('animation/mode_0*.jpg')) == 5)
assert(os.path.exists('animation/mode_0.avi'))
with pytest.raises(ValueError):
sim.export_normal_mode_animation(0, filename='animation/mode_0.quux')
@pytest.mark.xfail
def test_setting_different_material_parameters_in_different_regions(tmpdir):
"""
In this test we create a simulation with two different regions where the
material parameters and initial magnetistaion are different for each of the
regions.
The goal is to check whether the initialisation of sucha simulation works.
However, currently we construct the dolfin Functions representing the material
parameters by hand. Ideally, there would be a simpler way, e.g. by simply
saying:
sim.set_field('Ms', 8.6e5, region='nanodisk')
This will (hopefully) eventually be implemented, but in order to do this
lot of refactoring needs to be done so that fields can be treated in a unified
way even though some of them may be defined within the mesh cells (such as
Ms, A, etc.) and some of them on the nodes. Once this goal has been reached,
this test will be a proper test of that functionality, too. For now, it
mainly documents how to set varying parameters in different regions.
"""
os.chdir(str(tmpdir))
# Create a mesh consisting of a nanodisk with a spherical article on top.
d1_disk = 50
d2_disk = 30
h_disk = 5
r_sphere = 5
center_sphere = (0, 0, 20)
nanodisk = EllipticalNanodisk(
d1=d1_disk, d2=d2_disk, h=h_disk, name='Nanodisk')
sphere = Sphere(r=r_sphere, center=center_sphere, name='Sphere')
disk_with_sphere = nanodisk + sphere
mesh = disk_with_sphere.create_mesh(maxh=10.0, filename=os.path.join(
MODULE_DIR, 'nanodisk_with_spherical_particle.xml.gz'))
logger.debug(mesh)
def is_inside_nanodisk(pt):
x, y, z = pt
return z <= h_disk + df.DOLFIN_EPS
m_init_nanodisk = [1, 0, 0]
m_init_sphere = [0, 0, 1]
alpha_nanodisk = 0.2
alpha_sphere = 0.08
A_nanodisk = 13e-12
A_sphere = 23.0
Ms_nanodisk = 8.6e5
Ms_sphere = 42.0
K1_nanodisk = 0.1
K1_sphere = 7.4e5
K1_axis_nanodisk = [1, 0, 0]
K1_axis_sphere = [0, 1, 0]
D_nanodisk = 1.0
D_sphere = 2.0
# Define the material parameters, where each of them takes a different
# value in each of the regions
def m_init(pt):
return m_init_nanodisk if is_inside_nanodisk(pt) else m_init_sphere
def alpha(pt):
return alpha_nanodisk if is_inside_nanodisk(pt) else alpha_sphere
def A(pt):
return A_nanodisk if is_inside_nanodisk(pt) else A_sphere
def Ms(pt):
return Ms_nanodisk if is_inside_nanodisk(pt) else Ms_sphere
def K1(pt):
return K1_nanodisk if is_inside_nanodisk(pt) else K1_sphere
def K1_axis(pt):
return K1_axis_nanodisk if is_inside_nanodisk(pt) else K1_axis_sphere
def D(pt):
return D_nanodisk if is_inside_nanodisk(pt) else D_sphere
# Create a simulation object with the mesh above
sim = sim_with(mesh, Ms=Ms, m_init=m_init, alpha=alpha, unit_length=1e-9,
A=A, K1=K1, K1_axis=K1_axis, D=D, name='nanodisk_with_particle')
# Construct a CellFunction representing the subdomains. Unfortunately,
# dolfin doesn't seem to provide an easy way of getting this from
# mesh.domains() directly, so we construct it manually.
# 3 represents the dimension of the mesh cells
cell_markers = mesh.domains().markers(3)
fun_subdomains = df.CellFunction('size_t', mesh)
for (cell_no, marker) in cell_markers.iteritems():
fun_subdomains[cell_no] = marker
submesh_nanodisk = df.SubMesh(mesh, fun_subdomains, 0)
submesh_sphere = df.SubMesh(mesh, fun_subdomains, 1)
plot_mesh_with_paraview(
submesh_nanodisk, camera_position=[0, -200, 100], outfile='submesh_nanodisk.png')
plot_mesh_with_paraview(
submesh_sphere, camera_position=[0, -200, 100], outfile='submesh_sphere.png')
f = df.File("m.pvd")
f << sim._m
f = df.File("alpha.pvd")
f << sim.alpha
f = df.File("A.pvd")
f << sim.get_interaction('Exchange').A
f = df.File("Ms.pvd")
f << sim.llg.Ms
f = df.File("K1.pvd")
f << sim.get_interaction('Anisotropy').K1
f = df.File("K1_axis.pvd")
f << sim.get_interaction('Anisotropy').axis
f = df.File("D.pvd")
f << sim.get_interaction('DMI').D_on_mesh
# TODO: Extract all the values of m_init, Ms, ... on each of the submeshes.
# This should give numpy arrays of dolfin.Function vectors which are constant
# and whose length matches the number of nodes in the submesh. Both of these
# properties should be checked for each field.
raise NotImplementedError
def test_compute_energies_with_non_normalised_m(tmpdir):
"""
Check that we can set the magnetisation to non-normalised values, and that the
energy terms scale either linearly or quadratically with the magnetisation.
XXX TODO: Should this be broken up into separate unit tests for the individual energies?
"""
# Create a simulation with non-uniform magnetisation and a bunch of energy
# terms
sim = finmag.example.normal_modes.disk()
K1 = 7.4e5
anis = UniaxialAnisotropy(K1=K1, axis=[1, 1, 1])
sim.add(anis)
# Compute and store the energy values for the normalised magnetisation
m0 = sim.m
energies = {}
scaling_exponents = {
'Exchange': 2, 'Anisotropy': 2, 'Demag': 2, 'Zeeman': 1}
for name in scaling_exponents.keys():
energies[name] = sim.compute_energy(name)
# Scale the magnetisation and check whether the energy terms scale
# accordingly
vol_mesh = mesh_volume(sim.mesh) * sim.unit_length ** 3
for a in np.linspace(0.0, 1.0, 20):
sim.set_m(a * m0, normalise=False)
# Check that m was indeed scaled down
m_norms = [np.linalg.norm(x) for x in sim.m.reshape(3, -1).T]
assert np.allclose(m_norms, a, atol=1e-12, rtol=1e-12)
# Check that the energy terms scale correctly
for (name, exponent) in scaling_exponents.iteritems():
if name == 'Anisotropy':
# We need a separate case for the anisotropy due to the constant that
# we're adding in the definition of the anisotropy energy.
#
# Note that in the assert statement we need a tiny value of 'atol'
# for the case a=0 because the test will fail otherwise due to small
# rounding errors when subtracting the mesh volume.
assert(np.allclose((sim.compute_energy(name) - K1 * vol_mesh), a **
exponent * (energies[name] - K1 * vol_mesh), atol=1e-31, rtol=1e-12))
else:
assert(np.allclose(
sim.compute_energy(name), a ** exponent * energies[name], atol=0, rtol=1e-12))
@pytest.mark.xfail(LooseVersion(df.__version__) >= LooseVersion('1.5.0'),
reason='API change in dolfin 1.5')
@pytest.mark.requires_X_display
def test_compute_and_plot_power_spectral_density_in_mesh_region(tmpdir):
"""
Create a simulation with two mesh regions, where the magnetisation
is uniform in each region and external fields of different
strengths are applied in each one. Record the precession for a
certain time and then compute the spectrume in the first region
only.
"""
os.chdir(str(tmpdir))
sphere1 = Sphere(r=10, center=(-20, 0, 0), name='sphere1')
sphere2 = Sphere(r=10, center=(+20, 0, 0), name='sphere2')
mesh = (sphere1 + sphere2).create_mesh(maxh=10.0)
alpha1 = 0.05
alpha2 = 0.03
H_ext_1 = [0, 0, 1e7]
H_ext_2 = [0, 0, 3.8e7]
omega1 = gamma * H_ext_1[2]
omega2 = gamma * H_ext_2[2]
def fun_alpha(pt):
return alpha1 if (pt[0] < 0) else alpha2
def fun_H_ext(pt):
return H_ext_1 if (pt[0] < 0) else H_ext_2
def fun_regions(pt):
return 'left' if (pt[0] < 0) else 'right'
sim = normal_mode_simulation(mesh, Ms=8.6e5, m_init=[
1, 0, 0], alpha=fun_alpha, H_ext=fun_H_ext, A=13e-12, unit_length=1e-9, demag_solver=None)
sim.mark_regions(fun_regions)
t_ini = 0.0
t_end = 1e-11
t_step = 1e-13
ts = np.arange(t_ini, t_end, t_step)
sim.run_ringdown(t_end, alpha=fun_alpha, H_ext=fun_H_ext,
save_m_every=t_step, m_snapshots_filename='m_precession.npy')
# Create an analytic solution for the precession in region #1 with
# which we can compare.
H = H_ext_1[2]
m_analytic = make_analytic_solution(H, alpha1)
m_dynamics = np.array([m_analytic(t) for t in ts])
mx = m_dynamics[:, 0]
my = m_dynamics[:, 1]
mz = m_dynamics[:, 2]
num_vertices = mesh.num_vertices()
psd_mx_expected = num_vertices * np.absolute(np.fft.rfft(mx)) ** 2
psd_my_expected = num_vertices * np.absolute(np.fft.rfft(my)) ** 2
psd_mz_expected = num_vertices * np.absolute(np.fft.rfft(mz)) ** 2
sim._compute_spectrum(
use_averaged_m=False, mesh_region='left', t_step=t_step, t_ini=t_ini, t_end=t_end)
# XXX TODO: The following check doesn't work yet - I'm not even
# sure it's correct. Double-check this, or find a better
# check (perhaps check the location of the peaks?!?)
#
# Check that the analytically determined power spectra are the same as the computed ones.
# RTOL = 1e-10
# assert(np.allclose(psd_mx_expected, sim.psd_mx, atol=0, rtol=RTOL))
# assert(np.allclose(psd_my_expected, sim.psd_my, atol=0, rtol=RTOL))
# assert(np.allclose(psd_mz_expected, sim.psd_mz, atol=0, rtol=RTOL))
sim.plot_spectrum(t_step=t_step, t_ini=t_ini, t_end=t_end,
mesh_region='left', ticks=11, outfilename='spectrum_left.png')
sim.plot_spectrum(t_step=t_step, t_ini=t_ini, t_end=t_end,
mesh_region='right', ticks=11, outfilename='spectrum_right.png')
logger.debug("Precession frequency 1: {} GHz".format(omega1 / 1e9))
logger.debug("Precession frequency 2: {} GHz".format(omega2 / 1e9))
@pytest.mark.skipif("True")
def test_regression_schedule_switch_off_field(tmpdir):
"""
This is a test to remind myself to attempt a bugfix for this issue.
Due to the way the Tablewriter works at the moment, there is an
error if an interaction (e.g. the Zeeman interaction) is removed
from the simulation after some of its data has been written to a
file.
Once this works, the default value for the keyword argument
'remove_interaction' in the function 'sim.switch_off_H_ext()'
should perhaps be set to True again (because it is more
efficient).
"""
sim = macrospin()
sim.schedule('save_ndt', every=1e-12)
sim.schedule('switch_off_H_ext', at=3e-12, remove_interaction=True)
sim.run_until(5e-12)
def test_document_intended_behaviour_for_H_ext(tmpdir, debug=False):
"""
The purpose of this test is simply to document how the argument
H_ext is interpreted in the run_ringdown method of the
NormalModeSimulation class. Namely, if a field was applied during
the relaxation stage then using 'run_ringdown(..., H_ext=None)'
will switch that field off!
"""
os.chdir(str(tmpdir))
mesh = df.UnitCubeMesh(3, 3, 3)
# Create a simulation with an external field
sim = normal_mode_simulation(mesh, Ms=8.6e5, alpha=0.0, m_init=[1, 0, 0],
unit_length=1e-9, A=None, H_ext=[0, 0, 1e6],
demag_solver=None, name='precession')
# Call 'run_ringdown' with no external field
sim.run_ringdown(t_end=1e-11, alpha=0.0, save_ndt_every=2e-13, H_ext=None)
# Extract the dynamics from the .ndt file
f = Tablereader('precession.ndt')
ts, m_x, m_y, m_z = f['time', 'm_x', 'm_y', 'm_z']
# Check that the magnetisation didn't change over the course of
# the simulation (since the external field was automatically
# switched off for the ringdown).
assert(len(ts) == 51)
assert(np.allclose(m_x, 1))
assert(np.allclose(m_y, 0))
assert(np.allclose(m_z, 0))
#
# Repeat the test above, but this time specify an external field
# in 'run_ringdown'. This should result in a sinusoidal
# precession.
#
H = 4.2e7 # external field strength (A/m)
sim = normal_mode_simulation(mesh, Ms=8.6e5, alpha=0.0, m_init=[1, 0, 0],
unit_length=1e-9, A=None, H_ext=[0, 0, H],
demag_solver=None, name='precession2')
sim.run_ringdown(
t_end=1e-11, alpha=0.0, save_ndt_every=1e-13, H_ext=[0, 0, H])
freq = gamma * H / (2 * pi) # expected frequency
f = Tablereader('precession2.ndt')
ts, m_x, m_y, m_z = f['time', 'm_x', 'm_y', 'm_z']
if debug:
fig = plt.figure()
ax = fig.gca()
ax.plot(ts, m_x)
ax.plot(ts, np.cos(2. * pi * freq * ts))
fig.savefig('dynamics2.png')
# Check that we get sinusoidal dynamics of the correct frequency
TOL = 1e-3
assert(len(ts) == 101)
assert(np.allclose(m_x, np.cos(2 * pi * freq * ts), atol=TOL))
assert(np.allclose(m_y, np.sin(2 * pi * freq * ts), atol=TOL))
def test_m_average_is_robust_with_respect_to_mesh_discretization(tmpdir, debug=False):
"""
This test checks that the average magnetisation takes the
different cell volumes in the mesh correctly into account, i.e. it
gives a bigger contribution to cells with a large volume than
those with a small volume.
We create a mesh representing a long strip which is coarse at the
left and and fine at the right end. Then we initialise a
magnetisation pattern which does a full turn, so that the average
magnetisation is zero and check that the computed average is close
to that.
"""
os.chdir(str(tmpdir))
lx = 50
ly = 5
lz = 3
# We create the mesh of the nanostrip using gmsh, by writing the
# following string to a file and converting it using gmsh and
# dolfin-convert.
geofile_string = textwrap.dedent("""
nz = 1; // number of z-layers
lx = 50;
ly = 5;
lz = 3;
lc_left = 2.0;
lc_right = 0.1;
Point(1) = {0, 0, 0, lc_left};
Point(2) = {lx, 0, 0, lc_right};
Point(3) = {lx, ly, 0, lc_right};
Point(4) = {0, ly, 0, lc_left};
l1 = newreg; Line(l1) = {1, 2};
l2 = newreg; Line(l2) = {2, 3};
l3 = newreg; Line(l3) = {3, 4};
l4 = newreg; Line(l4) = {4, 1};
ll1 = newreg; Line Loop(ll1) = {l1, l2, l3, l4};
s1 = newreg; Plane Surface(s1) = {ll1};
Extrude {0, 0, lz} {
Surface{s1}; Layers{nz};
}
""")
with open('nanostrip.geo', 'w') as f:
f.write(geofile_string)
# Call gmsh and dolfin-convert to bring the mesh defined above
# into a form that's readable by dolfin.
sh.gmsh('-3', '-optimize', '-optimize_netgen', '-o', 'nanostrip.msh', 'nanostrip.geo')
sh.dolfin_convert('nanostrip.msh', 'nanostrip.xml')
mesh = df.Mesh('nanostrip.xml')
# Define magnetisation that performs a full rotation from the left
# end to the right end of the strip.
def m_init(pt):
x, y, z = pt
return [0, sin(2 * pi * x / lx), cos(2 * pi * x / lx)]
sim = sim_with(mesh, Ms=8.6e5, m_init=m_init, unit_length=1e-9)
# Check that the average magnetisation is close to zero
m_avg = sim.m_average
assert(np.allclose(m_avg, [0, 0, 0], atol=1e-3))
logger.debug("m_avg: {}".format(m_avg))
# Check that simply adding up the magnetization values at the vertices
m_avg_wrong = sim.m.reshape(3, -1).sum(axis=-1)
assert(not np.allclose(m_avg_wrong, [0, 0, 0], atol=10.0))
logger.debug("m_avg_wrong: {}".format(m_avg_wrong))
if debug:
plot_mesh_with_paraview(mesh, outfile='mesh.png')
sim.render_scene(
color_by_axis='y', glyph_scale_factor=2, outfile='nanostrip.png')
def test_eigenfrequencies_scale_with_gyromagnetic_ratio(tmpdir):
"""
The eigenfrequencies should scale linearly with the value of gamma in the simulation.
Here we check this for a few values of gamma.
"""
os.chdir(str(tmpdir))
# Create a small test simulation and compute its eigenfrequencies
mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(10, 20, 3), 3, 6, 1)
sim = normal_mode_simulation(
mesh, m_init=[1, 0, 0], Ms=8e5, A=13e-12, unit_length=1e-9)
omega_ref, _, _ = sim.compute_normal_modes()
# Set gamma to some different values and check that the eigenfrequencies
# scale accordingly
for a in [0.7, 1.3, 2.445, 12.0]:
sim.gamma = a * gamma
omega, _, _ = sim.compute_normal_modes(force_recompute_matrices=True)
assert np.allclose(omega, a * omega_ref)
@pytest.mark.requires_X_display
def test_plot_dynamics(tmpdir):
"""
Check whether we can call the functions `sim.plot_dynamics`
and `sim.plot_dynamics_3d` without errors.
"""
os.chdir(str(tmpdir))
mesh = df.UnitCubeMesh(1, 1, 1)
sim = sim_with(
mesh, Ms=8e5, m_init=[1, 0, 0], A=13e-12, H_ext=[0, 0, 5e4], demag_solver=None)
sim.schedule('save_ndt', every=5e-12)
sim.run_until(5e-11)
sim.plot_dynamics(figsize=(16, 3), outfile='dynamics_2d.png')
sim.plot_dynamics_3d(figsize=(5, 5), outfile='dynamics_3d.png')
# XXX TODO: Unfortunately, calling sim.profile from within a py.test
# environment doesn't work because the namespace is not exposed to
# cProfile in the usual way. Is there a way to work around this?
@pytest.mark.xfail
def test_profile(tmpdir):
"""
Check whether we can call sim.profile() and whether it
saves profiling data to th expected files.
"""
os.chdir(str(tmpdir))
sim = barmini()
sim.profile('run_until(1e-12)')
os.path.exists('barmini.prof')
sim.profile('relax()', filename='foobar.prof', sort=-1, N=5)
os.path.exists('foobar.prof')
def test_clean_up():
"""Fake test to shutdown simulation objects"""
s = barmini()
s.instances_delete_all_others()
del s
| 76,110 | 37.265963 | 146 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim_details.py
|
import finmag
import dolfin as df
import numpy as np
from finmag.util.consts import exchange_length, bloch_parameter, \
helical_period
from finmag.util.meshes import mesh_info as mesh_information
def _get_length_scales(sim):
lengths = {}
if (sim.has_interaction('Exchange')):
A = sim.get_interaction('Exchange').A.as_constant()
Ms = sim.Ms.as_constant()
l_ex = exchange_length(A, Ms)
lengths['Exchange length'] = l_ex
if (sim.has_interaction('Anisotropy')):
K1 = sim.get_interaction('Anisotropy').K1.vector().array().mean()
l_bloch = bloch_parameter(A, K1)
lengths['Bloch parameter'] = l_bloch
if (sim.has_interaction('DMI')):
D = sim.get_interaction('DMI').D_av
l_h_period = helical_period(A, D)
lengths['Helical period'] = l_h_period
return lengths
def length_scales(sim):
"""
Returns a string all the relevant lengths scales (Exchange
length, Bloch parameters and Helical period) of the sim object
and finds the of these minimum length scales.
First checks if the sim object has an Exchange interaction
and issues a warning if no Exchange interaction is present.
If the Exchange interaction is present in the sim object,
the Exchange length is calculated as well as Bloch parameter
(Anisotropy interaction required) and the Helical period
(DMI interaction required).
"""
lengths = _get_length_scales(sim)
info_string = ""
def added_info(name, length):
return "The {} = {:.2f} nm.\n".format(name, length * 1e9)
if not (sim.has_interaction('Exchange')):
info_string += "Warning: Simulation object has no exchange. Cannot compute length scales.\n"
else:
for key, value in lengths.items():
info_string += added_info(key, value)
return info_string
def mesh_info(sim):
"""
Return a string containing some basic information about the
mesh (such as the number of cells, interior/surface triangles,
vertices, etc.).
Also print a distribution of edge lengths present in the mesh
and how they compare to the exchange length, the Bloch
parameter and the Helical period (if these can be computed, which
requires an exchange interaction (plus anisotropy for the Bloch
parameter and DMI value for the Helical period)); note that for
spatially varying material parameters the average values are used).
This information is relevant to estimate whether the mesh
discretisation is too coarse and might result in numerical
artefacts (see W. Rave, K. Fabian, A. Hubert, "Magnetic states
ofsmall cubic particles with uniaxial anisotropy", J. Magn.
Magn. Mater. 190 (1998), 332-348).
"""
info_string = "{}\n".format(mesh_information(sim.mesh))
edgelengths = [e.length() * sim.unit_length for e in df.edges(sim.mesh)]
lengths = _get_length_scales(sim)
def added_info(name, L):
(a, b), _ = np.histogram(edgelengths, bins=[0, L, np.infty])
if b == 0.0:
msg = "All edges are shorter"
msg2 = ""
else:
msg = "Warning: {:.2f}% of edges are longer".format(
100.0 * b / (a + b))
msg2 = " (this may lead to discretisation artefacts)"
info = "{} than the {} = {:.2f} nm{}.\n".format(
msg, name, L * 1e9, msg2)
return info
if not (sim.has_interaction('Exchange')):
info_string += "Warning: Simulation object has no exchange. Cannot compute exchange length(s).\n"
else:
for key, value in lengths.items():
info_string += added_info(key, value)
info_string += "\nThe minimum length is the {} = {:.2f}nm".format(
min(lengths, key=lengths.get), min(lengths.values()) * 1e9)
return info_string
| 3,876 | 34.568807 | 105 |
py
|
finmag
|
finmag-master/src/finmag/sim/magnetisation_patterns_test.py
|
import numpy as np
import finmag
from finmag.sim.magnetisation_patterns import *
from finmag.util.meshes import cylinder
def test_vortex_functions():
"""
Testing for correct polarity and 'handiness' of the two vortex functions,
vortex_simple() and vortex_feldtkeller()
"""
mesh = cylinder(10, 1, 3)
coords = mesh.coordinates()
def functions(hand, p):
f_simple = vortex_simple(r=10.1, center=(0, 0, 1),
right_handed=hand, polarity=p)
f_feldtkeller = vortex_feldtkeller(beta=15, center=(0, 0, 1),
right_handed=hand, polarity=p)
return [f_simple, f_feldtkeller]
# The polarity test evaluates the function at the mesh coordinates and
# checks that the polarity of z-component from this matches the user input
# polarity
def polarity_test(func, coords, p):
assert(np.alltrue([(p * func(coord)[2] > 0) for coord in coords]))
# This function finds cross product of radius vector and the evaluated
# function vector, rxm. The z- component of this will be:
# - negative for a clockwise vortex
# - positive for a counter-clockwise vortex
# When (rxm)[2] is multiplied by the polarity, p, (rxm)[2] * p is:
# - negative for a left-handed state
# - positive for a right-handed state
def handiness_test(func, coords, hand, p):
r = coords
m = [func(coord) for coord in coords]
cross_product = np.cross(r, m)
if hand is True:
assert(np.alltrue((cross_product[:, 2] * p) > 0))
elif hand is False:
assert(np.alltrue((cross_product[:, 2] * p) < 0))
# run the tests
for hand in [True, False]:
for p in [-1, 1]:
funcs = functions(hand, p)
for func in funcs:
polarity_test(func, coords, p)
handiness_test(func, coords, hand, p)
# Final sanity check: f_simple should yield zero z-coordinate
# outside the vortex core radius, and the magnetisation should
# curl around the center.
f_simple = vortex_simple(r=20, center=(0, 0, 1),
right_handed=True, polarity=1)
assert(np.allclose(f_simple((21, 0, 0)), [0, 1, 0]))
assert(np.allclose(f_simple((-16, 16, 20)),
[-1. / np.sqrt(2), -1. / np.sqrt(2), 0]))
| 2,381 | 37.419355 | 78 |
py
|
finmag
|
finmag-master/src/finmag/sim/init.py
|
import logging
import argparse
import dolfin as df
import ufl
import ffc
from finmag.util import configuration, ansistrm
from finmag.util.helpers import start_logging_to_file
_FINMAG_LOG_LEVELS = {
"EXTREMEDEBUG": 5,
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL
}
_DOLFIN_LOG_LEVELS = {
"DEBUG": df.DEBUG,
"INFO": df.INFO,
"WARN": df.WARNING,
"WARNING": df.WARNING,
"ERROR": df.ERROR,
"CRITICAL": df.CRITICAL,
"PROGRESS": df.PROGRESS,
}
# If no finmag configuration file exists, create a default one in ~/.finmagrc.
configuration.create_default_finmagrc_file()
# Read the settings from the configuration file first.
logfiles = configuration.get_config_option("logging", "logfiles", "").split()
finmag_level = _FINMAG_LOG_LEVELS[
configuration.get_config_option("logging", "console_logging_level", "DEBUG")]
dolfin_level = _DOLFIN_LOG_LEVELS[
configuration.get_config_option("logging", "dolfin_logging_level", "WARNING")]
color_scheme = configuration.get_config_option(
"logging", "color_scheme", "light_bg")
# Parse command line options.
parser = argparse.ArgumentParser(
description='Parse the logging level and colour scheme.')
parser.add_argument("--verbosity", default=None,
choices=(
"extremedebug", "debug", "info", "warning", "error", "critical"),
help="Set the finmag logging level.")
parser.add_argument("--colour", default=None,
choices=("dark_bg", "light_bg", "none"),
help="Set the logging colour scheme.")
# Parse only known args so py.test can parse the remaining ones.
args, _ = parser.parse_known_args()
# The parsed command line options can override the configuration file settings.
if args.verbosity:
finmag_level = _FINMAG_LOG_LEVELS[args.verbosity.upper()]
if args.colour:
color_scheme = args.colour
# Apply the settings.
df.set_log_level(dolfin_level) # use root logger
# to control level separately from dolfin
logger = logging.getLogger(name='finmag')
logger.setLevel(logging.DEBUG)
# We set messages from UFL and FFC to 'WARNING' level.
# Maybe these should also be controlled by dolfin_level?
ufl_logger = logging.getLogger(name='UFL')
ffc_logger = logging.getLogger(name='FFC')
ufl_logger.setLevel('WARNING')
ffc_logger.setLevel('WARNING')
ch = ansistrm.ColorizingStreamHandler()
ch.setLevel(finmag_level)
formatter = logging.Formatter(
'[%(asctime)s] %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
try:
ch.level_map = ansistrm.level_maps[color_scheme]
except KeyError:
raise ValueError("Unkown color scheme: '{}' (allowed values: {})".format(
color_scheme, ansistrm.level_maps.keys()))
logger.addHandler(ch)
# Now add file handlers for all logfiles listed in the finmag
# configuration file.
for f in logfiles:
# XXX TODO: There still seems to be a small bug here. If a logfile
# exists whose size is greater than the specified limit then the
# RotatingFileHandler appears to leave it untouched. Thus we
# should explicitly test for any existing logfiles here which are
# too large and to a manual rollover if this is the case!
maxBytes = configuration.get_config_option("logging", "maxBytes", 51200)
backupCount = configuration.get_config_option("logging", "backupCount", 1)
start_logging_to_file(f, formatter=formatter, mode='a', level=finmag_level,
rotating=True, maxBytes=maxBytes, backupCount=backupCount)
| 3,630 | 35.676768 | 89 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim_relax.py
|
import functools
import logging
from finmag.util.consts import ONE_DEGREE_PER_NS
from finmag.util.helpers import compute_dmdt
log = logging.getLogger(name="finmag")
ONE_DEGREE_PER_NS = 17453292.5 # in rad/s
def relax(sim, save_vtk_snapshot_as=None, save_restart_data_as=None,
stopping_dmdt=1.0, dt_limit=1e-10, dmdt_increased_counter_limit=10):
"""
Run the simulation until the magnetisation has relaxed.
This means the magnetisation reaches a state where its change over time
at each node is smaller than the threshold `stopping_dm_dt` (which
should be given in multiples of degree/nanosecond).
If `save_vtk_snapshot_as` and/or `restart_restart_data_as` are
specified, a vtk snapshot and/or restart data is saved to a
file with the given name. This can also be achieved using the
scheduler but provides a slightly more convenient mechanism.
Note that any previously existing files with the same name
will be automatically overwritten!
"""
log.info("Simulation will run until relaxation of the magnetisation.")
log.debug("Relaxation parameters: stopping_dmdt={} (degrees per "
"nanosecond), dt_limit={}, dmdt_increased_counter_limit={}"
.format(stopping_dmdt, dt_limit, dmdt_increased_counter_limit))
dt0 = 1e-14 # Initial dt.
# Relaxation information is stored in a dictionary. This data is lost if
# another relaxation takes place after this one.
sim.relaxation = {}
# Define relaxation event.
def dt_interval(self):
"""
This function calculates the interval given the internal state of an
event instance.
The first time this method is called, variables are initialised to
starting values. This method then calculates the timestep for the next
iteration.
"""
# If the initial variables have not been defined, we must be in the
# first iteration. Initialise the variables now.
if 'dt' not in sim.relaxation.keys():
sim.relaxation['dt'] = dt0
sim.relaxation['dt_increment_multi'] = 1.5
sim.relaxation['dt_limit'] = dt_limit
sim.relaxation['dmdts'] = []
sim.relaxation['stopping_dmdt'] = stopping_dmdt * ONE_DEGREE_PER_NS
# Otherwise, calculate new dt value.
else:
if sim.relaxation['dt'] < sim.relaxation['dt_limit'] /\
sim.relaxation['dt_increment_multi']:
if len(sim.relaxation['dmdts']) >= 2 and\
sim.relaxation['dmdts'][-1][1] <\
sim.relaxation['dmdts'][-2][1]:
sim.relaxation['dt'] *=\
sim.relaxation['dt_increment_multi']
else:
sim.relaxation['dt'] = sim.relaxation['dt_limit']
return sim.relaxation['dt']
def trigger():
"""
This function calculates dm/dt and the energy of the magnetisation 'm',
and determines whether or not the magnetisation in this simulation is
relaxed.
The above result is differenced with the result from the previous
iteration (if any). The integration is stopped when dm/dt falls below
'stopping_dmdt', or when the system is deemed to be diverging (that is
to say, when dm/dt and energy increase simultaneously more than
'dmdt_increased_counter_limit' times).
"""
# If this is the first iteration, define initial variables.
if 'energies' not in sim.relaxation.keys():
sim.relaxation['energies'] = []
sim.relaxation['dmdt_increased_counter'] = 0
sim.relaxation[
'dmdt_increased_counter_limit'] = dmdt_increased_counter_limit
# Otherwise, find dm/dt and energy and compare.
else:
sim.relaxation['dmdts'].append([sim.t, compute_dmdt(
sim.relaxation['last_time'], sim.relaxation['last_m'], sim.t, sim.m)])
sim.relaxation['energies'].append(sim.total_energy())
# Continue iterating if dm/dt is not low enough.
if sim.relaxation['dmdts'][-1][1] >\
sim.relaxation['stopping_dmdt']:
log.debug("At t={:.3g}, last_dmdt={:.3g} * stopping_dmdt, "
"next dt={:.3g}."
.format(sim.t, sim.relaxation['dmdts'][-1][1] /
sim.relaxation['stopping_dmdt'],
sim.relaxation['dt']))
# If dm/dt and energy have both increased, start checking for
# non-convergence.
if len(sim.relaxation['dmdts']) >= 2:
if (sim.relaxation['dmdts'][-1][1] >
sim.relaxation['dmdts'][-2][1] and
sim.relaxation['energies'][-1] >
sim.relaxation['energies'][-2]):
# Since dm/dt has increased, we increment the counter.
sim.relaxation['dmdt_increased_counter'] += 1
log.debug("dmdt {} times larger than last time "
"(counting {}/{})."
.format(sim.relaxation['dmdts'][-1][1] /
sim.relaxation['dmdts'][-2][1],
sim.relaxation['dmdt_increased_counter'],
sim.relaxation['dmdt_increased_counter_limit']))
# The counter is too high, so we leave.
if sim.relaxation['dmdt_increased_counter'] >=\
sim.relaxation['dmdt_increased_counter_limit']:
log.warning("Stopping time integration after dmdt "
"increased {} times without a decrease in "
"energy (which indicates that something "
"might be wrong)."
.format(sim.relaxation['dmdt_increased_counter_limit']))
return False
# Since dm/dt is low enough, stop the integration.
if sim.relaxation['dmdts'][-1][1] <=\
sim.relaxation['stopping_dmdt']:
log.debug("Stopping integration at t={:.3g}, with dmdt={:.3g},"
" smaller than threshold={:.3g}."
.format(sim.t, sim.relaxation['dmdts'][-1][1],
float(sim.relaxation['stopping_dmdt'])))
return False
# Update values for the next integration.
sim.relaxation['last_m'] = sim.m.copy()
sim.relaxation['last_time'] = sim.t
dt_interval = functools.partial(dt_interval, sim)
sim.scheduler.add(trigger, every=dt_interval,
after=1e-14 if sim.t < 1e-14 else sim.t)
sim.scheduler.run(sim.integrator, sim.callbacks_at_scheduler_events)
sim.integrator.reinit() # TODO: Is this still needed now that set_m also calls reinit()?
# However, there it happens *after* setting m.
sim.set_m(sim.m)
log.info("Relaxation finished at time t = {:.2g}.".format(sim.t))
# Save a vtk snapshot and/or restart data of the relaxed state.
if save_vtk_snapshot_as is not None:
sim.save_vtk(save_vtk_snapshot_as, overwrite=True)
if save_restart_data_as is not None:
sim.save_restart_data(save_restart_data_as)
| 7,492 | 44.689024 | 93 |
py
|
finmag
|
finmag-master/src/finmag/sim/magnetisation_patterns.py
|
import finmag
from finmag.util import helpers
from copy import copy
import logging
import math
import numpy as np
from numpy.linalg import norm
log = logging.getLogger("finmag")
def initialise_helix_2D(sim, period, axis=np.array([1, 0])):
"""
Initialise the magnetisation to a pattern resembling a helix along a given
direction. By default, helices along the first dimension will be created.
The resulting magnetisation should be relaxed to obtain the most natural
helical state possible.
*Assumptions*: It is assumed that the mesh is a 2D mesh. If it is not, the
helix will be projected in higher dimensions.
*Arguments*:
period
Float representing the period of the helix in mesh co-ordinates.
axis
Numpy array containing direction of helix.
This function returns nothing.
"""
# Check for sane values.
if np.linalg.norm(axis) == 0:
raise ValueError("Axis ({}) norm is zero.".format(axis))
if period <= 0:
raise ValueError("Helix period ({}) cannot be zero or less."
.format(period))
# Normalise the axis.
axis = axis / np.linalg.norm(axis)
# Create rotation matrix to convert mesh co-ordinates to co-ordinates of
# the axis and it's right-handed perpendicular. In this new system, the
# second dimension corresponds to the axis direction.
cos_theta = axis[0]
theta = np.arccos(cos_theta)
sin_theta = np.sin(theta)
R = np.matrix(([cos_theta, sin_theta],
[-sin_theta, cos_theta]))
# Build the function.
def m_helical(pos):
# Convert to rotated co-ordinate system.
pos_xy = np.array([pos[0], pos[1]])
pos_rot_matrix = R * np.transpose(np.matrix(pos_xy))
pos_rot = np.array((pos_rot_matrix.item(0), pos_rot_matrix.item(1)))
# Find magnetisation components.
mx_r = np.cos((1 - (pos_rot[1] / period)) * 2 * np.pi)
my_r = 0
mz = np.sin((1 - (pos_rot[1] / period)) * 2 * np.pi)
# Rotate magnetisation back into mesh co-ordinates.
m = R * np.matrix(([mx_r], [my_r]))
mx = m.item(0)
my = m.item(1)
# Normalise and return.
out = np.array([mx, my, mz], dtype="float64")
return out / np.linalg.norm(out)
# Use the above function to initialise the magnetisation.
sim.set_m(m_helical)
def initialise_skyrmions(sim, skyrmionRadius, centres="singleCentre"):
"""
Initialise the magnetisation to a pattern resembling skyrmions with defined
centres. By default, a single skyrmion at (0, 0) will be created. The
resulting magnetisation should be relaxed to obtain the most natural
skyrmion possible. If skyrmions are found to overlap, a ValueError will be
raised. If centres is empty, the ferromagnetic state will be initialised.
*Assumptions*: It is assumed that the mesh is a 2D mesh. If it is not, the
skyrmion will be projected in higher dimensions.
*Arguments*:
centres
Numpy array containing co-ordinates stored by numpy arrays.
skyrmionRadius
The radius of the skyrmion in mesh co-ordinates (single value for all
skyrmions).
This function returns nothing.
"""
if centres == "singleCentre":
dim = sim.mesh.topology().dim()
centres = np.array([np.zeros(dim)])
numCentres = len(centres)
# Initialise ferromagnetic state if there are no centres.
if numCentres == 0:
def m_ferromagnetic(pos):
return np.array([0, 0, 1], dtype="float64")
sim.set_m(m_ferromagnetic)
return
# Determine whether there is skyrmion overlap.
if numCentres > 1:
for zI in xrange(numCentres):
for zJ in xrange(zI + 1, numCentres):
if norm(centres[zI] - centres[zJ]) < 2 * skyrmionRadius:
raise ValueError("Skyrmions at centres {} and {} overlap."
.format(centres[zI], centres[zJ]))
# Build the function
def m_skyrmions(pos):
# For each skyrmion, check if the position vector exists within it.
# Will pass until one is obtained.
for zI in xrange(numCentres):
loc = copy(pos) # Assignment means the original will change if "="
# operator is used.
# Convert the position vector into relative vector with respect to
# this centre.
loc = loc - centres[zI]
# Find the radius component in cylindrical form.
r = norm(loc)
# Check to see if this vector is within this circle. If it isn't,
# check the next centre by skipping the rest of this iteration.
if r > skyrmionRadius:
continue
# Convert position into cylindrical form, using r defined
# previously, and "t" as the argument.
if abs(loc[0]) < 1e-6:
if abs(loc[1]) < 1e-6:
t = 0
elif loc[1] > 0:
t = np.pi / 2.
else:
t = -np.pi / 2.
else:
t = np.arctan2(loc[1], loc[0])
# Define vector components inside the skyrmion:
mz = -np.cos(np.pi * r / skyrmionRadius)
mt = np.sin(np.pi * r / skyrmionRadius)
# Convert to cartesian form and normalize.
mx = -np.sin(t) * mt
my = np.cos(t) * mt
out = np.array([mx, my, mz], dtype="float64")
return out / norm(out)
# If control reaches here, it means that the vector is not in any
# circle. As such, return the corresponding ferromagnetic-state-like
# vector.
return np.array([0., 0., 1.], dtype="float64")
# Use the above function to initialise the magnetisation.
sim.set_m(m_skyrmions)
def initialise_skyrmion_hexlattice_2D(sim, meshX, meshY, tileScaleX=1,
skyrmionRadiusScale=0.2):
"""
Initialise the magnetisation to a pattern resembling a hexagonal
lattice of 2D skyrmions which should be relaxed to obtain the most
natural lattice possible. The most stable of lattices will exist on
meshes whose horizontal dimension is equal to the vertical tile
dimension / sqrt(3); if the mesh does not (approximately) conform to
these dimensions, a warning will be raised (because this will result in
elliptical skyrmions being created).
*Assumptions*: It is assumed that the mesh is a rectangular 2D mesh. If
it is not, the 2D hexagonal lattice will be projected in
higher dimensions.
*Arguments*:
meshX
The length of the rectangular mesh in the first dimension (the 'X'
direction).
meshY
As above, but for the second dimension (the 'Y' direction).
tileScaleX=1
The fraction of the size of the tile in the first dimension (the
'X' direction) to the size of the mesh. For example, if this
quantity is equal to 0.5, there will be two tiles in the first
dimension.
skyrmionRadiusScale=0.3
The radius of the skyrmion defined as a fraction of the tile in the
first dimension ('X' direction).
This function returns nothing.
"""
# Ensure the mesh is of the dimensions stated above, and raise a
# warning if it isn't.
ratioX = abs(meshX / float(meshY) - np.sqrt(3))
ratioY = abs(meshY / float(meshX) - np.sqrt(3))
if ratioX > 0.05 and ratioY > 0.05:
log.warning("Mesh dimensions do not accurately support hexagonal" +
" lattice formation! (One should be a factor of sqrt" +
"(3) greater than the other.)")
# Calculate lengths of tiles and the skyrmion radius in mesh
# co-ordinates.
tileLengthX = meshX * tileScaleX
tileLengthY = meshY * tileScaleX
skyrmionRadius = tileLengthX * skyrmionRadiusScale
# Build the function.
def m_skyrmion_hexlattice(pos):
"""
Function that takes a position vector of a point in a vector field
and returns a vector such that the vector field forms a hexagonal
lattice of skyrmions of the field is toroidal. This only works for
rectangular meshes whos horizontal tile dimension is equal to the
vertical tile dimension / sqrt(3)."""
# Convert position into tiled co-ordinates.
cx = pos[0] % tileLengthX - tileLengthX / 2.
cy = pos[1] % tileLengthY - tileLengthY / 2.
# ==== Define first skyrmion quart ====#
# Define temporary cartesian co-ordinates (tcx, tcy) that can be
# used to define a polar co-ordinate system.
tcx = cx - tileLengthX / 2.
tcy = cy
r = pow(pow(tcx, 2) + pow(tcy, 2), 0.5)
t = np.arctan2(tcy, tcx)
tcx_flip = cx + tileLengthX / 2.
r_flip = pow(pow(tcx_flip, 2) + pow(tcy, 2), 0.5)
t_flip = np.arctan2(tcy, tcx_flip)
# Populate vector field:
mz = -1 + 2 * r / skyrmionRadius
mz_flip = -1 + 2 * r_flip / skyrmionRadius
# Replicate to other half-plane of the vector field and convert to
# cartesian form.
if(mz <= 1):
mt = np.sin(np.pi * r / skyrmionRadius)
mx_1 = -np.sin(t) * mt
my_1 = np.cos(t) * mt
mz_1 = mz
elif(mz_flip < 1):
mt = -np.sin(np.pi * r_flip / skyrmionRadius)
mz_1 = mz_flip
mx_1 = np.sin(t_flip) * mt
my_1 = -np.cos(t_flip) * mt
elif(mz > 1):
mx_1 = 0
my_1 = 0
mz_1 = 1
# ==== Define second skyrmion quart ====#
# Define temporary cartesian co-ordinates (tcx, tcy) that can be
# used to define polar co-ordinate system.
tcx = cx
tcy = cy - tileLengthY / 2.
r = pow(pow(tcx, 2) + pow(tcy, 2), 0.5)
t = np.arctan2(tcy, tcx)
tcy_flip = cy + tileLengthY / 2.
r_flip = pow(pow(tcx, 2) + pow(tcy_flip, 2), 0.5)
t_flip = np.arctan2(tcy_flip, tcx)
# Populate vector field:
mz = -1 + 2 * r / skyrmionRadius
mz_flip = -1 + 2 * r_flip / skyrmionRadius
# Replicate to other half-plane of the vector field and convert to
# cartesian form.
if(mz <= 1):
mt = np.sin(np.pi * r / skyrmionRadius)
mx_2 = -np.sin(t) * mt
my_2 = np.cos(t) * mt
mz_2 = mz
elif(mz_flip < 1):
mt = -np.sin(np.pi * r_flip / skyrmionRadius)
mz_2 = mz_flip
mx_2 = np.sin(t_flip) * mt
my_2 = -np.cos(t_flip) * mt
elif(mz > 1):
mx_2 = 0
my_2 = 0
mz_2 = 1
#==== Combine and normalize. ====#
mx = mx_1 + mx_2
my = my_1 + my_2
mz = mz_1 + mz_2 - 1
out = np.array([mx, my, mz], dtype="float64")
return out / norm(out)
# Use the above function to initialise the magnetisation.
sim.set_m(m_skyrmion_hexlattice)
def vortex_simple(r, center, right_handed=True, polarity=+1):
"""
Returns a function f: (x,y,z) -> m representing a vortex magnetisation
pattern where the vortex lies in the x/y-plane (i.e. the magnetisation is
constant along the z-direction), the vortex core is centered around the
point `center` and the vortex core has radius `r`. More precisely, m_z=1 at
the vortex core center and m_z falls off in a radially symmetric way until
m_z=0 at a distance `r` from the center. If `right_handed` is True then the
vortex curls counterclockwise around the z-axis, otherwise clockwise. It
should be noted that the returned function `f` only represents an
approximation to a true vortex state, so this can be used to initialise the
magnetisation in a simulation which is then relaxed.
Note that both `r` and the coordinates of `center` should be given in mesh
coordinates, not in metres.
"""
def f(pt):
x = pt[0]
y = pt[1]
xc = x - center[0]
yc = y - center[1]
phi = math.atan2(yc, xc)
rho = math.sqrt(xc ** 2 + yc ** 2)
# To start with, create a right-handed vortex with polarity 1.
if rho < r:
theta = 2 * math.atan(rho / r)
mz = math.cos(theta)
mx = -math.sin(theta) * math.sin(phi)
my = math.sin(theta) * math.cos(phi)
else:
mz = 0
mx = -math.sin(phi)
my = math.cos(phi)
# If we actually want a different polarity, flip the z-coordinates
if polarity < 0:
mz = -mz
# Adapt the chirality accordingly
if ((polarity > 0) and (not right_handed)) or\
((polarity < 0) and right_handed):
mx = -mx
my = -my
return (mx, my, mz)
return f
def vortex_feldtkeller(beta, center, right_handed=True, polarity=+1):
"""
Returns a function f: (x,y,z) -> m representing a vortex
magnetisation pattern where the vortex lies in the x/y-plane (i.e.
the magnetisation is constant along the z-direction), the vortex
core is centered around the point `center` and the m_z component
falls off exponentially as given by the following formula, which
is a result by Feldtkeller and Thomas [1].:
m_z = exp(-2*r^2/beta^2).
Here `r` is the distance from the vortex core centre and `beta` is
a parameter, whose value is taken from the first argument to this
function.
[1] E. Feldtkeller and H. Thomas, "Struktur und Energie von
Blochlinien in Duennen Ferromagnetischen Schichten", Phys.
Kondens. Materie 8, 8 (1965).
"""
beta_sq = beta ** 2
def f(pt):
x = pt[0]
y = pt[1]
# To start with, create a right-handed vortex with polarity 1.
xc = x - center[0]
yc = y - center[1]
phi = math.atan2(yc, xc)
r_sq = xc ** 2 + yc ** 2
mz = math.exp(-2.0 * r_sq / beta_sq)
mx = -math.sqrt(1 - mz * mz) * math.sin(phi)
my = math.sqrt(1 - mz * mz) * math.cos(phi)
# If we actually want a different polarity, flip the z-coordinates
if polarity < 0:
mz = -mz
# Adapt the chirality accordingly
if ((polarity > 0) and (not right_handed)) or\
((polarity < 0) and right_handed):
mx = -mx
my = -my
return (mx, my, mz)
return f
def initialise_vortex(sim, type, center=None, **kwargs):
"""
Initialise the magnetisation to a pattern that resembles a vortex state.
This can be used as an initial guess for the magnetisation, which should
then be relaxed to actually obtain the true vortex pattern (in case it is
energetically stable).
If `center` is None, the vortex core centre is placed at the sample centre
(which is the point where each coordinate lies exactly in the middle
between the minimum and maximum coordinate for each component). The vortex
lies in the x/y-plane (i.e. the magnetisation is constant in z-direction).
The magnetisation pattern is such that m_z=1 in the vortex core centre, and
it falls off in a radially symmetric way.
The exact vortex profile depends on the argument `type`. Currently the
following types are supported:
'simple':
m_z falls off in a radially symmetric way until m_z=0 at
distance `r` from the centre.
'feldtkeller':
m_z follows the profile m_z = exp(-2*r^2/beta^2), where `beta`
is a user-specified parameter.
All provided keyword arguments are passed on to functions which implement
the vortex profiles. See their documentation for details and other allowed
arguments.
"""
coords = np.array(sim.mesh.coordinates())
if center is None:
center = 0.5 * (coords.min(axis=0) + coords.max(axis=0))
vortex_funcs = {'simple': vortex_simple,
'feldtkeller': vortex_feldtkeller}
kwargs['center'] = center
try:
fun_m_init = vortex_funcs[type](**kwargs)
log.debug("Initialising vortex of type '{}' with arguments: {}".
format(type, kwargs))
except KeyError:
raise ValueError("Vortex type must be one of {}. Got: {}".
format(vortex_funcs.keys(), type))
sim.set_m(fun_m_init)
def initialise_target_state(diskRadius, centre, rings, right_handed=False):
"""
Function to initialise target state (as seen in [1]).
'diskRadius' is the radial length from the centre of the target to
the outer edge (this function will work on non cylindrical objects)
'centre' is the centre of the target state. If 'centre' in None, the
target centre will automatically be set at (0,0,0). Note that the centre
of the target has a positive magnetisation.
'rings' is the number of positively magnetised rings around the
(positively magnetised) central target. 'rings' can also take non-integer
values. It cannot be zero though.
Note that handedness is preserved throughout the system, thus as mz changes
from positive to negative, the 'vortex' direction will flip accordingly.
[1] A.B. Butenko et al. Theory of ortex states in magnetic nanodisks with
induced Dzyaloshinskii-Moriya interactions. Phys. Rev. B 80, 134410 (2009)
"""
if rings == 0:
raise ValueError("Number of rings cannot be zero")
ringRadius = diskRadius / float(rings)
def f(pt):
x = pt[0]
y = pt[1]
xc = x - centre[0]
yc = y - centre[1]
rho = math.sqrt(xc ** 2 + yc ** 2)
theta = 2 * math.atan(rho / ringRadius)
phi = math.atan2(yc, xc)
# first create a (right handed) vortex structure but with modulating mz,
# as seen in target state.
mz = math.cos(2 * np.pi * rho / ringRadius)
mx = -math.sin(theta) * math.sin(phi)
my = math.sin(theta) * math.cos(phi)
# if the mz is negative, flip the direction of the vortex direction, to
# preserve the chirality/handedness.
if (mz < 0):
mx = -mx
my = -my
# change to left handedness if required.
if not right_handed:
mx = -mx
my = -my
return (mx, my, mz)
return f
| 18,518 | 33.550373 | 80 |
py
|
finmag
|
finmag-master/src/finmag/sim/__init__.py
|
# FinMag - a thin layer on top of FEniCS to enable micromagnetic multi-physics simulations
# Copyright (C) 2012 University of Southampton
# Do not distribute
#
# CONTACT: [email protected]
from init import *
| 213 | 25.75 | 90 |
py
|
finmag
|
finmag-master/src/finmag/sim/sim_helpers.py
|
import time
import finmag
import logging
import shutil
import os
import types
import dolfin as df
import numpy as np
from datetime import datetime, timedelta
from finmag.util.consts import ONE_DEGREE_PER_NS
from finmag.util.meshes import nodal_volume
log = logging.getLogger("finmag")
def save_ndt(sim):
"""
Save the average field values (such as the magnetisation) to a file.
The filename is derived from the simulation name (as given when the
simulation was initialised) and has the extension .ndt'.
"""
if sim.driver == 'cvode':
log.debug("Saving data to ndt file at t={} "
"(sim.name={}).".format(sim.t, sim.name))
else:
raise NotImplementedError("Only cvode driver known.")
sim.tablewriter.save()
def save_m(sim, filename=None, incremental=False, overwrite=False):
"""
Convenience function to save the magnetisation to a file (as a numpy array).
The following two calls do exactly the same thing:
sim.save_m(...)
sim.save_field('m', ...)
Thus see the documentation of sim.save_field() for details on
the arguments.
"""
sim.save_field(
'm', filename=filename, incremental=incremental, overwrite=overwrite)
def create_backup_file_if_file_exists(filename, backupextension='.backup'):
if os.path.exists(filename):
backup_file_name = filename + backupextension
shutil.copy(filename, backup_file_name)
log.extremedebug("Creating backup %s of %s" %
(backup_file_name, filename))
def canonical_restart_filename(sim):
return sim.sanitized_name + "-restart.npz"
def create_non_existing_parent_directories(filename):
"""
Create parent directories of the given file if they do not already exist.
"""
dirname = os.path.dirname(os.path.abspath(filename))
if not os.path.exists(dirname):
log.debug(
"Creating non-existing parent directory: '{}'".format(dirname))
os.makedirs(dirname)
def save_restart_data(sim, filename=None):
"""Given a simulation object, this function saves the current
magnetisation, and some integrator metadata into a file. """
# create metadata
integrator_stats = sim.integrator.stats()
datetimetuple = datetime.now()
drivertype = 'cvode' # we should deduce this from sim object XXX
simtime = sim.t
# fix filename
if filename == None:
filename = canonical_restart_filename(sim)
create_backup_file_if_file_exists(filename)
create_non_existing_parent_directories(filename)
np.savez_compressed(filename,
m=sim.integrator.llg._m_field.get_numpy_array_debug(),
stats=integrator_stats,
simtime=simtime,
datetime=datetimetuple,
simname=sim.name,
driver=drivertype)
log.debug("Have saved restart data at t=%g to %s "
"(sim.name=%s)" % (sim.t, filename, sim.name))
def load_restart_data(filename_or_simulation):
"""Given a file name, load the restart data saved in that file
name and return as dictionary. If object is simulation instance,
use canonical name."""
if isinstance(filename_or_simulation, finmag.Simulation):
filename = canonical_restart_filename(filename_or_simulation)
elif isinstance(filename_or_simulation, types.StringTypes):
filename = filename_or_simulation
else:
ValueError("Can only deal with simulations or filenames, "
"but not '%s'" % type(filename_or_simulation))
data = np.load(filename)
# strip of arrays where we do not want them:
data2 = {}
for key in data.keys():
# the 'tolist()' command returns dictionary and datetime objects
# when wrapped up in numpy array
if key in ['stats', 'datetime', 'simtime', 'simname', 'driver']:
data2[key] = data[key].tolist()
else:
data2[key] = data[key]
return data2
def get_submesh(sim, region=None):
"""
Return the submesh associated with the given region.
"""
if region == None:
submesh = sim.mesh
else:
region_id = sim._get_region_id(region)
submesh = df.SubMesh(sim.mesh, sim.region_markers, region_id)
return submesh
def run_normal_modes_computation(sim, params_relax=None, params_precess=None):
"""
Run a normal modes computation consisting of two stages. During the first
stage, the simulation is relaxed with the given parameters. During the
second ('precessional') stage, the computation is run up to a certain
time. The magnetisation can be saved at regular intervals (specified by
the corresponding parameters in params_relax and params_precess), and this
can be used for post-processing such as plotting normal modes, etc.
XXX TODO: Document the parameter dictionaries params_relax, params_precess.
"""
default_params_relax = {
'alpha': 1.0,
'H_ext': None,
'save_ndt_every': None,
'save_vtk_every': None,
'save_npy_every': None,
'save_relaxed_vtk': True,
'save_relaxed_npy': True,
'filename': None
}
default_params_precess = {
'alpha': 0.0,
'H_ext': None,
'save_ndt_every': 1e-11,
'save_vtk_every': None,
'save_npy_every': None,
't_end': 10e-9,
'filename': None
}
# if params_precess == None:
# raise ValueError("No precession parameters given. Expected params_precess != None.")
def set_simulation_parameters_and_schedule(sim, params, suffix=''):
sim.alpha = params['alpha']
sim.set_H_ext = params['H_ext']
#if params['save_ndt_every'] != None: sim.schedule('save_ndt', filename=sim.name + '_precess.ndt', every=params['save_ndt_every'])
if params['save_ndt_every'] != None:
sim.schedule('save_ndt', every=params['save_ndt_every'])
#if params['save_ndt_every'] != None: raise NotImplementedError("XXX FIXME: This is currently not implemented because we need a different .ndt filename but it cannot be changed at present.")
if params['save_vtk_every'] != None:
sim.schedule('save_vtk', filename=sim.name +
suffix + '.pvd', every=params['save_vtk_every'])
if params['save_npy_every'] != None:
sim.schedule('save_field', 'm', filename=sim.name +
suffix + '.npy', every=params['save_npy_every'])
if params_relax == None:
pass # skip the relaxation phase
else:
params = default_params_relax
params.update(params_relax)
set_simulation_parameters_and_schedule(sim, params, suffix='_relax')
sim.relax()
if params['save_relaxed_vtk']:
sim.save_vtk(filename=sim.name + '_relaxed.pvd')
if params['save_relaxed_npy']:
sim.save_field('m', filename=sim.name + '_relaxed.npy')
sim.reset_time(0.0)
sim.clear_schedule()
params = default_params_precess
if params_precess != None:
params.update(params_precess)
set_simulation_parameters_and_schedule(sim, params, suffix='_precess')
sim.run_until(params['t_end'])
def eta(sim, when_started):
"""
Estimated time of simulation completion.
Only works in conjunction with run_until.
"""
elapsed_real_time = time.time() - when_started
simulation_speed = sim.t / elapsed_real_time
if simulation_speed > 0 and sim.t < sim.t_max:
remaining_simulation_time = sim.t_max - sim.t
remaining_real_time = remaining_simulation_time / simulation_speed
# split up remaining_real_time in hours, minutes
# and seconds for nicer formatting
hours, remainder = divmod(remaining_real_time, 60)
minutes, seconds = divmod(remainder, 60)
log.info("Integrated up to t = {:.4} ns. "
"Predicted end in {:0>2}:{:0>2}:{:0>2}.".format(
sim.t * 1e9, int(hours), int(minutes), int(seconds)))
def plot_relaxation(sim, filename="relaxation.png"):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
t, max_dmdt_norms = np.array(zip(* sim.relaxation['dmdts']))
ax.semilogy(t * 1e9, max_dmdt_norms / ONE_DEGREE_PER_NS, "ro")
ax.set_xlabel("time (ns)")
ax.set_ylabel("maximum dm/dt (1/ns)")
threshold = sim.relaxation['stopping_dmdt'] / ONE_DEGREE_PER_NS
ax.axhline(y=threshold, xmin=0.5, color="red", linestyle="--")
ax.annotate("threshold", xy=(0.6, 1.1 * threshold), color="r")
plt.savefig(filename)
plt.close()
def skyrmion_number(self):
"""
This function returns the skyrmion number calculated from the spin
texture in this simulation instance.
If the sim object is 3D, the skyrmion number is calculated from the
magnetisation of the top surface (since the skyrmion number formula
is only defined for 2D).
Details about computing functionals over subsets of the mesh (the
method used in this function to calculate the skyrmion number) can be
found at:
https://bitbucket.org/fenics-project/dolfin/src/master/demo/undocumented/lift-drag/python/demo_lift-drag.py
"""
mesh = self.mesh
# Get m field and define skyrmion number integrand
m = self.m_field.f
integrand = -0.25 / np.pi * df.dot(m, df.cross(df.Dx(m, 0),
df.Dx(m, 1)))
# determine if 3D system or not. Act accordingly.
if self.mesh.topology().dim() == 3:
mesh_coords = mesh.coordinates()
z_max = max(mesh_coords[:, 2])
# Define a subdomain which consists of the top surface of the geometry
class Top(df.SubDomain):
def inside(self, pt, on_boundary):
x, y, z = pt
return z >= z_max - df.DOLFIN_EPS and on_boundary
# Define a set of Markers from a MeshFunction (which is a function that
# can be evaluated at a set of mesh entities). Set all the marks to Zero.
markers = df.MeshFunction("size_t", mesh, mesh.topology().dim() - 1)
markers.set_all(0)
top = Top()
# Redefine the marks on the top surface to 1.
top.mark(markers, 1)
# Define ds so that it only computes where the marker=1 (top surface)
ds = df.ds[markers]
# Assemble the integrand on the the original domain, but only over the
# marked region (top surface).
S = df.assemble(form = integrand * ds(1, domain=mesh))
else:
S = df.assemble(integrand * df.dx)
return S
def skyrmion_number_density_function(self):
"""
This function returns the skyrmion number density function calculated
from the spin texture in this simulation instance. This function can be
probed to determine the local nature of the skyrmion number.
"""
integrand = -0.25 / np.pi * df.dot(self.m_field.f,
df.cross(df.Dx(self.m_field.f, 0),
df.Dx(self.m_field.f, 1)))
# Build the function space of the mesh nodes.
dofmap = self.S3.dofmap()
S1 = df.FunctionSpace(self.S3.mesh(), "Lagrange", 1,
constrained_domain=dofmap.constrained_domain)
# Find the skyrmion density at the mesh nodes using the above function
# space.
nodalSkx = df.dot(integrand, df.TestFunction(S1)) * df.dx
nodalVolumeS1 = nodal_volume(S1, self.unit_length)
skDensity = df.assemble(nodalSkx).array() * self.unit_length\
** self.S3.mesh().topology().dim() / nodalVolumeS1
# Build the skyrmion number density dolfin function from the skDensity
# array.
skDensityFunc = df.Function(S1)
skDensityFunc.vector()[:] = skDensity
return skDensityFunc
| 11,985 | 35.542683 | 198 |
py
|
finmag
|
finmag-master/src/finmag/sim/hysteresis.py
|
import os
import re
import glob
import logging
import textwrap
import fileinput
import numpy as np
from finmag.energies import Zeeman
from finmag.util.helpers import norm
log = logging.getLogger(name="finmag")
def hysteresis(sim, H_ext_list, fun=None, **kwargs):
"""
Set the applied field to the first value in `H_ext_list` (which should
be a list of external field vectors) and then call the relax() method.
When convergence is reached, the field is changed to the next one in
H_ext_list, and so on until all values in H_ext_list are exhausted.
Note: The fields in H_ext_list are applied *in addition to* any Zeeman
interactions that are already present in the simulation.
In particular, if only one external field should be present then
do not add any Zeeman interactions before calling this method.
If you would like to perform a certain action (e.g. save a VTK
snapshot of the magnetisation) at the end of each relaxation stage,
use the sim.schedule() command with the directive 'at_end=True' as
in the following example:
sim.schedule('save_vtk', at_end=True, ...)
sim.hysteresis(...)
*Arguments*
H_ext_list: list of 3-vectors
List of external fields, where each field can have any of
the forms accepted by Zeeman.__init__() (see its docstring
for more details).
fun: callable
The user can pass a function here (which should accept the
Simulation object as its only argument); this function is
called after each relaxation and determines the return
value (see below). For example, if
fun = (lambda sim: sim.m_average[0])
then the return value is a list of values representing the
average x-component of the magnetisation at the end of
each relaxation.
All other keyword arguments are passed on to the relax() method.
See its documentation for details.
*Return value*
If `fun` is not None then the return value is a list containing an
accumulation of all the return values of `fun` after each stage.
Otherwise the return value is None.
"""
if H_ext_list == []:
return
# Add a new Zeeman interaction, initialised to zero.
H = Zeeman((0, 0, 0))
sim.add(H)
# We keep track of the current stage of the hysteresis loop.
cur_stage = 0
num_stages = len(H_ext_list)
res = []
try:
while True:
H_cur = H_ext_list[cur_stage]
log.info(
"Entering hysteresis stage #{} ({} out of {}). Current field: "
"{}".format(cur_stage, cur_stage + 1, num_stages, H_cur))
H.set_value(H_cur)
sim.relax(**kwargs)
cur_stage += 1
if fun is not None:
retval = fun(sim)
res.append(retval)
log.debug("hysteresis callback function '{}' returned "
"value: {}".format(fun.__name__, retval))
except IndexError:
log.info("Hysteresis is finished.")
log.info("Removing the applied field used for hysteresis.")
sim.remove_interaction(H.name)
return res or None
def hysteresis_loop(sim, H_max, direction, N, **kwargs):
"""
Compute a hysteresis loop. This is a specialised convenience
version of the more general `hysteresis` method. It computes a
hysteresis loop where the external field is applied along a
single axis and changes magnitude from +H_max to -H_max and
back (using N steps in each direction).
The return value is a pair (H_vals, m_vals), where H_vals is
the list of field strengths at which a relaxation is performed
and m_vals is a list of scalar values containing, for each
field value, the averaged value of the magnetisation along the
axis `direction` (after relaxation has been reached). Thus the
command plot(H_vals, m_vals) could be used to plot the
hysteresis loop.
direction -- a vector indicating the direction of the
external field (will be normalised
automatically)
H_max -- maximum field strength
N -- number of data points to compute in each direction
(thus the total number of data points for the entire
loop will be 2*N-1)
kwargs -- any keyword argument accepted by the hysteresis() method
"""
d = np.array(direction)
H_dir = d / norm(d)
H_norms = list(np.linspace(H_max, -H_max, N)) + \
list(np.linspace(-H_max, H_max, N))
H_vals = [h * H_dir for h in H_norms]
m_avg = hysteresis(sim, H_vals, fun=lambda sim: sim.m_average, **kwargs)
# projected lengths of the averaged magnetisation values along the axis
# `H_dir`
m_vals = [np.dot(m, H_dir) for m in m_avg]
return (H_norms, m_vals)
| 4,925 | 33.93617 | 79 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/__init__.py
|
# This file is needed just os that python recognises
# the contents as a module, but we're not actually
# exposing any names here.
| 131 | 32 | 52 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/deprecated/custom_colormaps.py
|
#################################################################
### ###
### DO NOT EDIT THIS FILE!!! ###
### ###
### It was autogenerated from 'generate_custom_colormaps.py'. ###
### ###
#################################################################
import matplotlib.colors as mcolors
from numpy import array
circular1_vals = \
array([[0.42723266, 0.48755404, 0.31440724],
[0.42275894, 0.48841058, 0.32065462],
[0.41834834, 0.48922391, 0.3269548],
[0.41400352, 0.48999425, 0.33330456],
[0.40972727, 0.49072182, 0.33970066],
[0.40552247, 0.4914068, 0.34613991],
[0.40139217, 0.49204937, 0.35261908],
[0.39733952, 0.49264971, 0.35913493],
[0.39336783, 0.49320797, 0.36568423],
[0.38948055, 0.49372429, 0.37226371],
[0.3856813, 0.4941988, 0.37887011],
[0.38197385, 0.49463162, 0.38550012],
[0.37836213, 0.49502284, 0.39215043],
[0.37485024, 0.49537254, 0.39881772],
[0.37144243, 0.4956808, 0.40549862],
[0.36814315, 0.49594767, 0.41218975],
[0.36495699, 0.49617319, 0.41888771],
[0.3618887, 0.49635737, 0.42558908],
[0.35894318, 0.49650022, 0.43229042],
[0.35612548, 0.49660172, 0.43898824],
[0.35344078, 0.49666186, 0.44567907],
[0.35089438, 0.49668058, 0.45235939],
[0.34849167, 0.49665782, 0.45902569],
[0.34623813, 0.4965935, 0.46567441],
[0.34413928, 0.49648753, 0.472302],
[0.34220069, 0.4963398, 0.47890489],
[0.3404279, 0.49615018, 0.4854795],
[0.33882645, 0.49591853, 0.49202223],
[0.33740177, 0.49564468, 0.49852948],
[0.33615922, 0.49532847, 0.50499766],
[0.335104, 0.49496969, 0.51142316],
[0.33424112, 0.49456815, 0.51780238],
[0.33357536, 0.49412363, 0.5241317],
[0.33311124, 0.49363588, 0.53040754],
[0.33285297, 0.49310467, 0.53662632],
[0.33280439, 0.49252972, 0.54278445],
[0.33296898, 0.49191077, 0.54887837],
[0.33334976, 0.49124753, 0.55490454],
[0.33394933, 0.4905397, 0.56085944],
[0.33476978, 0.48978696, 0.56673957],
[0.3358127, 0.488989, 0.57254145],
[0.33707917, 0.48814549, 0.57826164],
[0.3385697, 0.48725609, 0.58389672],
[0.34028427, 0.48632045, 0.58944332],
[0.34222232, 0.48533822, 0.5948981],
[0.34438274, 0.48430903, 0.60025776],
[0.34676388, 0.48323251, 0.60551906],
[0.34936356, 0.4821083, 0.61067878],
[0.35217913, 0.48093602, 0.61573377],
[0.35520742, 0.47971529, 0.62068092],
[0.35844484, 0.47844572, 0.62551721],
[0.36188737, 0.47712694, 0.63023963],
[0.36553058, 0.47575857, 0.63484526],
[0.3693697, 0.47434022, 0.63933125],
[0.37339962, 0.47287152, 0.6436948],
[0.37761497, 0.4713521, 0.6479332],
[0.38201008, 0.46978157, 0.65204378],
[0.38657909, 0.46815959, 0.65602399],
[0.39131594, 0.46648579, 0.65987132],
[0.39621442, 0.46475983, 0.66358336],
[0.40126817, 0.46298137, 0.66715777],
[0.40647076, 0.46115009, 0.67059231],
[0.41181565, 0.45926567, 0.67388482],
[0.41729628, 0.45732781, 0.67703322],
[0.42290603, 0.45533623, 0.68003553],
[0.42863831, 0.45329066, 0.68288988],
[0.43448649, 0.45119086, 0.68559445],
[0.440444, 0.4490366, 0.68814756],
[0.44650428, 0.44682767, 0.69054761],
[0.45266085, 0.44456389, 0.6927931],
[0.45890725, 0.4422451, 0.69488263],
[0.46523711, 0.43987116, 0.69681492],
[0.47164413, 0.43744199, 0.69858877],
[0.4781221, 0.4349575, 0.7002031],
[0.48466487, 0.43241766, 0.70165693],
[0.49126641, 0.42982245, 0.70294939],
[0.49792076, 0.42717192, 0.70407971],
[0.50462206, 0.42446612, 0.70504725],
[0.51136456, 0.42170515, 0.70585146],
[0.51814258, 0.41888919, 0.70649191],
[0.52495057, 0.4160184, 0.70696828],
[0.53178306, 0.41309304, 0.70728034],
[0.53863469, 0.41011339, 0.70742801],
[0.54550018, 0.40707979, 0.70741129],
[0.55237436, 0.40399264, 0.7072303],
[0.55925217, 0.40085238, 0.70688528],
[0.56612863, 0.39765952, 0.70637657],
[0.57299885, 0.39441465, 0.70570463],
[0.57985806, 0.39111838, 0.70487002],
[0.58670155, 0.38777142, 0.70387341],
[0.59352474, 0.38437456, 0.70271559],
[0.60032312, 0.38092863, 0.70139745],
[0.60709227, 0.37743458, 0.69991999],
[0.61382787, 0.37389341, 0.69828431],
[0.62052568, 0.37030621, 0.69649163],
[0.62718157, 0.36667419, 0.69454326],
[0.63379147, 0.36299861, 0.69244061],
[0.64035141, 0.35928087, 0.69018521],
[0.64685752, 0.35552245, 0.68777868],
[0.65330599, 0.35172495, 0.68522272],
[0.65969313, 0.34789009, 0.68251917],
[0.6660153, 0.34401969, 0.67966991],
[0.67226897, 0.34011574, 0.67667697],
[0.67845068, 0.33618032, 0.67354242],
[0.68455708, 0.33221567, 0.67026845],
[0.69058487, 0.32822419, 0.66685732],
[0.69653087, 0.32420843, 0.6633114],
[0.70239195, 0.32017108, 0.6596331],
[0.70816508, 0.31611504, 0.65582496],
[0.71384734, 0.31204337, 0.65188955],
[0.71943585, 0.30795933, 0.64782955],
[0.72492784, 0.30386638, 0.64364768],
[0.73032063, 0.29976818, 0.63934676],
[0.7356116, 0.29566864, 0.63492967],
[0.74079824, 0.29157187, 0.63039932],
[0.74587811, 0.28748222, 0.62575873],
[0.75084886, 0.28340433, 0.62101095],
[0.75570823, 0.27934306, 0.61615908],
[0.76045404, 0.27530356, 0.61120629],
[0.76508419, 0.27129126, 0.60615577],
[0.76959667, 0.26731187, 0.6010108],
[0.77398955, 0.26337141, 0.59577465],
[0.77826101, 0.25947619, 0.59045066],
[0.78240928, 0.25563283, 0.5850422],
[0.7864327, 0.25184825, 0.57955268],
[0.79032967, 0.24812967, 0.57398551],
[0.79409871, 0.24448462, 0.56834415],
[0.7977384, 0.24092089, 0.56263207],
[0.80124741, 0.23744658, 0.55685277],
[0.8046245, 0.23407001, 0.55100976],
[0.80786851, 0.23079973, 0.54510654],
[0.81097835, 0.2276445, 0.53914666],
[0.81395305, 0.22461319, 0.53313363],
[0.81679169, 0.22171481, 0.52707099],
[0.81949344, 0.21895838, 0.52096227],
[0.82205757, 0.21635291, 0.51481099],
[0.82448341, 0.2139073, 0.50862067],
[0.82677039, 0.21163027, 0.5023948],
[0.82891801, 0.20953028, 0.49613687],
[0.83092586, 0.2076154, 0.48985036],
[0.83279359, 0.20589327, 0.48353869],
[0.83452096, 0.20437092, 0.47720531],
[0.83610778, 0.20305476, 0.4708536],
[0.83755396, 0.20195044, 0.46448691],
[0.83885947, 0.20106275, 0.45810859],
[0.84002438, 0.20039556, 0.45172193],
[0.8410488, 0.19995178, 0.44533018],
[0.84193295, 0.19973327, 0.43893655],
[0.8426771, 0.19974082, 0.43254422],
[0.8432816, 0.19997416, 0.42615632],
[0.84374689, 0.20043191, 0.41977593],
[0.84407345, 0.20111167, 0.41340608],
[0.84426184, 0.20201002, 0.40704975],
[0.84431271, 0.20312258, 0.40070989],
[0.84422674, 0.20444409, 0.39438936],
[0.84400471, 0.20596849, 0.38809099],
[0.84364745, 0.20768902, 0.38181757],
[0.84315586, 0.20959831, 0.37557181],
[0.84253088, 0.21168846, 0.36935639],
[0.84177354, 0.21395118, 0.36317391],
[0.84088492, 0.21637785, 0.35702696],
[0.83986616, 0.21895964, 0.35091803],
[0.83871844, 0.22168757, 0.34484959],
[0.83744303, 0.22455262, 0.33882407],
[0.83604123, 0.22754577, 0.33284383],
[0.83451438, 0.23065809, 0.32691121],
[0.83286392, 0.23388076, 0.3210285],
[0.83109128, 0.23720517, 0.31519795],
[0.82919799, 0.24062289, 0.3094218],
[0.82718559, 0.24412576, 0.30370223],
[0.82505569, 0.24770588, 0.29804144],
[0.82280993, 0.25135564, 0.29244157],
[0.82045001, 0.25506773, 0.2869048],
[0.81797764, 0.25883515, 0.28143327],
[0.8153946, 0.2626512, 0.27602914],
[0.8127027, 0.2665095, 0.27069459],
[0.80990377, 0.27040398, 0.26543182],
[0.80699969, 0.27432887, 0.26024305],
[0.80399239, 0.2782787, 0.25513055],
[0.80088379, 0.28224829, 0.25009667],
[0.79767588, 0.28623273, 0.24514378],
[0.79437065, 0.2902274, 0.24027436],
[0.79097014, 0.29422792, 0.23549096],
[0.78747641, 0.29823016, 0.23079625],
[0.78389153, 0.30223025, 0.22619299],
[0.7802176, 0.30622453, 0.22168408],
[0.77645675, 0.31020956, 0.21727257],
[0.77261113, 0.3141821, 0.21296164],
[0.7686829, 0.31813913, 0.20875465],
[0.76467424, 0.32207778, 0.20465514],
[0.76058734, 0.32599539, 0.20066682],
[0.75642441, 0.32988945, 0.1967936],
[0.75218768, 0.33375761, 0.1930396],
[0.74787938, 0.33759769, 0.18940914],
[0.74350176, 0.34140764, 0.18590675],
[0.73905705, 0.34518552, 0.18253716],
[0.73454754, 0.34892957, 0.17930531],
[0.72997547, 0.35263812, 0.17621631],
[0.72534312, 0.35630961, 0.17327548],
[0.72065276, 0.3599426, 0.17048825],
[0.71590667, 0.36353577, 0.16786021],
[0.71110712, 0.36708786, 0.16539702],
[0.70625639, 0.37059775, 0.1631044],
[0.70135674, 0.37406437, 0.16098806],
[0.69641046, 0.37748674, 0.15905369],
[0.6914198, 0.38086399, 0.15730685],
[0.68638702, 0.38419528, 0.15575292],
[0.68131439, 0.38747988, 0.15439705],
[0.67620413, 0.39071712, 0.15324408],
[0.67105851, 0.39390636, 0.15229847],
[0.66587973, 0.39704708, 0.15156424],
[0.66067002, 0.40013876, 0.15104488],
[0.65543158, 0.40318099, 0.15074334],
[0.65016661, 0.40617336, 0.15066193],
[0.64487728, 0.40911554, 0.1508023],
[0.63956576, 0.41200726, 0.15116544],
[0.6342342, 0.41484825, 0.15175163],
[0.62888474, 0.41763833, 0.15256045],
[0.62351949, 0.42037732, 0.15359077],
[0.61814054, 0.42306511, 0.15484084],
[0.61275, 0.4257016, 0.15630825],
[0.60734991, 0.42828675, 0.15799001],
[0.60194232, 0.43082053, 0.15988261],
[0.59652927, 0.43330295, 0.16198204],
[0.59111275, 0.43573404, 0.16428392],
[0.58569477, 0.43811386, 0.1667835],
[0.58027728, 0.44044251, 0.16947575],
[0.57486223, 0.44272008, 0.17235541],
[0.56945157, 0.44494672, 0.1754171],
[0.56404719, 0.44712258, 0.17865528],
[0.55865101, 0.44924782, 0.1820644],
[0.55326489, 0.45132264, 0.18563886],
[0.54789069, 0.45334722, 0.18937312],
[0.54253027, 0.45532181, 0.19326166],
[0.53718546, 0.45724661, 0.19729908],
[0.53185807, 0.45912189, 0.20148005],
[0.52654992, 0.46094788, 0.20579939],
[0.5212628, 0.46272485, 0.21025203],
[0.5159985, 0.46445307, 0.21483306],
[0.51075883, 0.46613283, 0.21953767],
[0.50554556, 0.4677644, 0.22436125],
[0.50036047, 0.46934806, 0.22929929],
[0.49520538, 0.47088412, 0.23434744],
[0.49008206, 0.47237287, 0.23950146],
[0.48499234, 0.4738146, 0.24475726],
[0.47993805, 0.47520961, 0.25011085],
[0.47492103, 0.4765582, 0.25555836],
[0.46994315, 0.47786066, 0.26109602],
[0.46500632, 0.47911729, 0.26672014],
[0.46011249, 0.48032837, 0.27242713],
[0.45526362, 0.48149419, 0.27821346],
[0.45046176, 0.48261504, 0.28407567],
[0.44570898, 0.48369118, 0.29001035],
[0.44100743, 0.4847229, 0.29601415],
[0.43635932, 0.48571044, 0.30208375],
[0.43176694, 0.48665407, 0.30821586]])
circular1 = mcolors.ListedColormap(circular1_vals)
circular2_vals = \
array([[0.47084433, 0.60577592, 0.35220371],
[0.46599366, 0.60657871, 0.35871817],
[0.46121803, 0.60734123, 0.36528155],
[0.45652098, 0.60806355, 0.3718905],
[0.45190615, 0.60874577, 0.37854167],
[0.44737735, 0.60938797, 0.38523173],
[0.4429385, 0.60999022, 0.39195735],
[0.43859369, 0.6105526, 0.39871521],
[0.43434713, 0.61107517, 0.40550198],
[0.43020319, 0.611558, 0.41231434],
[0.42616639, 0.61200113, 0.41914894],
[0.42224139, 0.61240461, 0.42600246],
[0.418433, 0.61276849, 0.43287153],
[0.41474618, 0.61309278, 0.43975278],
[0.41118602, 0.6133775, 0.44664285],
[0.40775772, 0.61362269, 0.45353834],
[0.40446664, 0.61382832, 0.46043584],
[0.40131821, 0.61399441, 0.46733193],
[0.39831797, 0.61412094, 0.47422317],
[0.39547152, 0.61420788, 0.48110611],
[0.39278454, 0.6142552, 0.48797728],
[0.3902627, 0.61426286, 0.49483321],
[0.38791171, 0.61423081, 0.5016704],
[0.38573725, 0.61415899, 0.50848534],
[0.38374492, 0.61404733, 0.51527453],
[0.38194026, 0.61389574, 0.52203444],
[0.38032868, 0.61370414, 0.52876153],
[0.37891542, 0.61347244, 0.53545229],
[0.37770554, 0.61320053, 0.54210316],
[0.37670383, 0.61288829, 0.54871061],
[0.37591484, 0.61253561, 0.5552711],
[0.37534279, 0.61214235, 0.5617811],
[0.37499154, 0.61170838, 0.56823707],
[0.37486458, 0.61123355, 0.5746355],
[0.37496496, 0.61071772, 0.58097287],
[0.3752953, 0.61016074, 0.58724569],
[0.37585773, 0.60956243, 0.59345048],
[0.37665388, 0.60892264, 0.59958376],
[0.37768487, 0.60824119, 0.60564211],
[0.37895129, 0.60751792, 0.61162211],
[0.38045319, 0.60675265, 0.61752035],
[0.38219007, 0.6059452, 0.62333349],
[0.38416091, 0.60509539, 0.6290582],
[0.38636415, 0.60420305, 0.63469117],
[0.38879772, 0.60326799, 0.64022917],
[0.39145905, 0.60229004, 0.64566897],
[0.39434507, 0.60126903, 0.65100741],
[0.39745229, 0.60020479, 0.65624136],
[0.40077676, 0.59909715, 0.66136776],
[0.40431416, 0.59794594, 0.66638358],
[0.40805978, 0.59675101, 0.67128585],
[0.41200858, 0.59551222, 0.67607169],
[0.41615524, 0.59422943, 0.68073823],
[0.42049414, 0.59290251, 0.68528269],
[0.42501945, 0.59153133, 0.68970237],
[0.42972513, 0.59011581, 0.69399461],
[0.43460496, 0.58865583, 0.69815683],
[0.43965259, 0.58715133, 0.70218653],
[0.44486156, 0.58560225, 0.7060813],
[0.45022529, 0.58400855, 0.70983876],
[0.45573718, 0.58237019, 0.71345667],
[0.46139056, 0.58068717, 0.71693282],
[0.46717874, 0.57895952, 0.72026513],
[0.47309504, 0.57718728, 0.72345158],
[0.47913278, 0.5753705, 0.72649023],
[0.48528532, 0.57350929, 0.72937926],
[0.49154605, 0.57160376, 0.73211692],
[0.49790842, 0.56965407, 0.73470156],
[0.50436594, 0.56766038, 0.73713164],
[0.51091217, 0.56562293, 0.73940569],
[0.51754078, 0.56354195, 0.74152235],
[0.52424549, 0.56141774, 0.74348038],
[0.53102012, 0.5592506, 0.7452786],
[0.53785858, 0.55704091, 0.74691598],
[0.54475487, 0.55478906, 0.74839155],
[0.55170309, 0.5524955, 0.74970448],
[0.55869742, 0.55016072, 0.75085401],
[0.56573216, 0.54778526, 0.75183952],
[0.57280168, 0.5453697, 0.75266047],
[0.57990046, 0.54291467, 0.75331644],
[0.5870231, 0.54042087, 0.75380713],
[0.59416425, 0.53788903, 0.75413231],
[0.60131869, 0.53531995, 0.75429189],
[0.6084813, 0.53271449, 0.75428589],
[0.61564702, 0.53007355, 0.75411441],
[0.62281092, 0.52739812, 0.75377769],
[0.62996813, 0.52468922, 0.75327604],
[0.63711391, 0.52194796, 0.75260993],
[0.64424357, 0.51917552, 0.75177988],
[0.65135254, 0.51637313, 0.75078656],
[0.65843631, 0.5135421, 0.74963072],
[0.66549049, 0.5106838, 0.74831323],
[0.67251075, 0.5077997, 0.74683505],
[0.67949287, 0.50489133, 0.74519726],
[0.68643268, 0.5019603, 0.74340103],
[0.69332613, 0.49900829, 0.74144763],
[0.70016924, 0.49603706, 0.73933844],
[0.70695811, 0.49304848, 0.73707493],
[0.71368891, 0.49004448, 0.73465867],
[0.72035794, 0.48702707, 0.73209132],
[0.72696152, 0.48399836, 0.72937464],
[0.73349609, 0.48096054, 0.72651049],
[0.73995817, 0.47791589, 0.7235008],
[0.74634434, 0.47486677, 0.7203476],
[0.7526513, 0.47181565, 0.717053],
[0.75887578, 0.46876507, 0.71361921],
[0.76501463, 0.46571766, 0.7100485],
[0.77106476, 0.46267615, 0.70634323],
[0.77702318, 0.45964334, 0.70250585],
[0.78288697, 0.45662214, 0.69853885],
[0.78865329, 0.45361553, 0.69444483],
[0.79431938, 0.45062658, 0.69022644],
[0.79988256, 0.44765844, 0.68588639],
[0.80534025, 0.44471434, 0.68142748],
[0.81068993, 0.44179759, 0.67685256],
[0.81592918, 0.43891156, 0.67216451],
[0.82105564, 0.4360597, 0.66736632],
[0.82606704, 0.43324553, 0.66246098],
[0.83096122, 0.43047261, 0.65745157],
[0.83573606, 0.42774457, 0.65234119],
[0.84038954, 0.42506506, 0.64713301],
[0.84491974, 0.4224378, 0.64183021],
[0.84932479, 0.41986651, 0.63643602],
[0.85360294, 0.41735495, 0.63095373],
[0.85775249, 0.41490688, 0.62538661],
[0.86177183, 0.41252606, 0.61973801],
[0.86565945, 0.41021625, 0.61401127],
[0.86941391, 0.40798117, 0.60820977],
[0.87303385, 0.40582451, 0.60233689],
[0.87651801, 0.40374992, 0.59639605],
[0.87986518, 0.40176097, 0.59039066],
[0.88307426, 0.39986116, 0.58432415],
[0.88614422, 0.39805391, 0.57819996],
[0.88907412, 0.39634251, 0.57202151],
[0.8918631, 0.39473015, 0.56579225],
[0.89451037, 0.39321987, 0.5595156],
[0.89701524, 0.39181456, 0.553195],
[0.89937707, 0.39051695, 0.54683385],
[0.90159534, 0.38932957, 0.54043555],
[0.90366958, 0.38825477, 0.5340035],
[0.9055994, 0.38729469, 0.52754107],
[0.90738451, 0.38645126, 0.5210516],
[0.90902467, 0.38572616, 0.51453841],
[0.91051973, 0.38512083, 0.50800481],
[0.91186963, 0.38463647, 0.50145407],
[0.91307437, 0.38427402, 0.49488942],
[0.91413402, 0.38403416, 0.48831409],
[0.91504873, 0.3839173, 0.48173123],
[0.91581872, 0.38392356, 0.475144],
[0.9164443, 0.38405283, 0.46855549],
[0.91692584, 0.3843047, 0.46196877],
[0.91726376, 0.38467851, 0.45538685],
[0.91745857, 0.38517332, 0.44881273],
[0.91751086, 0.38578795, 0.44224934],
[0.91742126, 0.38652097, 0.43569958],
[0.91719049, 0.3873707, 0.4291663],
[0.91681931, 0.38833524, 0.42265234],
[0.91630857, 0.38941247, 0.41616044],
[0.91565916, 0.39060006, 0.40969336],
[0.91487204, 0.3918955, 0.40325379],
[0.91394825, 0.39329608, 0.39684437],
[0.91288885, 0.39479895, 0.39046772],
[0.91169499, 0.39640109, 0.38412644],
[0.91036786, 0.39809936, 0.37782307],
[0.9089087, 0.39989049, 0.37156013],
[0.90731883, 0.40177113, 0.36534013],
[0.9055996, 0.40373781, 0.35916553],
[0.90375242, 0.40578701, 0.35303881],
[0.90177873, 0.40791513, 0.3469624],
[0.89968004, 0.41011855, 0.34093875],
[0.89745791, 0.41239358, 0.3349703],
[0.89511393, 0.41473656, 0.32905949],
[0.89264973, 0.41714377, 0.32320878],
[0.890067, 0.41961153, 0.31742066],
[0.88736746, 0.42213615, 0.31169763],
[0.88455288, 0.42471398, 0.30604223],
[0.88162505, 0.42734139, 0.30045708],
[0.8785858, 0.4300148, 0.2949448],
[0.87543702, 0.43273066, 0.28950814],
[0.87218059, 0.43548549, 0.28414988],
[0.86881847, 0.43827587, 0.27887292],
[0.86535262, 0.44109844, 0.27368024],
[0.86178503, 0.44394989, 0.26857497],
[0.85811773, 0.44682703, 0.26356033],
[0.85435277, 0.44972671, 0.2586397],
[0.85049223, 0.45264586, 0.25381661],
[0.8465382, 0.45558151, 0.24909474],
[0.8424928, 0.45853077, 0.24447798],
[0.83835819, 0.46149083, 0.23997038],
[0.83413652, 0.46445896, 0.23557619],
[0.82982996, 0.46743254, 0.23129986],
[0.82544072, 0.47040902, 0.22714607],
[0.82097101, 0.47338593, 0.2231197],
[0.81642306, 0.47636092, 0.21922585],
[0.81179909, 0.47933168, 0.21546982],
[0.80710137, 0.48229604, 0.21185715],
[0.80233215, 0.48525187, 0.20839353],
[0.7974937, 0.48819714, 0.20508486],
[0.79258829, 0.49112992, 0.20193719],
[0.78761822, 0.49404834, 0.19895668],
[0.78258577, 0.49695063, 0.19614962],
[0.77749324, 0.49983507, 0.19352232],
[0.77234291, 0.50270004, 0.1910811],
[0.7671371, 0.50554399, 0.18883223],
[0.7618781, 0.50836546, 0.18678187],
[0.75656821, 0.51116302, 0.18493601],
[0.75120973, 0.51393536, 0.18330037],
[0.74580496, 0.5166812, 0.18188036],
[0.74035619, 0.51939935, 0.18068102],
[0.73486573, 0.52208867, 0.17970689],
[0.72933584, 0.5247481, 0.178962],
[0.72376883, 0.52737662, 0.17844977],
[0.71816697, 0.52997328, 0.17817297],
[0.71253252, 0.5325372, 0.17813369],
[0.70686776, 0.53506752, 0.17833327],
[0.70117494, 0.53756346, 0.17877231],
[0.69545632, 0.5400243, 0.17945064],
[0.68971412, 0.54244935, 0.18036734],
[0.6839506, 0.54483796, 0.18152076],
[0.67816796, 0.54718956, 0.18290854],
[0.67236844, 0.54950359, 0.18452766],
[0.66655423, 0.55177955, 0.1863745],
[0.66072754, 0.55401698, 0.18844486],
[0.65489056, 0.55621545, 0.1907341],
[0.64904547, 0.55837457, 0.19323712],
[0.64319445, 0.56049401, 0.1959485],
[0.63733966, 0.56257343, 0.19886252],
[0.63148326, 0.56461256, 0.20197325],
[0.62562742, 0.56661114, 0.20527462],
[0.61977429, 0.56856895, 0.20876043],
[0.613926, 0.5704858, 0.21242446],
[0.60808472, 0.57236151, 0.2162605],
[0.60225258, 0.57419594, 0.22026234],
[0.59643173, 0.57598898, 0.22442387],
[0.59062432, 0.57774051, 0.22873908],
[0.5848325, 0.57945048, 0.23320208],
[0.57905844, 0.58111881, 0.2378071],
[0.57330431, 0.58274547, 0.24254854],
[0.5675723, 0.58433044, 0.24742095],
[0.5618646, 0.5858737, 0.25241905],
[0.55618344, 0.58737528, 0.25753771],
[0.55053105, 0.58883518, 0.26277197],
[0.54490971, 0.59025345, 0.26811702],
[0.53932172, 0.59163013, 0.27356822],
[0.53376941, 0.59296527, 0.27912106],
[0.52825515, 0.59425893, 0.28477116],
[0.52278137, 0.59551119, 0.2905143],
[0.51735052, 0.59672213, 0.29634635],
[0.51196514, 0.59789182, 0.3022633],
[0.50662781, 0.59902036, 0.30826125],
[0.50134118, 0.60010784, 0.31433639],
[0.49610796, 0.60115436, 0.32048497],
[0.49093097, 0.60216001, 0.32670335],
[0.48581308, 0.60312489, 0.33298793],
[0.48075728, 0.6040491, 0.33933516],
[0.47576663, 0.60493275, 0.34574157]])
circular2 = mcolors.ListedColormap(circular2_vals)
circular3_vals = \
array([[0.45824865, 0.67303858, 0.36593155],
[0.45300776, 0.67377035, 0.37242085],
[0.44784266, 0.67446563, 0.37895505],
[0.44275757, 0.67512442, 0.38553078],
[0.43775691, 0.67574676, 0.39214472],
[0.4328453, 0.67633267, 0.39879356],
[0.4280275, 0.67688218, 0.40547399],
[0.4233085, 0.6773953, 0.41218273],
[0.41869348, 0.67787204, 0.41891651],
[0.4141878, 0.67831244, 0.42567204],
[0.40979703, 0.6787165, 0.43244606],
[0.40552693, 0.67908423, 0.43923529],
[0.40138346, 0.67941563, 0.44603644],
[0.39737275, 0.67971071, 0.45284624],
[0.39350111, 0.67996946, 0.45966139],
[0.38977502, 0.68019188, 0.4664786],
[0.38620108, 0.68037795, 0.47329454],
[0.38278606, 0.68052766, 0.48010591],
[0.37953679, 0.68064098, 0.48690938],
[0.37646018, 0.68071789, 0.49370161],
[0.37356322, 0.68075835, 0.50047925],
[0.37085286, 0.68076233, 0.50723894],
[0.36833604, 0.68072978, 0.51397732],
[0.36601963, 0.68066065, 0.52069103],
[0.36391038, 0.68055489, 0.52737667],
[0.36201484, 0.68041244, 0.53403087],
[0.36033939, 0.68023323, 0.54065024],
[0.35889009, 0.6800172, 0.54723139],
[0.3576727, 0.67976428, 0.55377093],
[0.35669257, 0.67947438, 0.56026547],
[0.35595465, 0.67914743, 0.56671162],
[0.35546338, 0.67878334, 0.57310601],
[0.35522269, 0.67838203, 0.57944526],
[0.35523592, 0.6779434, 0.58572601],
[0.35550581, 0.67746735, 0.59194491],
[0.35603444, 0.6769538, 0.59809861],
[0.35682327, 0.67640265, 0.6041838],
[0.35787303, 0.6758138, 0.61019718],
[0.35918378, 0.67518715, 0.61613546],
[0.3607549, 0.67452261, 0.62199539],
[0.36258506, 0.67382008, 0.62777374],
[0.36467228, 0.67307946, 0.63346731],
[0.36701393, 0.67230067, 0.63907293],
[0.36960674, 0.67148361, 0.64458746],
[0.37244687, 0.6706282, 0.65000782],
[0.37552994, 0.66973436, 0.65533094],
[0.37885102, 0.66880202, 0.6605538],
[0.38240477, 0.66783111, 0.66567345],
[0.38618539, 0.66682156, 0.67068696],
[0.39018674, 0.66577333, 0.67559146],
[0.39440233, 0.66468637, 0.68038413],
[0.39882541, 0.66356065, 0.68506222],
[0.40344902, 0.66239615, 0.689623],
[0.40826597, 0.66119287, 0.69406385],
[0.41326895, 0.65995079, 0.69838218],
[0.41845054, 0.65866996, 0.70257548],
[0.42380325, 0.65735039, 0.70664129],
[0.42931954, 0.65599215, 0.71057725],
[0.43499186, 0.65459529, 0.71438104],
[0.44081267, 0.65315992, 0.71805043],
[0.44677448, 0.65168614, 0.72158328],
[0.45286985, 0.65017409, 0.7249775],
[0.45909141, 0.64862391, 0.72823111],
[0.46543187, 0.64703578, 0.73134217],
[0.47188405, 0.64540991, 0.73430888],
[0.47844088, 0.64374653, 0.73712948],
[0.4850954, 0.6420459, 0.73980232],
[0.49184076, 0.6403083, 0.74232584],
[0.49867026, 0.63853406, 0.74469855],
[0.50557731, 0.63672351, 0.74691908],
[0.51255547, 0.63487705, 0.74898614],
[0.5195984, 0.63299509, 0.75089853],
[0.52669991, 0.63107809, 0.75265516],
[0.53385396, 0.62912653, 0.75425502],
[0.5410546, 0.62714094, 0.75569721],
[0.54829602, 0.6251219, 0.75698093],
[0.55557256, 0.62307001, 0.75810547],
[0.56287864, 0.62098592, 0.75907022],
[0.57020883, 0.61887032, 0.75987469],
[0.57755781, 0.61672397, 0.76051846],
[0.58492037, 0.61454764, 0.76100125],
[0.5922914, 0.61234216, 0.76132285],
[0.59966593, 0.61010843, 0.76148317],
[0.60703905, 0.60784736, 0.76148221],
[0.614406, 0.60555994, 0.76132008],
[0.62176207, 0.6032472, 0.760997],
[0.6291027, 0.60091023, 0.76051328],
[0.63642339, 0.59855016, 0.75986932],
[0.64371974, 0.5961682, 0.75906566],
[0.65098744, 0.59376559, 0.7581029],
[0.65822228, 0.59134363, 0.75698177],
[0.66542011, 0.58890368, 0.75570307],
[0.6725769, 0.58644717, 0.75426774],
[0.67968868, 0.58397557, 0.75267677],
[0.68675157, 0.58149042, 0.75093128],
[0.69376176, 0.5789933, 0.74903248],
[0.70071555, 0.57648588, 0.74698167],
[0.70760929, 0.57396986, 0.74478024],
[0.71443942, 0.57144701, 0.74242967],
[0.72120245, 0.56891916, 0.73993155],
[0.72789498, 0.5663882, 0.73728753],
[0.73451367, 0.56385608, 0.73449937],
[0.74105527, 0.56132478, 0.73156891],
[0.74751661, 0.55879638, 0.72849806],
[0.75389457, 0.55627298, 0.72528884],
[0.76018614, 0.55375676, 0.72194331],
[0.76638835, 0.55124992, 0.71846364],
[0.77249833, 0.54875473, 0.71485206],
[0.77851328, 0.54627353, 0.71111089],
[0.78443046, 0.54380866, 0.7072425],
[0.79024723, 0.54136254, 0.70324934],
[0.79596101, 0.53893761, 0.69913392],
[0.8015693, 0.53653636, 0.69489882],
[0.80706966, 0.53416132, 0.69054668],
[0.81245975, 0.53181504, 0.68608019],
[0.81773729, 0.52950009, 0.68150212],
[0.82290008, 0.52721907, 0.67681526],
[0.827946, 0.52497462, 0.67202247],
[0.832873, 0.52276936, 0.66712665],
[0.83767911, 0.52060594, 0.66213077],
[0.84236243, 0.51848699, 0.65703779],
[0.84692115, 0.51641518, 0.65185076],
[0.85135352, 0.51439312, 0.64657275],
[0.85565789, 0.51242344, 0.64120684],
[0.85983266, 0.51050873, 0.63575618],
[0.86387632, 0.50865157, 0.63022392],
[0.86778745, 0.50685448, 0.62461323],
[0.87156467, 0.50511996, 0.61892733],
[0.87520673, 0.50345045, 0.61316943],
[0.8787124, 0.50184833, 0.60734277],
[0.88208058, 0.50031593, 0.6014506],
[0.88531021, 0.49885548, 0.59549617],
[0.88840031, 0.49746915, 0.58948276],
[0.89135, 0.49615904, 0.58341363],
[0.89415846, 0.4949271, 0.57729205],
[0.89682494, 0.49377525, 0.5711213],
[0.89934877, 0.49270523, 0.56490462],
[0.90172937, 0.49171873, 0.55864529],
[0.90396622, 0.49081727, 0.55234655],
[0.90605887, 0.49000226, 0.54601163],
[0.90800696, 0.48927498, 0.53964375],
[0.90981019, 0.48863656, 0.53324611],
[0.91146835, 0.48808801, 0.52682191],
[0.91298128, 0.48763016, 0.5203743],
[0.91434891, 0.48726371, 0.51390642],
[0.91557124, 0.48698921, 0.50742139],
[0.91664831, 0.48680704, 0.50092229],
[0.91758029, 0.48671743, 0.49441218],
[0.91836735, 0.48672046, 0.4878941],
[0.91900979, 0.48681603, 0.48137105],
[0.91950793, 0.48700389, 0.47484598],
[0.91986219, 0.48728366, 0.46832184],
[0.92007304, 0.48765476, 0.46180152],
[0.920141, 0.4881165, 0.4552879],
[0.92006669, 0.48866801, 0.44878381],
[0.91985077, 0.48930829, 0.44229205],
[0.91949395, 0.4900362, 0.43581538],
[0.91899703, 0.49085046, 0.42935656],
[0.91836085, 0.49174966, 0.42291827],
[0.91758632, 0.49273226, 0.4165032],
[0.91667438, 0.49379661, 0.410114],
[0.91562606, 0.49494095, 0.40375328],
[0.91444243, 0.49616342, 0.39742365],
[0.91312462, 0.49746203, 0.39112768],
[0.9116738, 0.49883474, 0.38486794],
[0.91009119, 0.5002794, 0.37864697],
[0.90837808, 0.5017938, 0.37246732],
[0.9065358, 0.50337566, 0.36633151],
[0.90456571, 0.50502263, 0.3602421],
[0.90246924, 0.50673231, 0.35420161],
[0.90024784, 0.50850226, 0.3482126],
[0.89790304, 0.51032999, 0.34227766],
[0.89543637, 0.512213, 0.33639938],
[0.89284943, 0.51414875, 0.3305804],
[0.89014384, 0.51613468, 0.3248234],
[0.88732128, 0.51816821, 0.31913111],
[0.88438344, 0.52024678, 0.31350634],
[0.88133207, 0.52236782, 0.30795193],
[0.87816894, 0.52452875, 0.30247086],
[0.87489584, 0.52672702, 0.29706615],
[0.87151462, 0.52896009, 0.29174095],
[0.86802715, 0.53122543, 0.28649853],
[0.8644353, 0.53352056, 0.28134227],
[0.86074101, 0.53584299, 0.27627571],
[0.85694622, 0.5381903, 0.27130253],
[0.85305291, 0.54056009, 0.26642657],
[0.84906305, 0.54294999, 0.26165185],
[0.84497867, 0.54535769, 0.25698258],
[0.8408018, 0.54778091, 0.25242314],
[0.83653449, 0.55021742, 0.24797815],
[0.83217882, 0.55266504, 0.2436524],
[0.82773687, 0.55512164, 0.23945091],
[0.82321075, 0.55758513, 0.2353789],
[0.81860257, 0.56005349, 0.23144183],
[0.81391446, 0.56252475, 0.22764533],
[0.80914857, 0.56499698, 0.22399524],
[0.80430703, 0.56746833, 0.22049758],
[0.79939203, 0.56993698, 0.21715853],
[0.79440571, 0.57240117, 0.2139844],
[0.78935026, 0.57485923, 0.21098161],
[0.78422787, 0.57730949, 0.20815663],
[0.77904071, 0.57975039, 0.20551596],
[0.77379099, 0.58218038, 0.20306606],
[0.76848089, 0.58459801, 0.20081331],
[0.76311261, 0.58700184, 0.19876392],
[0.75768835, 0.58939052, 0.19692388],
[0.75221031, 0.59176274, 0.19529891],
[0.74668069, 0.59411724, 0.19389435],
[0.74110169, 0.59645282, 0.19271511],
[0.7354755, 0.59876832, 0.19176558],
[0.72980431, 0.60106265, 0.19104961],
[0.72409033, 0.60333475, 0.19057039],
[0.71833573, 0.60558361, 0.19033045],
[0.71254271, 0.6078083, 0.1903316],
[0.70671343, 0.61000789, 0.19057489],
[0.70085009, 0.61218152, 0.19106061],
[0.69495486, 0.61432837, 0.19178827],
[0.68902989, 0.61644768, 0.19275666],
[0.68307736, 0.6185387, 0.19396378],
[0.67709942, 0.62060074, 0.19540699],
[0.67109824, 0.62263316, 0.19708294],
[0.66507595, 0.62463533, 0.19898771],
[0.65903472, 0.62660668, 0.20111685],
[0.65297668, 0.62854667, 0.20346542],
[0.64690397, 0.6304548, 0.20602806],
[0.64081874, 0.63233058, 0.2087991],
[0.63472314, 0.63417359, 0.21177259],
[0.62861929, 0.63598341, 0.21494237],
[0.62250935, 0.63775966, 0.21830214],
[0.61639547, 0.63950199, 0.22184551],
[0.61027979, 0.64121009, 0.22556605],
[0.60416448, 0.64288365, 0.22945734],
[0.5980517, 0.6445224, 0.233513],
[0.59194365, 0.6461261, 0.23772674],
[0.58584251, 0.64769453, 0.24209236],
[0.5797505, 0.64922747, 0.24660381],
[0.57366985, 0.65072475, 0.25125516],
[0.56760282, 0.6521862, 0.25604063],
[0.5615517, 0.65361169, 0.26095464],
[0.5555188, 0.65500108, 0.26599175],
[0.54950647, 0.65635427, 0.27114668],
[0.5435171, 0.65767115, 0.27641434],
[0.53755315, 0.65895165, 0.2817898],
[0.53161708, 0.6601957, 0.28726828],
[0.52571145, 0.66140325, 0.29284516],
[0.51983886, 0.66257424, 0.29851595],
[0.51400198, 0.66370865, 0.30427633],
[0.50820357, 0.66480645, 0.31012207],
[0.50244645, 0.66586762, 0.31604908],
[0.49673355, 0.66689215, 0.32205338],
[0.49106788, 0.66788005, 0.32813108],
[0.48545256, 0.66883131, 0.33427839],
[0.47989081, 0.66974595, 0.3404916],
[0.474386, 0.67062398, 0.34676706],
[0.4689416, 0.67146541, 0.35310121],
[0.46356123, 0.67227027, 0.35949053]])
circular3 = mcolors.ListedColormap(circular3_vals)
circular4_vals = \
array([[0.56368834, 0.79397589, 0.46980697],
[0.55636314, 0.79252094, 0.47502489],
[0.549044, 0.79092065, 0.48017003],
[0.54173692, 0.78917656, 0.48523945],
[0.53444808, 0.78729026, 0.49023031],
[0.52718379, 0.78526346, 0.4951398],
[0.51995051, 0.78309794, 0.4999652],
[0.51275487, 0.78079555, 0.50470384],
[0.50560363, 0.77835822, 0.50935312],
[0.49850375, 0.77578796, 0.51391053],
[0.4914623, 0.77308685, 0.51837362],
[0.48448656, 0.77025704, 0.52273999],
[0.47758392, 0.76730075, 0.52700734],
[0.47076195, 0.76422027, 0.53117344],
[0.46402838, 0.76101794, 0.5352361],
[0.45739106, 0.75769618, 0.53919325],
[0.450858, 0.75425745, 0.54304287],
[0.44443732, 0.75070429, 0.54678302],
[0.43813726, 0.74703926, 0.55041183],
[0.43196617, 0.74326502, 0.55392753],
[0.42593246, 0.73938423, 0.5573284],
[0.42004463, 0.73539962, 0.56061283],
[0.41431117, 0.73131396, 0.56377925],
[0.40874061, 0.72713006, 0.56682622],
[0.40334144, 0.72285077, 0.56975234],
[0.39812207, 0.71847898, 0.57255631],
[0.39309081, 0.71401759, 0.57523692],
[0.38825581, 0.70946956, 0.57779303],
[0.38362503, 0.70483785, 0.58022358],
[0.37920615, 0.70012546, 0.58252762],
[0.37500655, 0.6953354, 0.58470426],
[0.37103324, 0.69047071, 0.58675269],
[0.3672928, 0.68553443, 0.58867222],
[0.3637913, 0.68052962, 0.59046222],
[0.36053429, 0.67545935, 0.59212214],
[0.35752669, 0.6703267, 0.59365154],
[0.35477279, 0.66513474, 0.59505004],
[0.35227614, 0.65988656, 0.59631736],
[0.35003956, 0.65458522, 0.59745332],
[0.34806508, 0.6492338, 0.5984578],
[0.3463539, 0.64383536, 0.59933079],
[0.34490641, 0.63839296, 0.60007233],
[0.34372215, 0.63290964, 0.60068259],
[0.34279981, 0.62738841, 0.6011618],
[0.34213727, 0.62183228, 0.60151027],
[0.34173161, 0.61624425, 0.6017284],
[0.34157911, 0.61062726, 0.60181669],
[0.34167535, 0.60498425, 0.60177571],
[0.34201521, 0.59931813, 0.6016061],
[0.34259298, 0.59363179, 0.60130859],
[0.34340235, 0.58792805, 0.600884],
[0.34443655, 0.58220973, 0.60033323],
[0.34568835, 0.57647961, 0.59965724],
[0.34715021, 0.57074042, 0.59885709],
[0.34881428, 0.56499486, 0.5979339],
[0.35067249, 0.55924558, 0.59688887],
[0.35271664, 0.5534952, 0.59572327],
[0.35493843, 0.54774627, 0.59443847],
[0.35732956, 0.54200133, 0.59303587],
[0.35988173, 0.53626285, 0.59151697],
[0.36258673, 0.53053325, 0.58988332],
[0.36543648, 0.52481493, 0.58813656],
[0.36842305, 0.5191102, 0.58627837],
[0.3715387, 0.51342135, 0.58431052],
[0.37477592, 0.50775062, 0.58223481],
[0.37812746, 0.50210019, 0.58005313],
[0.38158631, 0.4964722, 0.57776741],
[0.38514575, 0.49086873, 0.57537965],
[0.38879934, 0.48529182, 0.57289189],
[0.39254096, 0.47974346, 0.57030624],
[0.39636476, 0.4742256, 0.56762485],
[0.4002652, 0.46874015, 0.56484991],
[0.40423705, 0.46328895, 0.56198368],
[0.40827537, 0.45787382, 0.55902845],
[0.4123755, 0.45249655, 0.55598654],
[0.41653307, 0.44715887, 0.55286034],
[0.42074398, 0.44186248, 0.54965225],
[0.42500442, 0.43660906, 0.54636471],
[0.4293108, 0.43140027, 0.54300022],
[0.4336598, 0.42623771, 0.53956127],
[0.43804833, 0.42112299, 0.5360504],
[0.44247353, 0.41605769, 0.53247018],
[0.44693273, 0.41104339, 0.52882319],
[0.45142348, 0.40608165, 0.52511203],
[0.45594353, 0.40117402, 0.52133933],
[0.46049078, 0.39632207, 0.51750773],
[0.46506333, 0.39152738, 0.51361988],
[0.46965941, 0.38679153, 0.50967843],
[0.47427742, 0.38211613, 0.50568606],
[0.47891588, 0.37750281, 0.50164543],
[0.48357344, 0.37295324, 0.49755923],
[0.48824886, 0.36846913, 0.49343012],
[0.49294102, 0.36405223, 0.48926078],
[0.49764888, 0.35970437, 0.48505386],
[0.50237152, 0.35542742, 0.48081202],
[0.50710806, 0.35122333, 0.4765379],
[0.51185772, 0.34709412, 0.47223412],
[0.51661976, 0.34304192, 0.46790331],
[0.52139352, 0.33906894, 0.46354803],
[0.52617837, 0.33517748, 0.45917087],
[0.53097373, 0.33136998, 0.45477435],
[0.53577904, 0.32764897, 0.45036099],
[0.5405938, 0.32401712, 0.44593327],
[0.54541748, 0.32047724, 0.44149363],
[0.55024962, 0.31703224, 0.43704449],
[0.55508972, 0.31368521, 0.43258821],
[0.55993732, 0.31043936, 0.42812712],
[0.56479194, 0.30729806, 0.42366351],
[0.56965309, 0.30426482, 0.4191996],
[0.57452028, 0.3013433, 0.4147376],
[0.57939299, 0.29853732, 0.41027962],
[0.58427069, 0.29585081, 0.40582776],
[0.58915282, 0.29328786, 0.40138404],
[0.5940388, 0.29085269, 0.39695042],
[0.598928, 0.28854962, 0.39252882],
[0.60381976, 0.28638308, 0.38812107],
[0.60871339, 0.28435758, 0.38372895],
[0.61360815, 0.28247773, 0.37935419],
[0.61850324, 0.28074814, 0.37499843],
[0.62339785, 0.27917347, 0.37066324],
[0.62829109, 0.27775838, 0.36635013],
[0.63318202, 0.27650747, 0.36206054],
[0.63806966, 0.2754253, 0.35779584],
[0.64295295, 0.27451632, 0.35355731],
[0.64783079, 0.27378486, 0.34934618],
[0.65270204, 0.27323505, 0.3451636],
[0.65756546, 0.27287086, 0.34101062],
[0.66241977, 0.27269597, 0.33688826],
[0.66726363, 0.27271382, 0.33279744],
[0.67209565, 0.27292754, 0.32873901],
[0.67691434, 0.27333989, 0.32471376],
[0.6817182, 0.27395329, 0.32072241],
[0.68650563, 0.27476976, 0.31676559],
[0.69127497, 0.27579088, 0.31284389],
[0.69602454, 0.27701784, 0.30895782],
[0.70075254, 0.27845134, 0.30510785],
[0.70545716, 0.28009166, 0.30129438],
[0.7101365, 0.28193859, 0.29751774],
[0.71478864, 0.2839915, 0.29377823],
[0.71941156, 0.28624927, 0.29007611],
[0.72400323, 0.28871039, 0.28641158],
[0.72856152, 0.29137287, 0.28278481],
[0.73308431, 0.29423437, 0.27919595],
[0.73756937, 0.29729211, 0.27564513],
[0.74201447, 0.300543, 0.27213243],
[0.74641731, 0.30398357, 0.26865796],
[0.75077557, 0.30761007, 0.26522181],
[0.75508687, 0.31141845, 0.26182407],
[0.75934881, 0.31540441, 0.25846485],
[0.76355894, 0.31956343, 0.2551443],
[0.76771479, 0.32389079, 0.25186257],
[0.77181387, 0.32838159, 0.24861988],
[0.77585364, 0.33303079, 0.2454165],
[0.77983156, 0.33783322, 0.24225275],
[0.78374507, 0.3427836, 0.23912906],
[0.78759158, 0.3478766, 0.23604592],
[0.79136849, 0.35310679, 0.23300394],
[0.7950732, 0.35846871, 0.23000384],
[0.7987031, 0.36395687, 0.22704646],
[0.80225556, 0.36956577, 0.2241328],
[0.80572797, 0.37528989, 0.22126402],
[0.80911772, 0.38112373, 0.21844145],
[0.8124222, 0.38706178, 0.21566659],
[0.8156388, 0.39309858, 0.21294117],
[0.81876495, 0.39922869, 0.21026713],
[0.82179807, 0.40544668, 0.20764663],
[0.82473561, 0.41174718, 0.2050821],
[0.82757503, 0.41812487, 0.20257621],
[0.83031385, 0.42457445, 0.20013192],
[0.83294957, 0.43109068, 0.19775247],
[0.83547976, 0.43766835, 0.19544138],
[0.83790201, 0.44430233, 0.1932025],
[0.84021395, 0.45098751, 0.19103997],
[0.84241324, 0.45771883, 0.18895823],
[0.8444976, 0.4644913, 0.18696207],
[0.84646479, 0.47129996, 0.18505655],
[0.84831261, 0.47813992, 0.18324704],
[0.85003894, 0.48500631, 0.18153919],
[0.85164169, 0.49189433, 0.17993891],
[0.85311883, 0.49879922, 0.17845236],
[0.8544684, 0.50571627, 0.17708588],
[0.85568849, 0.51264081, 0.175846],
[0.85677728, 0.51956824, 0.17473936],
[0.85773299, 0.52649398, 0.17377268],
[0.85855392, 0.5334135, 0.17295267],
[0.85923845, 0.54032234, 0.17228601],
[0.85978503, 0.54721606, 0.17177924],
[0.86019218, 0.55409028, 0.17143872],
[0.86045851, 0.56094067, 0.17127053],
[0.8605827, 0.56776293, 0.17128041],
[0.86056351, 0.57455284, 0.17147369],
[0.86039981, 0.58130619, 0.17185518],
[0.86009053, 0.58801884, 0.17242918],
[0.85963469, 0.59468671, 0.17319933],
[0.8590314, 0.60130575, 0.17416865],
[0.85827988, 0.60787198, 0.17533943],
[0.85737943, 0.61438144, 0.17671322],
[0.85632942, 0.62083027, 0.17829085],
[0.85512935, 0.62721464, 0.18007238],
[0.85377879, 0.63353076, 0.18205711],
[0.85227743, 0.63977494, 0.18424366],
[0.85062503, 0.6459435, 0.18662991],
[0.84882148, 0.65203286, 0.1892131],
[0.84686674, 0.65803948, 0.19198986],
[0.84476088, 0.66395989, 0.19495627],
[0.84250408, 0.66979069, 0.19810788],
[0.84009661, 0.67552853, 0.20143982],
[0.83753885, 0.68117015, 0.20494683],
[0.83483127, 0.68671234, 0.2086233],
[0.83197445, 0.69215196, 0.21246337],
[0.82896909, 0.69748597, 0.21646096],
[0.82581596, 0.70271136, 0.22060982],
[0.82251594, 0.70782524, 0.22490355],
[0.81907005, 0.71282477, 0.22933571],
[0.81547936, 0.7177072, 0.23389979],
[0.81174508, 0.72246985, 0.23858926],
[0.80786851, 0.72711014, 0.24339764],
[0.80385106, 0.73162554, 0.24831845],
[0.79969423, 0.73601365, 0.25334528],
[0.79539964, 0.74027212, 0.25847182],
[0.790969, 0.7443987, 0.2636918],
[0.78640412, 0.74839123, 0.2689991],
[0.78170693, 0.75224764, 0.27438765],
[0.77687945, 0.75596594, 0.27985154],
[0.7719238, 0.75954426, 0.28538495],
[0.7668422, 0.7629808, 0.29098216],
[0.76163698, 0.76627386, 0.29663761],
[0.75631058, 0.76942183, 0.30234581],
[0.75086551, 0.77242321, 0.30810142],
[0.7453044, 0.77527659, 0.31389918],
[0.73963, 0.77798066, 0.31973397],
[0.73384511, 0.78053421, 0.32560075],
[0.72795269, 0.78293613, 0.33149461],
[0.72195575, 0.78518539, 0.33741072],
[0.71585743, 0.7872811, 0.34334436],
[0.70966097, 0.78922244, 0.3492909],
[0.70336969, 0.7910087, 0.35524579],
[0.69698703, 0.79263928, 0.36120459],
[0.69051652, 0.79411368, 0.36716293],
[0.6839618, 0.79543148, 0.37311652],
[0.67732662, 0.79659239, 0.37906117],
[0.67061482, 0.79759621, 0.38499274],
[0.66383034, 0.79844284, 0.39090718],
[0.65697724, 0.7991323, 0.39680051],
[0.65005968, 0.79966468, 0.40266882],
[0.64308193, 0.80004019, 0.40850828],
[0.63604837, 0.80025914, 0.41431512],
[0.62896348, 0.80032194, 0.42008563],
[0.62183187, 0.80022909, 0.42581618],
[0.61465825, 0.79998121, 0.4315032],
[0.60744746, 0.79957898, 0.43714318],
[0.60020446, 0.79902322, 0.44273267],
[0.59293432, 0.79831481, 0.44826831],
[0.58564224, 0.79745474, 0.45374678],
[0.57833356, 0.7964441, 0.45916482],
[0.57101373, 0.79528407, 0.46451926]])
circular4 = mcolors.ListedColormap(circular4_vals)
husl_99_75_vals = \
array([[0.99772728, 0.61398246, 0.69300476],
[0.99773502, 0.61487166, 0.68537325],
[0.99774278, 0.6157606, 0.67761784],
[0.99775055, 0.61665034, 0.66972379],
[0.99775836, 0.61754197, 0.6616753],
[0.99776621, 0.61843657, 0.65345533],
[0.99777411, 0.61933526, 0.64504541],
[0.99778207, 0.62023914, 0.63642541],
[0.9977901, 0.62114938, 0.62757329],
[0.99779821, 0.62206715, 0.61846478],
[0.99780642, 0.62299366, 0.60907298],
[0.99781473, 0.62393019, 0.59936798],
[0.99782316, 0.62487805, 0.58931624],
[0.99783171, 0.62583862, 0.57887998],
[0.99784041, 0.62681333, 0.56801633],
[0.99784927, 0.62780371, 0.55667629],
[0.9978583, 0.62881137, 0.54480344],
[0.99786752, 0.62983801, 0.53233222],
[0.99787695, 0.63088547, 0.5191858],
[0.9978866, 0.63195568, 0.5052731],
[0.9978965, 0.63305074, 0.49048487],
[0.99790666, 0.6341729, 0.47468825],
[0.99791712, 0.63532458, 0.45771902],
[0.99792789, 0.63650843, 0.43937027],
[0.99793901, 0.63772729, 0.41937521],
[0.99795051, 0.63898431, 0.39737988],
[0.99796241, 0.64028289, 0.37289748],
[0.99797477, 0.64162679, 0.34522629],
[0.99798761, 0.64302015, 0.31328787],
[0.99800099, 0.64446754, 0.27526397],
[0.99801496, 0.64597402, 0.22760324],
[0.99802957, 0.64754525, 0.16114023],
[0.99665581, 0.64968082, 0.05220968],
[0.9867071, 0.65480068, 0.05217829],
[0.97700171, 0.65968141, 0.05214805],
[0.96751758, 0.6643454, 0.05211887],
[0.95823432, 0.66881245, 0.05209067],
[0.94913298, 0.67310024, 0.05206335],
[0.94019588, 0.67722454, 0.05203686],
[0.93140648, 0.68119952, 0.05201111],
[0.92274919, 0.68503797, 0.05198606],
[0.91420927, 0.68875141, 0.05196164],
[0.90577274, 0.69235035, 0.0519378],
[0.89742621, 0.69584432, 0.0519145],
[0.88915686, 0.69924207, 0.05189169],
[0.88095231, 0.7025516, 0.05186932],
[0.87280055, 0.7057803, 0.05184736],
[0.86468986, 0.70893497, 0.05182577],
[0.85660874, 0.71202194, 0.05180452],
[0.84854584, 0.71504707, 0.05178357],
[0.8404899, 0.71801587, 0.05176289],
[0.83242966, 0.72093347, 0.05174246],
[0.82435383, 0.72380471, 0.05172224],
[0.81625097, 0.72663416, 0.05170221],
[0.80810945, 0.72942615, 0.05168233],
[0.7999174, 0.7321848, 0.05166259],
[0.79166257, 0.73491406, 0.05164296],
[0.78333229, 0.73761771, 0.05162342],
[0.77491337, 0.74029939, 0.05160394],
[0.76639198, 0.74296264, 0.05158449],
[0.75775357, 0.7456109, 0.05156506],
[0.74898273, 0.74824754, 0.05154562],
[0.74006304, 0.75087584, 0.05152615],
[0.73097693, 0.75349908, 0.05150662],
[0.72170548, 0.75612049, 0.05148701],
[0.71222821, 0.75874329, 0.0514673],
[0.70252286, 0.76137072, 0.05144746],
[0.69256505, 0.76400603, 0.05142746],
[0.682328, 0.76665252, 0.05140728],
[0.67178205, 0.76931353, 0.05138689],
[0.66089424, 0.77199248, 0.05136627],
[0.64962765, 0.7746929, 0.05134538],
[0.63794071, 0.7774184, 0.0513242],
[0.62578628, 0.78017274, 0.05130268],
[0.61311049, 0.78295983, 0.0512808],
[0.59985134, 0.78578375, 0.05125853],
[0.5859368, 0.78864879, 0.05123581],
[0.57128241, 0.79155947, 0.05121261],
[0.55578805, 0.79452056, 0.0511889],
[0.53933359, 0.79753714, 0.0511646],
[0.52177281, 0.80061463, 0.05113969],
[0.50292481, 0.80375879, 0.0511141],
[0.48256137, 0.80697586, 0.05108777],
[0.46038768, 0.81027252, 0.05106063],
[0.43601173, 0.81365601, 0.05103262],
[0.40889268, 0.81713418, 0.05100366],
[0.37824758, 0.82071557, 0.05097365],
[0.34286585, 0.82440951, 0.05094251],
[0.30068778, 0.82822624, 0.05091012],
[0.2476282, 0.83217698, 0.05087638],
[0.17278955, 0.83627415, 0.05084115],
[0.05108215, 0.8395208, 0.09015243],
[0.05150655, 0.83810554, 0.20200306],
[0.05190436, 0.83676888, 0.26584904],
[0.05227845, 0.83550297, 0.31306083],
[0.0526313, 0.83430091, 0.35107166],
[0.05296507, 0.83315665, 0.38306843],
[0.05328166, 0.83206482, 0.4107662],
[0.0535827, 0.83102068, 0.43521338],
[0.05386966, 0.83001997, 0.45710607],
[0.05414383, 0.82905891, 0.47693403],
[0.05440637, 0.82813409, 0.49505699],
[0.05465829, 0.82724245, 0.51174815],
[0.05490052, 0.82638121, 0.52722051],
[0.05513389, 0.82554784, 0.54164375],
[0.05535914, 0.82474007, 0.55515554],
[0.05557694, 0.82395579, 0.56786923],
[0.05578792, 0.8231931, 0.5798794],
[0.05599263, 0.82245022, 0.59126585],
[0.05619159, 0.82172553, 0.60209663],
[0.05638526, 0.82101753, 0.61243023],
[0.05657409, 0.82032482, 0.62231737],
[0.05675847, 0.81964611, 0.63180234],
[0.05693876, 0.81898017, 0.64092408],
[0.05711533, 0.81832587, 0.64971703],
[0.05728848, 0.81768214, 0.65821185],
[0.05745853, 0.81704796, 0.66643594],
[0.05762575, 0.81642237, 0.67441396],
[0.05779041, 0.81580446, 0.68216821],
[0.05795277, 0.81519336, 0.6897189],
[0.05811307, 0.81458824, 0.69708452],
[0.05827153, 0.81398827, 0.70428199],
[0.05842837, 0.81339269, 0.71132689],
[0.05858381, 0.81280073, 0.71823365],
[0.05873806, 0.81221165, 0.72501567],
[0.0588913, 0.81162472, 0.73168545],
[0.05904374, 0.81103924, 0.73825473],
[0.05919555, 0.81045449, 0.74473458],
[0.05934694, 0.80986975, 0.75113547],
[0.05949808, 0.80928434, 0.75746736],
[0.05964916, 0.80869754, 0.76373978],
[0.05980035, 0.80810862, 0.76996191],
[0.05995185, 0.80751688, 0.7761426],
[0.06010383, 0.80692156, 0.78229046],
[0.06025649, 0.80632191, 0.78841389],
[0.06041001, 0.80571715, 0.79452114],
[0.06056459, 0.80510648, 0.80062039],
[0.06072043, 0.80448905, 0.80671972],
[0.06087774, 0.80386401, 0.81282722],
[0.06103672, 0.80323043, 0.81895103],
[0.06119761, 0.80258736, 0.82509934],
[0.06136064, 0.8019338, 0.83128049],
[0.06152604, 0.80126867, 0.83750299],
[0.06169408, 0.80059085, 0.84377556],
[0.06186502, 0.79989911, 0.85010721],
[0.06203917, 0.79919217, 0.85650728],
[0.06221681, 0.79846864, 0.8629855],
[0.06239829, 0.79772703, 0.86955206],
[0.06258396, 0.7969657, 0.87621767],
[0.06277419, 0.79618292, 0.88299366],
[0.06296939, 0.79537677, 0.88989203],
[0.06317002, 0.79454518, 0.89692559],
[0.06337654, 0.79368587, 0.90410803],
[0.06358949, 0.79279633, 0.91145409],
[0.06380945, 0.7918738, 0.91897963],
[0.06403704, 0.79091525, 0.92670185],
[0.06427296, 0.78991729, 0.93463945],
[0.06451797, 0.78887615, 0.94281282],
[0.06477294, 0.78778762, 0.95124433],
[0.06503881, 0.78664698, 0.95995854],
[0.06531664, 0.78544893, 0.9689826],
[0.06560762, 0.78418743, 0.97834661],
[0.06591309, 0.78285567, 0.98808404],
[0.08145765, 0.78123638, 0.99736713],
[0.18579268, 0.77734027, 0.99736573],
[0.24686469, 0.77354432, 0.99736437],
[0.2929153, 0.76984014, 0.99736306],
[0.33066524, 0.76621996, 0.99736178],
[0.3629892, 0.76267657, 0.99736054],
[0.3914302, 0.75920327, 0.99735933],
[0.41692965, 0.75579377, 0.99735814],
[0.44011194, 0.7524422, 0.99735699],
[0.46141635, 0.74914303, 0.99735586],
[0.48116579, 0.74589101, 0.99735475],
[0.49960596, 0.74268117, 0.99735366],
[0.51692891, 0.7395088, 0.99735259],
[0.53328821, 0.73636935, 0.99735154],
[0.54880896, 0.73325847, 0.99735051],
[0.56359473, 0.73017196, 0.99734948],
[0.57773243, 0.72710575, 0.99734847],
[0.5912959, 0.72405585, 0.99734747],
[0.60434857, 0.7210184, 0.99734648],
[0.61694543, 0.71798954, 0.9973455],
[0.6291346, 0.71496551, 0.99734453],
[0.64095854, 0.71194255, 0.99734356],
[0.65245498, 0.70891689, 0.99734259],
[0.66365772, 0.70588476, 0.99734163],
[0.67459724, 0.70284237, 0.99734067],
[0.68530118, 0.69978585, 0.99733971],
[0.69579484, 0.69671127, 0.99733875],
[0.70610146, 0.69361462, 0.99733779],
[0.71624255, 0.69049175, 0.99733683],
[0.72623814, 0.68733837, 0.99733586],
[0.73610702, 0.68415004, 0.99733489],
[0.7458669, 0.68092213, 0.99733392],
[0.7555346, 0.67764978, 0.99733293],
[0.76512618, 0.67432788, 0.99733194],
[0.77465711, 0.67095102, 0.99733093],
[0.78414235, 0.66751347, 0.99732992],
[0.79359649, 0.66400915, 0.99732889],
[0.80303385, 0.66043152, 0.99732785],
[0.81246857, 0.6567736, 0.99732679],
[0.82191471, 0.65302785, 0.99732572],
[0.83138636, 0.64918612, 0.99732462],
[0.84089772, 0.64523958, 0.99732351],
[0.85046317, 0.64117861, 0.99732237],
[0.8600974, 0.63699271, 0.99732121],
[0.86981552, 0.63267036, 0.99732002],
[0.87963311, 0.62819886, 0.99731879],
[0.88956639, 0.62356421, 0.99731754],
[0.89963231, 0.61875086, 0.99731625],
[0.90984868, 0.61374151, 0.99731492],
[0.92023431, 0.6085168, 0.99731355],
[0.93080922, 0.603055, 0.99731213],
[0.94159473, 0.59733158, 0.99731066],
[0.95261376, 0.59131876, 0.99730914],
[0.96389098, 0.58498485, 0.99730756],
[0.9754531, 0.57829356, 0.99730591],
[0.98732921, 0.57120306, 0.99730419],
[0.99732668, 0.56552241, 0.99509296],
[0.99734617, 0.56800304, 0.98314291],
[0.99736455, 0.57032901, 0.97169814],
[0.99738192, 0.57251697, 0.96071116],
[0.99739839, 0.57458132, 0.9501397],
[0.99741404, 0.57653459, 0.93994597],
[0.99742895, 0.57838772, 0.93009603],
[0.99744319, 0.58015033, 0.92055927],
[0.99745682, 0.58183089, 0.91130796],
[0.99746989, 0.58343693, 0.9023169],
[0.99748245, 0.58497512, 0.89356306],
[0.99749455, 0.58645144, 0.88502533],
[0.99750622, 0.58787125, 0.87668428],
[0.9975175, 0.58923935, 0.86852195],
[0.99752842, 0.5905601, 0.86052166],
[0.99753901, 0.59183744, 0.85266786],
[0.9975493, 0.59307496, 0.844946],
[0.99755931, 0.59427592, 0.83734239],
[0.99756906, 0.59544331, 0.8298441],
[0.99757859, 0.59657988, 0.82243884],
[0.99758789, 0.59768816, 0.81511491],
[0.997597, 0.5987705, 0.80786108],
[0.99760593, 0.59982905, 0.80066652],
[0.9976147, 0.60086583, 0.79352076],
[0.99762332, 0.60188273, 0.78641357],
[0.9976318, 0.60288151, 0.77933497],
[0.99764016, 0.60386383, 0.77227509],
[0.99764841, 0.60483126, 0.76522416],
[0.99765656, 0.60578527, 0.75817246],
[0.99766462, 0.60672727, 0.75111021],
[0.99767261, 0.60765861, 0.74402759],
[0.99768054, 0.60858058, 0.73691459],
[0.99768841, 0.60949441, 0.72976102],
[0.99769623, 0.61040131, 0.72255642],
[0.99770402, 0.61130244, 0.71528998],
[0.99771179, 0.61219894, 0.70795047],
[0.99771953, 0.61309191, 0.70052617]])
husl_99_75 = mcolors.ListedColormap(husl_99_75_vals)
husl_99_70_vals = \
array([[0.99739511, 0.52540983, 0.63131701],
[0.99740716, 0.52664976, 0.62142525],
[0.99741923, 0.52788794, 0.61131055],
[0.99743133, 0.5291259, 0.600947],
[0.99744348, 0.53036513, 0.59030602],
[0.9974557, 0.53160716, 0.57935588],
[0.99746799, 0.5328535, 0.5680611],
[0.99748037, 0.5341057, 0.55638174],
[0.99749287, 0.53536534, 0.54427247],
[0.9975055, 0.53663403, 0.5316814],
[0.99751826, 0.53791343, 0.51854867],
[0.9975312, 0.53920526, 0.50480445],
[0.99754431, 0.54051129, 0.49036648],
[0.99755763, 0.54183337, 0.47513657],
[0.99757117, 0.54317344, 0.45899596],
[0.99758495, 0.54453353, 0.44179859],
[0.99759901, 0.5459158, 0.4233614],
[0.99761336, 0.54732252, 0.40344968],
[0.99762803, 0.54875609, 0.38175396],
[0.99764305, 0.55021911, 0.35785177],
[0.99765845, 0.55171431, 0.3311396],
[0.99767428, 0.55324468, 0.3007014],
[0.99769055, 0.55481338, 0.26502095],
[0.99770732, 0.55642389, 0.22122779],
[0.99772463, 0.55807993, 0.16239362],
[0.99774253, 0.55978558, 0.05543238],
[0.98672101, 0.56672467, 0.04510236],
[0.97553984, 0.57346818, 0.04506407],
[0.96475621, 0.5797831, 0.04502766],
[0.95433424, 0.58571732, 0.04499296],
[0.94424161, 0.59131192, 0.04495982],
[0.934449, 0.59660238, 0.0449281],
[0.92492977, 0.60161949, 0.04489767],
[0.91565959, 0.60639017, 0.04486841],
[0.90661613, 0.61093802, 0.04484024],
[0.89777885, 0.61528391, 0.04481305],
[0.88912873, 0.61944629, 0.04478677],
[0.88064813, 0.62344164, 0.04476131],
[0.87232057, 0.62728465, 0.04473663],
[0.86413063, 0.63098853, 0.04471264],
[0.85606379, 0.63456518, 0.04468929],
[0.84810633, 0.63802536, 0.04466654],
[0.84024519, 0.64137884, 0.04464433],
[0.83246792, 0.64463451, 0.04462262],
[0.82476257, 0.64780052, 0.04460136],
[0.81711759, 0.65088434, 0.04458052],
[0.8095218, 0.65389283, 0.04456005],
[0.80196428, 0.65683234, 0.04453994],
[0.79443432, 0.65970877, 0.04452013],
[0.78692133, 0.66252758, 0.04450061],
[0.77941483, 0.6652939, 0.04448135],
[0.77190433, 0.6680125, 0.04446231],
[0.76437929, 0.67068792, 0.04444347],
[0.75682907, 0.67332439, 0.0444248],
[0.74924283, 0.67592596, 0.04440628],
[0.7416095, 0.67849646, 0.04438789],
[0.73391767, 0.68103958, 0.0443696],
[0.72615554, 0.68355883, 0.04435139],
[0.71831081, 0.68605761, 0.04433323],
[0.71037061, 0.68853922, 0.04431512],
[0.70232137, 0.69100687, 0.04429701],
[0.69414872, 0.69346367, 0.0442789],
[0.68583738, 0.69591272, 0.04426075],
[0.67737097, 0.69835704, 0.04424256],
[0.66873186, 0.70079967, 0.04422428],
[0.65990097, 0.70324359, 0.04420591],
[0.65085755, 0.70569182, 0.04418743],
[0.6415789, 0.70814739, 0.04416879],
[0.63204004, 0.71061338, 0.04414999],
[0.62221336, 0.7130929, 0.04413099],
[0.61206813, 0.71558914, 0.04411178],
[0.60156995, 0.71810538, 0.04409231],
[0.5906801, 0.720645, 0.04407257],
[0.57935463, 0.72321148, 0.04405252],
[0.56754337, 0.72580848, 0.04403214],
[0.55518854, 0.72843981, 0.04401138],
[0.54222301, 0.73110944, 0.04399021],
[0.52856809, 0.7338216, 0.0439686],
[0.5141305, 0.73658074, 0.0439465],
[0.49879828, 0.73939158, 0.04392386],
[0.4824352, 0.74225917, 0.04390065],
[0.46487269, 0.7451889, 0.0438768],
[0.44589809, 0.74818655, 0.04385227],
[0.42523671, 0.75125837, 0.04382698],
[0.40252327, 0.75441109, 0.04380088],
[0.37725382, 0.75765204, 0.04377389],
[0.34869881, 0.76098917, 0.04374593],
[0.31573022, 0.76443118, 0.04371691],
[0.27642882, 0.76798759, 0.04368674],
[0.22698806, 0.77166888, 0.0436553],
[0.15725362, 0.77548661, 0.04362247],
[0.04384703, 0.77851183, 0.08025261],
[0.04424249, 0.77719309, 0.18447469],
[0.04461316, 0.7759476, 0.24396619],
[0.04496174, 0.77476802, 0.28795799],
[0.04529053, 0.77364795, 0.32337637],
[0.04560154, 0.77258173, 0.35319087],
[0.04589653, 0.77156437, 0.37899956],
[0.04617703, 0.77059144, 0.40177938],
[0.04644442, 0.76965898, 0.42217892],
[0.0466999, 0.76876347, 0.44065455],
[0.04694453, 0.76790173, 0.45754148],
[0.04717927, 0.7670709, 0.47309425],
[0.04740498, 0.76626839, 0.48751134],
[0.04762243, 0.76549187, 0.50095088],
[0.04783232, 0.76473919, 0.51354113],
[0.04803527, 0.7640084, 0.5253877],
[0.04823185, 0.76329772, 0.53657874],
[0.0484226, 0.76260551, 0.54718861],
[0.04860799, 0.76193025, 0.55728069],
[0.04878846, 0.76127054, 0.56690951],
[0.04896441, 0.76062507, 0.57612231],
[0.04913621, 0.75999265, 0.58496038],
[0.04930421, 0.75937213, 0.59345999],
[0.04946873, 0.75876245, 0.60165324],
[0.04963008, 0.75816263, 0.60956868],
[0.04978853, 0.7575717, 0.61723187],
[0.04994434, 0.75698878, 0.62466577],
[0.05009777, 0.75641302, 0.63189115],
[0.05024906, 0.7558436, 0.63892687],
[0.05039842, 0.75527974, 0.64579013],
[0.05054607, 0.75472069, 0.65249671],
[0.05069222, 0.75416573, 0.65906113],
[0.05083706, 0.75361414, 0.66549682],
[0.05098078, 0.75306524, 0.67181628],
[0.05112358, 0.75251835, 0.67803117],
[0.05126561, 0.7519728, 0.68415241],
[0.05140708, 0.75142792, 0.69019031],
[0.05154814, 0.75088307, 0.69615464],
[0.05168897, 0.75033758, 0.70205467],
[0.05182974, 0.7497908, 0.7078993],
[0.05197063, 0.74924206, 0.71369706],
[0.05211179, 0.74869067, 0.71945621],
[0.05225341, 0.74813595, 0.72518477],
[0.05239565, 0.7475772, 0.73089056],
[0.0525387, 0.74701369, 0.73658128],
[0.05268274, 0.74644466, 0.74226454],
[0.05282795, 0.74586935, 0.74794788],
[0.05297453, 0.74528693, 0.75363883],
[0.05312268, 0.74469657, 0.75934497],
[0.05327259, 0.74409736, 0.76507395],
[0.0534245, 0.74348838, 0.77083353],
[0.05357862, 0.74286861, 0.77663163],
[0.05373519, 0.74223701, 0.7824764],
[0.05389448, 0.74159246, 0.78837621],
[0.05405675, 0.74093373, 0.79433978],
[0.05422228, 0.74025955, 0.80037617],
[0.05439138, 0.73956851, 0.80649487],
[0.05456438, 0.73885911, 0.81270587],
[0.05474164, 0.73812972, 0.81901971],
[0.05492353, 0.73737856, 0.82544759],
[0.05511047, 0.73660368, 0.83200144],
[0.05530291, 0.73580297, 0.83869402],
[0.05550134, 0.7349741, 0.84553905],
[0.05570629, 0.7341145, 0.85255133],
[0.05591836, 0.73322132, 0.85974687],
[0.05613819, 0.73229142, 0.8671431],
[0.05636649, 0.73132129, 0.87475903],
[0.05660407, 0.730307, 0.88261548],
[0.05685181, 0.72924416, 0.89073536],
[0.05711069, 0.72812782, 0.89914395],
[0.05738183, 0.72695236, 0.9078693],
[0.05766646, 0.72571142, 0.91694261],
[0.05796599, 0.72439775, 0.92639876],
[0.05828203, 0.72300301, 0.9362769],
[0.0586164, 0.7215176, 0.94662121],
[0.05897118, 0.7199304, 0.95748173],
[0.05934879, 0.71822842, 0.96891546],
[0.05975201, 0.71639643, 0.98098768],
[0.06018409, 0.71441646, 0.99377354],
[0.1552159, 0.71069214, 0.99683284],
[0.22399818, 0.70653103, 0.99683105],
[0.27374331, 0.70242748, 0.99682931],
[0.31394441, 0.69837516, 0.9968276],
[0.34818394, 0.69436806, 0.99682593],
[0.37827033, 0.69040041, 0.99682428],
[0.40526634, 0.68646664, 0.99682266],
[0.42985914, 0.68256138, 0.99682106],
[0.45252341, 0.67867941, 0.99681948],
[0.4736034, 0.67481562, 0.99681792],
[0.49335828, 0.670965, 0.99681638],
[0.51198911, 0.66712262, 0.99681486],
[0.52965567, 0.66328356, 0.99681334],
[0.54648759, 0.65944294, 0.99681184],
[0.56259184, 0.65559586, 0.99681035],
[0.57805805, 0.65173739, 0.99680886],
[0.59296234, 0.64786252, 0.99680738],
[0.60737008, 0.64396617, 0.9968059],
[0.62133808, 0.64004313, 0.99680442],
[0.63491614, 0.63608805, 0.99680294],
[0.64814838, 0.63209538, 0.99680146],
[0.66107418, 0.62805939, 0.99679998],
[0.67372903, 0.62397408, 0.99679849],
[0.68614513, 0.61983316, 0.99679699],
[0.69835197, 0.61563002, 0.99679549],
[0.71037672, 0.61135765, 0.99679397],
[0.72224466, 0.60700863, 0.99679244],
[0.73397945, 0.60257502, 0.99679089],
[0.74560341, 0.59804834, 0.99678933],
[0.75713779, 0.59341947, 0.99678774],
[0.76860292, 0.58867854, 0.99678614],
[0.78001848, 0.58381487, 0.99678451],
[0.79140359, 0.57881685, 0.99678285],
[0.802777, 0.57367178, 0.99678116],
[0.81415726, 0.56836573, 0.99677944],
[0.82556283, 0.56288336, 0.99677769],
[0.83701224, 0.55720772, 0.99677589],
[0.84852423, 0.55131997, 0.99677406],
[0.86011784, 0.54519909, 0.99677217],
[0.87181264, 0.53882151, 0.99677024],
[0.88362881, 0.53216071, 0.99676825],
[0.8955873, 0.52518662, 0.9967662],
[0.90771006, 0.51786504, 0.99676409],
[0.92002016, 0.51015677, 0.9967619],
[0.93254202, 0.5020166, 0.99675964],
[0.94530164, 0.49339205, 0.99675729],
[0.95832685, 0.48422168, 0.99675485],
[0.97164763, 0.47443296, 0.99675231],
[0.98529636, 0.46393935, 0.99674966],
[0.99677214, 0.45542394, 0.99422674],
[0.99680244, 0.45913988, 0.98052145],
[0.996831, 0.4626091, 0.96736354],
[0.99685801, 0.46585952, 0.95470108],
[0.99688361, 0.46891505, 0.94248772],
[0.99690794, 0.47179631, 0.93068192],
[0.99693113, 0.47452117, 0.91924628],
[0.99695327, 0.47710522, 0.90814695],
[0.99697446, 0.47956212, 0.89735317],
[0.99699478, 0.4819039, 0.88683687],
[0.99701431, 0.48414119, 0.8765723],
[0.99703312, 0.48628346, 0.86653575],
[0.99705127, 0.48833911, 0.85670528],
[0.99706881, 0.49031572, 0.84706049],
[0.99708579, 0.49222005, 0.83758234],
[0.99710226, 0.49405823, 0.82825294],
[0.99711826, 0.49583579, 0.81905543],
[0.99713383, 0.49755778, 0.80997383],
[0.997149, 0.49922877, 0.80099288],
[0.99716381, 0.50085296, 0.79209797],
[0.99717829, 0.5024342, 0.78327502],
[0.99719246, 0.50397603, 0.77451036],
[0.99720635, 0.50548173, 0.76579067],
[0.99721998, 0.50695433, 0.75710286],
[0.99723338, 0.50839665, 0.748434],
[0.99724658, 0.50981133, 0.73977124],
[0.99725958, 0.51120082, 0.73110169],
[0.99727241, 0.51256746, 0.72241241],
[0.99728509, 0.51391342, 0.71369023],
[0.99729764, 0.51524077, 0.70492172],
[0.99731007, 0.51655148, 0.69609308],
[0.9973224, 0.51784744, 0.68719002],
[0.99733464, 0.51913043, 0.67819767],
[0.99734681, 0.5204022, 0.66910042],
[0.99735893, 0.52166442, 0.65988182],
[0.99737101, 0.52291871, 0.6505244],
[0.99738307, 0.52416666, 0.64100949]])
husl_99_70 = mcolors.ListedColormap(husl_99_70_vals)
husl_99_65_vals = \
array([[0.99709929, 0.42642982, 0.56899161],
[0.99711717, 0.42821719, 0.55635822],
[0.99713508, 0.42999821, 0.54332701],
[0.99715303, 0.43177511, 0.52984726],
[0.99717106, 0.43355011, 0.51586063],
[0.99718919, 0.43532538, 0.50129938],
[0.99720743, 0.43710314, 0.48608391],
[0.99722581, 0.43888559, 0.47011948],
[0.99724436, 0.44067497, 0.45329166],
[0.99726309, 0.44247353, 0.43545994],
[0.99728204, 0.4442836, 0.41644838],
[0.99730124, 0.44610755, 0.39603143],
[0.9973207, 0.44794781, 0.37391169],
[0.99734047, 0.44980693, 0.34968283],
[0.99736056, 0.45168752, 0.32276375],
[0.99738102, 0.45359234, 0.29227071],
[0.99740189, 0.45552427, 0.25673712],
[0.99742319, 0.45748632, 0.21337608],
[0.99744497, 0.45948171, 0.15541924],
[0.99746727, 0.46151384, 0.04986161],
[0.98399445, 0.47222628, 0.0381439],
[0.97044573, 0.48240482, 0.03809373],
[0.95757128, 0.49166634, 0.03804691],
[0.94530301, 0.50014487, 0.03800306],
[0.93358125, 0.50794893, 0.03796187],
[0.92235342, 0.51516753, 0.03792304],
[0.91157294, 0.52187445, 0.03788634],
[0.90119836, 0.5281315, 0.03785157],
[0.89119264, 0.53399087, 0.03781852],
[0.8815225, 0.53949701, 0.03778705],
[0.87215793, 0.54468803, 0.037757],
[0.86307175, 0.54959684, 0.03772825],
[0.85423922, 0.55425203, 0.03770068],
[0.84563777, 0.55867855, 0.03767418],
[0.8372467, 0.56289833, 0.03764868],
[0.82904693, 0.56693071, 0.03762408],
[0.82102081, 0.57079283, 0.03760031],
[0.81315199, 0.57449996, 0.03757729],
[0.80542516, 0.57806574, 0.03755498],
[0.79782603, 0.58150243, 0.0375333],
[0.79034112, 0.58482106, 0.03751222],
[0.7829577, 0.58803163, 0.03749167],
[0.77566365, 0.59114319, 0.03747162],
[0.76844742, 0.59416401, 0.03745203],
[0.76129792, 0.59710163, 0.03743285],
[0.75420444, 0.59996298, 0.03741406],
[0.7471566, 0.60275444, 0.03739561],
[0.74014427, 0.60548191, 0.03737748],
[0.7331575, 0.60815083, 0.03735963],
[0.72618649, 0.6107663, 0.03734205],
[0.71922149, 0.61333306, 0.0373247],
[0.71225279, 0.61585555, 0.03730755],
[0.70527059, 0.61833796, 0.0372906],
[0.69826503, 0.62078425, 0.0372738],
[0.69122605, 0.62319814, 0.03725714],
[0.68414338, 0.62558321, 0.0372406],
[0.67700643, 0.62794287, 0.03722415],
[0.66980424, 0.63028039, 0.03720778],
[0.66252542, 0.63259891, 0.03719147],
[0.65515801, 0.63490151, 0.03717519],
[0.64768943, 0.63719114, 0.03715892],
[0.64010635, 0.63947071, 0.03714266],
[0.63239457, 0.64174309, 0.03712637],
[0.62453891, 0.64401109, 0.03711003],
[0.61652301, 0.6462775, 0.03709364],
[0.60832917, 0.64854512, 0.03707716],
[0.59993813, 0.65081674, 0.03706058],
[0.59132882, 0.65309517, 0.03704387],
[0.58247808, 0.65538327, 0.03702702],
[0.57336028, 0.65768392, 0.03700999],
[0.56394691, 0.66000009, 0.03699278],
[0.55420606, 0.66233481, 0.03697534],
[0.54410178, 0.66469122, 0.03695767],
[0.53359332, 0.66707257, 0.03693972],
[0.5226341, 0.66948222, 0.03692148],
[0.51117052, 0.67192373, 0.03690291],
[0.49914031, 0.67440078, 0.03688398],
[0.48647043, 0.67691729, 0.03686465],
[0.47307434, 0.67947739, 0.0368449],
[0.45884817, 0.68208546, 0.03682467],
[0.44366549, 0.68474618, 0.03680393],
[0.42736991, 0.68746456, 0.03678264],
[0.40976411, 0.69024597, 0.03676074],
[0.39059321, 0.69309619, 0.03673818],
[0.36951828, 0.69602149, 0.03671489],
[0.34607173, 0.69902864, 0.03669083],
[0.31957663, 0.70212503, 0.03666591],
[0.28898634, 0.70531874, 0.03664005],
[0.25252008, 0.70861859, 0.03661318],
[0.2066459, 0.71203432, 0.03658519],
[0.14194199, 0.71557665, 0.03655598],
[0.03675607, 0.71838364, 0.0704957],
[0.03710997, 0.71716003, 0.16719937],
[0.0374435, 0.71600438, 0.22239925],
[0.03775874, 0.7149099, 0.26321755],
[0.03805749, 0.71387063, 0.29608091],
[0.03834135, 0.71288132, 0.32374464],
[0.03861173, 0.71193735, 0.34769154],
[0.03886986, 0.71103461, 0.36882805],
[0.03911686, 0.71016942, 0.387756],
[0.0393537, 0.70933851, 0.40489883],
[0.03958127, 0.70853893, 0.42056756],
[0.03980036, 0.70776803, 0.43499838],
[0.04001169, 0.70702342, 0.44837545],
[0.0402159, 0.70630291, 0.46084548],
[0.04041359, 0.70560453, 0.47252749],
[0.04060247, 0.70492646, 0.48351947],
[0.04078488, 0.70426705, 0.49390321],
[0.04096187, 0.70362477, 0.50374769],
[0.04113388, 0.70299822, 0.51311175],
[0.04130133, 0.7023861, 0.52204596],
[0.04146458, 0.7017872, 0.53059417],
[0.04162399, 0.7012004, 0.53879467],
[0.04177987, 0.70062464, 0.54668114],
[0.04193253, 0.70005895, 0.55428334],
[0.04208223, 0.69950239, 0.56162777],
[0.04222925, 0.69895409, 0.56873815],
[0.04237383, 0.69841322, 0.57563578],
[0.04251619, 0.69787899, 0.58233993],
[0.04265656, 0.69735065, 0.5888681],
[0.04279515, 0.69682747, 0.59523626],
[0.04293215, 0.69630875, 0.60145904],
[0.04306775, 0.69579382, 0.60754991],
[0.04320215, 0.69528203, 0.61352135],
[0.0433355, 0.69477272, 0.61938493],
[0.04346799, 0.69426528, 0.62515148],
[0.04359978, 0.69375908, 0.63083115],
[0.04373104, 0.69325352, 0.63643349],
[0.04386193, 0.69274797, 0.64196756],
[0.0439926, 0.69224183, 0.64744197],
[0.04412322, 0.69173449, 0.65286498],
[0.04425394, 0.69122533, 0.6582445],
[0.04438492, 0.69071372, 0.66358819],
[0.04451632, 0.69019902, 0.6689035],
[0.0446483, 0.68968058, 0.67419768],
[0.04478104, 0.68915772, 0.67947789],
[0.04491468, 0.68862974, 0.68475116],
[0.04504942, 0.68809593, 0.69002451],
[0.04518542, 0.68755553, 0.69530493],
[0.04532288, 0.68700775, 0.70059944],
[0.04546198, 0.68645177, 0.70591514],
[0.04560293, 0.68588671, 0.71125924],
[0.04574593, 0.68531166, 0.71663907],
[0.04589121, 0.68472563, 0.7220622],
[0.04603901, 0.68412757, 0.72753642],
[0.04618957, 0.68351636, 0.73306978],
[0.04634316, 0.68289081, 0.73867072],
[0.04650006, 0.68224963, 0.74434802],
[0.04666059, 0.6815914, 0.75011097],
[0.04682506, 0.68091463, 0.75596934],
[0.04699383, 0.68021765, 0.76193352],
[0.04716728, 0.67949867, 0.76801459],
[0.04734584, 0.67875573, 0.77422438],
[0.04752995, 0.67798665, 0.78057562],
[0.04772012, 0.67718905, 0.78708204],
[0.04791689, 0.67636031, 0.79375851],
[0.04812086, 0.67549749, 0.80062119],
[0.04833269, 0.67459734, 0.80768771],
[0.04855314, 0.67365623, 0.81497741],
[0.048783, 0.67267006, 0.82251154],
[0.04902321, 0.67163424, 0.83031355],
[0.04927478, 0.67054358, 0.83840947],
[0.04953888, 0.66939216, 0.84682824],
[0.04981681, 0.66817326, 0.85560224],
[0.05011005, 0.66687913, 0.86476779],
[0.05042029, 0.66550088, 0.87436588],
[0.05074949, 0.66402817, 0.88444293],
[0.05109985, 0.66244897, 0.89505186],
[0.05147399, 0.66074914, 0.9062532],
[0.0518749, 0.658912, 0.91811672],
[0.05230613, 0.65691766, 0.93072321],
[0.05277185, 0.65474227, 0.94416692],
[0.05327702, 0.65235693, 0.95855856],
[0.05382762, 0.64972631, 0.97402919],
[0.05443084, 0.64680671, 0.99073527],
[0.14568077, 0.64250689, 0.99626241],
[0.21844541, 0.63769958, 0.99626002],
[0.27024912, 0.63291619, 0.99625766],
[0.31197896, 0.62815026, 0.99625534],
[0.34753421, 0.62339545, 0.99625304],
[0.37883671, 0.61864543, 0.99625077],
[0.40699988, 0.61389394, 0.99624852],
[0.43273676, 0.60913466, 0.99624629],
[0.45653658, 0.60436124, 0.99624408],
[0.4787524, 0.59956725, 0.99624188],
[0.49964912, 0.59474611, 0.99623968],
[0.51943173, 0.5898911, 0.9962375],
[0.53826293, 0.58499529, 0.99623532],
[0.5562746, 0.58005149, 0.99623314],
[0.57357565, 0.57505221, 0.99623096],
[0.59025741, 0.56998965, 0.99622878],
[0.60639758, 0.56485555, 0.9962266],
[0.62206311, 0.55964121, 0.9962244],
[0.63731236, 0.55433741, 0.9962222],
[0.65219677, 0.54893426, 0.99621998],
[0.66676211, 0.5434212, 0.99621774],
[0.68104956, 0.53778685, 0.99621548],
[0.69509648, 0.5320189, 0.99621321],
[0.70893712, 0.52610395, 0.9962109],
[0.72260312, 0.5200274, 0.99620857],
[0.73612401, 0.51377323, 0.9962062],
[0.74952757, 0.50732379, 0.9962038],
[0.76284021, 0.50065953, 0.99620136],
[0.7760872, 0.49375872, 0.99619887],
[0.78929299, 0.48659703, 0.99619634],
[0.80248144, 0.47914712, 0.99619375],
[0.81567598, 0.47137806, 0.99619111],
[0.82889991, 0.46325464, 0.9961884],
[0.84217651, 0.45473652, 0.99618563],
[0.85552929, 0.44577716, 0.99618278],
[0.86898217, 0.43632237, 0.99617985],
[0.88255968, 0.42630856, 0.99617683],
[0.89628714, 0.41566032, 0.99617371],
[0.91019093, 0.40428721, 0.99617049],
[0.92429867, 0.39207928, 0.99616716],
[0.93863954, 0.37890091, 0.9961637],
[0.95324451, 0.36458167, 0.9961601],
[0.96814667, 0.34890272, 0.99615636],
[0.98338161, 0.33157548, 0.99615245],
[0.99617547, 0.31704148, 0.99335271],
[0.99622037, 0.3234138, 0.97808605],
[0.99626271, 0.32928737, 0.96339664],
[0.99630274, 0.33472782, 0.94922882],
[0.99634069, 0.33978954, 0.9355328],
[0.99637676, 0.34451806, 0.92226381],
[0.99641113, 0.34895187, 0.90938143],
[0.99644395, 0.35312373, 0.89684893],
[0.99647537, 0.35706176, 0.88463283],
[0.9965055, 0.36079024, 0.87270244],
[0.99653446, 0.3643303, 0.86102946],
[0.99656235, 0.36770038, 0.84958769],
[0.99658926, 0.37091671, 0.83835276],
[0.99661527, 0.3739936, 0.82730183],
[0.99664045, 0.37694377, 0.81641344],
[0.99666487, 0.37977854, 0.80566726],
[0.9966886, 0.38250806, 0.79504395],
[0.99671169, 0.38514142, 0.78452496],
[0.99673419, 0.38768686, 0.77409245],
[0.99675616, 0.39015182, 0.76372906],
[0.99677763, 0.39254305, 0.75341788],
[0.99679864, 0.39486675, 0.74314223],
[0.99681925, 0.39712854, 0.73288562],
[0.99683947, 0.39933364, 0.72263158],
[0.99685935, 0.40148682, 0.71236354],
[0.99687892, 0.40359252, 0.70206473],
[0.99689821, 0.40565484, 0.69171803],
[0.99691725, 0.40767763, 0.68130583],
[0.99693606, 0.40966447, 0.67080987],
[0.99695467, 0.41161872, 0.66021111],
[0.99697311, 0.41354356, 0.64948949],
[0.9969914, 0.415442, 0.63862378],
[0.99700956, 0.41731689, 0.62759127],
[0.99702763, 0.41917096, 0.61636756],
[0.99704561, 0.42100681, 0.60492617],
[0.99706353, 0.42282697, 0.59323818],
[0.99708142, 0.42463385, 0.58127177]])
husl_99_65 = mcolors.ListedColormap(husl_99_65_vals)
| 91,838 | 49.157837 | 65 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/deprecated/normal_modes_deprecated.py
|
from __future__ import division
import dolfin as df
import numpy as np
import logging
import os
import scipy.sparse.linalg
from time import time
from finmag.util import helpers
from finmag.util.meshes import embed3d
from itertools import izip
from math import pi
from finmag.field import Field
logger = logging.getLogger('finmag')
# Matrix-vector or Matrix-matrix product
def _mult_one(a, b):
# a and b are ?x?xn arrays where ? = 1..3
assert len(a.shape) == 3
assert len(b.shape) == 3
assert a.shape[2] == b.shape[2]
assert a.shape[1] == b.shape[0]
assert a.shape[0] <= 3 and a.shape[1] <= 3
assert b.shape[0] <= 3 and b.shape[1] <= 3
# One of the arrays might be complex, so we determine the type
# of the resulting array by adding two elements of the argument arrays
res = np.zeros(
(a.shape[0], b.shape[1], a.shape[2]), dtype=type(a[0, 0, 0] + b[0, 0, 0]))
for i in xrange(res.shape[0]):
for j in xrange(res.shape[1]):
for k in xrange(a.shape[1]):
res[i, j, :] += a[i, k, :] * b[k, j, :]
return res
# Returns the componentwise matrix product of the supplied matrix fields
def mf_mult(*args):
if len(args) < 2:
raise Exception("mult requires at least 2 arguments")
res = args[0]
for i in xrange(1, len(args)):
res = _mult_one(res, args[i])
return res
# Transposes the mxk matrix to a kxm matrix
def mf_transpose(a):
return np.transpose(a, [1, 0, 2])
# Computes the componentwise cross product of a vector field a
# and a vector or vector field b
def mf_cross(a, b):
assert a.shape == (3, 1, a.shape[2])
res = np.empty(a.shape, dtype=a.dtype)
res[0] = a[1] * b[2] - a[2] * b[1]
res[1] = a[2] * b[0] - a[0] * b[2]
res[2] = a[0] * b[1] - a[1] * b[0]
return res
# Normalises the 3d vector m
def mf_normalise(m):
assert m.shape == (3, 1, m.shape[2])
return m / np.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2])
# Set up the basis for the tangential space and the corresponding
# projection operator
def compute_tangential_space_basis(m0):
assert m0.ndim == 3
n = m0.shape[2]
assert m0.shape == (3, 1, n)
# Set up a field of vectors m_perp that are perpendicular to m0
# Start with e_z and compute e_z x m
m_perp = mf_cross(m0, [0., 0., -1.])
# In case m || e_z, add a tiny component in e_y
m_perp[1] += 1e-100
# Normalise and compute the cross product with m0 again
m_perp = mf_cross(mf_normalise(m_perp), m0)
m_perp = mf_normalise(m_perp)
# The basis in the 3d space is ((m_perp x m0) x m0, m_perp x m0, m0)
R = np.zeros((3, 3, n))
R[:, 2, :] = m0[:, 0, :]
R[:, 1, :] = m_perp[:, 0, :]
R[:, 0, :] = mf_cross(m_perp, m0)[:, 0, :]
# Matrix for the injection from 2n to 3n (3x2)
S = np.zeros((3, 2, n))
S[0, 0, :] = 1.
S[1, 1, :] = 1.
# Matrix for the projection from 3n to 2n is transpose(S)
# Matrix for the cross product m0 x in the 2n space
Mcross = np.zeros((2, 2, n))
Mcross[0, 1, :] = -1
Mcross[1, 0, :] = 1
# The relationship between the 3d tangential vector v
# and the 2d vector w is
# v = (R S) w
# w = (R S)^t v
Q = mf_mult(R, S)
return Q, R, S, Mcross
def differentiate_fd4(f, x, dx):
"""
Compute and return a fourth-order approximation to the directional
derivative of `f` at the point `x` in the direction of `dx`.
"""
x_sq = np.dot(x, x)
dx_sq = np.dot(dx, dx)
h = 0.001 * np.sqrt(x_sq + dx_sq) / np.sqrt(dx_sq + 1e-50)
# weights: 1. / 12., -2. / 3., 2. / 3., -1. / 12.
# coefficients: -2., -1., 1., 2.
res = (1. / 12. / h) * f(x - 2 * h * dx)
res += (-2. / 3. / h) * f(x - h * dx)
res += (2. / 3. / h) * f(x + h * dx)
res += (-1. / 12. / h) * f(x + 2 * h * dx)
return res
def compute_eigenproblem_matrix(sim, frequency_unit=1e9, filename=None, differentiate_H_numerically=True, dtype=complex):
"""
Compute and return the square matrix `D` defining the eigenproblem which
has the normal mode frequencies and oscillation patterns as its solution.
Note that `sim` needs to be in a relaxed state, otherwise the results will
be wrong.
"""
# Create the helper simulation which we use to compute
# the effective field for various values of m.
#Ms = sim.Ms
#A = sim.get_interaction('Exchange').A
#unit_length = sim.unit_length
# try:
# sim.get_interaction('Demag')
# demag_solver = 'FK'
# except ValueError:
# demag_solver = None
#sim_aux = sim_with(sim.mesh, Ms=Ms, m_init=[1, 0, 0], A=A, unit_length=unit_length, demag_solver=demag_solver)
# In order to compute the derivative of the effective field, the magnetisation needs to be set
# to many different values. Thus we store a backup so that we can restore
# it later.
m_orig = sim.m
def effective_field_for_m(m, normalise=True):
if np.iscomplexobj(m):
raise NotImplementedError(
"XXX TODO: Implement the version for complex arrays!")
sim.set_m(m, normalise=normalise, debug=False)
return sim.effective_field()
# N is the number of degrees of freedom of the magnetisation vector.
# It may be smaller than the number of mesh nodes if we are using
# periodic boundary conditions.
N = sim.llg.S3.dim()
n = N // 3
assert (N == 3 * n)
m0_array = sim.m.copy()
# this corresponds to the vector 'm0_flat' in Simlib
m0_3xn = m0_array.reshape(3, n)
m0_column_vector = m0_array.reshape(3, 1, n)
H0_array = effective_field_for_m(m0_array)
H0_3xn = H0_array.reshape(3, n)
h0 = H0_3xn[0] * m0_3xn[0] + H0_3xn[1] * m0_3xn[1] + H0_3xn[2] * m0_3xn[2]
logger.debug(
"Computing basis of the tangent space and transition matrices.")
Q, R, S, Mcross = compute_tangential_space_basis(m0_column_vector)
Qt = mf_transpose(Q).copy()
# Returns the product of the linearised llg times vector
def linearised_llg_times_vector(v):
assert v.shape == (3, 1, n)
# The linearised equation is
# dv/dt = - gamma m0 x (H' v - h_0 v)
v_array = v.view()
v_array.shape = (-1,)
# Compute H'(m_0)*v, i.e. the "directional derivative" of H at
# m_0 in the direction of v. Since H is linear in m (at least
# theoretically, although this is not quite true in the case
# of our demag computation), this is the same as H(v)!
if differentiate_H_numerically:
res = differentiate_fd4(effective_field_for_m, m0_array, v_array)
else:
res = effective_field_for_m(v_array, normalise=False)
res.shape = (3, -1)
# Subtract h0 v
res[0] -= h0 * v[0, 0]
res[1] -= h0 * v[1, 0]
res[2] -= h0 * v[2, 0]
# Multiply by -gamma m0x
res *= sim.gamma
res.shape = (3, 1, -1)
# Put res on the left in case v is complex
res = mf_cross(res, m0_column_vector)
return res
# The linearised equation in the tangential basis
def linearised_llg_times_tangential_vector(w):
w = w.view()
w.shape = (2, 1, n)
# Go to the 3d space
v = mf_mult(Q, w)
# Compute the linearised llg
L = linearised_llg_times_vector(v)
# Go back to 2d space
res = np.empty(w.shape, dtype=dtype)
res[:] = mf_mult(Qt, L)
if dtype == complex:
# Multiply by -i/(2*pi*U) so that we get frequencies as the real
# part of eigenvalues
res *= -1j / (2 * pi * frequency_unit)
else:
# This will yield imaginary eigenvalues, but we divide by 1j in the
# calling routine.
res *= 1. / (2 * pi * frequency_unit)
res.shape = (-1,)
return res
df.tic()
logger.info("Assembling eigenproblem matrix.")
D = np.zeros((2 * n, 2 * n), dtype=dtype)
logger.debug("Eigenproblem matrix D will occupy {:.2f} MB of memory.".format(
D.nbytes / 1024. ** 2))
for i, w in enumerate(np.eye(2 * n)):
if i % 50 == 0:
t_cur = df.toc()
completion_info = '' if (i == 0) else ', estimated remaining time: {}'.format(
helpers.format_time(t_cur * (2 * n / i - 1)))
logger.debug("Processing row {}/{} (time elapsed: {}{})".format(i,
2 * n, helpers.format_time(t_cur), completion_info))
D[:, i] = linearised_llg_times_tangential_vector(w)
logger.debug("Eigenproblem matrix D occupies {:.2f} MB of memory.".format(
D.nbytes / 1024. ** 2))
logger.info("Finished assembling eigenproblem matrix.")
if filename != None:
logger.info("Saving eigenproblem matrix to file '{}'".format(filename))
np.save(filename, D)
# Restore the original magnetisation.
# XXX TODO: Is this method safe, or does it leave any trace of the
# temporary changes we did above?
sim.set_m(m_orig)
return D
# We use the following class (which behaves like a function due to its
# __call__ method) instead of a simple lambda expression because it is
# pickleable, which is needed if we want to cache computation results.
#
# XXX TODO: lambda expresions can be pickled with the 'dill' module,
# so we should probably get rid of this.
class M_times_w(object):
def __init__(self, Mcross, n, alpha=0.):
self.Mcross = Mcross
self.n = n
self.alpha = alpha
def __call__(self, w):
w = w.view()
w.shape = (2, 1, self.n)
res = -1j * mf_mult(self.Mcross, w)
if self.alpha != 0.:
res += -1j * self.alpha * w
res.shape = (-1,)
return res
class NotImplementedOp(object):
def __call__(self, w):
raise NotImplementedError("rmatvec is not implemented")
def is_hermitian(A, atol=1e-8, rtol=1e-12):
"""
Returns True if the matrix `A` is Hermitian (up to the given
tolerance) and False otherwise.
The arguments `atol` and `rtol` have the same meaning as in
`numpy.allclose`.
"""
if isinstance(A, np.ndarray):
# Note: just using an absolute tolerance and checking for
# the maximum difference is about twice as efficient, so
# maybe we should avoid the relative tolerance in the future.
return np.allclose(A, np.conj(A.T), atol=atol, rtol=rtol)
elif isinstance(A, scipy.sparse.linalg.LinearOperator):
raise NotImplementedError
else:
raise NotImplementedError
def check_is_hermitian(A, matrix_name, atol=1e-8, rtol=1e-12):
"""
Check if `A` is hermitian and print a warning if this is not the case.
The argument `matrix_name` is only used for printing the warning.
"""
if not is_hermitian(A):
mat_diff = np.absolute(A - np.conj(A.T))
logger.critical("Matrix {} is not Hermitian. Maximum difference "
"between A and conj(A^tr): {}, median difference: {}, "
"mean difference: {} (maximum entry of A: {}, "
"median entry: {}, mean entry: {})".format(
matrix_name, mat_diff.max(), np.median(
mat_diff), np.mean(mat_diff),
np.max(np.absolute(A)), np.median(np.absolute(A)), np.mean(np.absolute(A))))
def compute_generalised_eigenproblem_matrices(sim, alpha=0.0, frequency_unit=1e9,
filename_mat_A=None, filename_mat_M=None,
check_hermitian=False, differentiate_H_numerically=True):
"""
XXX TODO: write me
"""
m_orig = sim.m
def effective_field_for_m(m, normalise=True):
if np.iscomplexobj(m):
raise NotImplementedError(
"XXX TODO: Implement the version for complex arrays!")
sim.set_m(m, normalise=normalise)
return sim.effective_field()
n = sim.mesh.num_vertices()
N = 3 * n # number of degrees of freedom
m0_array = sim.m.copy()
# this corresponds to the vector 'm0_flat' in Simlib
m0_3xn = m0_array.reshape(3, n)
m0_column_vector = m0_array.reshape(3, 1, n)
H0_array = effective_field_for_m(m0_array)
H0_3xn = H0_array.reshape(3, n)
h0 = H0_3xn[0] * m0_3xn[0] + H0_3xn[1] * m0_3xn[1] + H0_3xn[2] * m0_3xn[2]
logger.debug(
"Computing basis of the tangent space and transition matrices.")
Q, R, S, Mcross = compute_tangential_space_basis(m0_column_vector)
Qt = mf_transpose(Q).copy()
logger.debug("Q.shape: {} ({} MB)".format(Q.shape, Q.nbytes / 1024. ** 2))
def A_times_vector(v):
# A = H' v - h_0 v
assert v.shape == (3, 1, n)
v_array = v.view()
v_array.shape = (-1,)
# Compute H'(m_0)*v, i.e. the "directional derivative" of H at
# m_0 in the direction of v. Since H is linear in m (at least
# theoretically, although this is not quite true in the case
# of our demag computation), this is the same as H(v)!
if differentiate_H_numerically:
res = differentiate_fd4(effective_field_for_m, m0_array, v_array)
else:
res = effective_field_for_m(v_array, normalise=False)
res.shape = (3, n)
# Subtract h0 v
res[0] -= h0 * v[0, 0]
res[1] -= h0 * v[1, 0]
res[2] -= h0 * v[2, 0]
res.shape = (3, 1, n)
return res
df.tic()
logger.info("Assembling eigenproblem matrix.")
A = np.zeros((2 * n, 2 * n), dtype=complex)
logger.debug("Eigenproblem matrix A occupies {:.2f} MB of memory.".format(
A.nbytes / 1024. ** 2))
# Compute A
w = np.zeros(2 * n)
for i in xrange(2 * n):
if i % 50 == 0:
logger.debug(
"Processing row {}/{} (time taken so far: {:.2f} seconds)".format(i, 2 * n, df.toc()))
# Ensure that w is the i-th standard basis vector
w.shape = (2 * n,)
w[i - 1] = 0.0 # this will do no harm if i==0
w[i] = 1.0
w.shape = (2, 1, n)
Av = A_times_vector(mf_mult(Q, w))
A[:, i] = mf_mult(Qt, Av).reshape(-1)
# Multiply by (-gamma)/(2 pi U)
A[:, i] *= -sim.gamma / (2 * pi * frequency_unit)
# Compute B, which is -i Mcross 2 pi U / gamma
# B = np.zeros((2, n, 2, n), dtype=complex)
# for i in xrange(n):
# B[:, i, :, i] = Mcross[:, :, i]
# B[:, i, :, i] *= -1j
# B.shape = (2*n, 2*n)
M = scipy.sparse.linalg.LinearOperator(
(2 * n, 2 * n), M_times_w(Mcross, n, alpha), NotImplementedOp(), NotImplementedOp(), dtype=complex)
if check_hermitian:
# Sanity check: A and M should be Hermitian matrices
check_is_hermitian(A, "A")
#check_is_hermitian(M, "M")
if filename_mat_A != None:
dirname_mat_A = os.path.dirname(os.path.abspath(filename_mat_A))
if not os.path.exists(dirname_mat_A):
logger.debug(
"Creating directory '{}' as it does not exist.".format(dirname_mat_A))
os.makedirs(dirname_mat_A)
logger.info(
"Saving generalised eigenproblem matrix 'A' to file '{}'".format(filename_mat_A))
np.save(filename_mat_A, A)
if filename_mat_M != None:
dirname_mat_M = os.path.dirname(os.path.abspath(filename_mat_M))
if not os.path.exists(dirname_mat_M):
logger.debug(
"Creating directory '{}' as it does not exist.".format(dirname_mat_M))
os.makedirs(dirname_mat_M)
logger.info(
"Saving generalised eigenproblem matrix 'M' to file '{}'".format(filename_mat_M))
np.save(filename_mat_M, M)
# Restore the original magnetisation.
# XXX TODO: Is this method safe, or does it leave any trace of the
# temporary changes we did above?
sim.set_m(m_orig)
return A, M, Q, Qt
def compute_normal_modes(D, n_values=10, sigma=0., tol=1e-8, which='LM'):
logger.debug("Solving eigenproblem. This may take a while...")
df.tic()
omega, w = scipy.sparse.linalg.eigs(
D, n_values, which=which, sigma=0., tol=tol, return_eigenvectors=True)
logger.debug(
"Computing the eigenvalues and eigenvectors took {:.2f} seconds".format(df.toc()))
return omega, w
def compute_normal_modes_generalised(A, M, n_values=10, tol=1e-8, discard_negative_frequencies=False, sigma=None, which='LM',
v0=None, ncv=None, maxiter=None, Minv=None, OPinv=None, mode='normal'):
logger.debug("Solving eigenproblem. This may take a while...")
df.tic()
if discard_negative_frequencies:
n_values *= 2
# XXX TODO: The following call seems to increase memory consumption quite a bit. Why?!?
#
# We have to swap M and A when passing them to eigsh since the M matrix
# has to be positive definite for eigsh!
omega_inv, w = scipy.sparse.linalg.eigsh(M, k=n_values, M=A, which=which, tol=tol, return_eigenvectors=True, sigma=sigma,
v0=v0, ncv=ncv, maxiter=maxiter, Minv=Minv, OPinv=OPinv, mode=mode)
logger.debug(
"Computing the eigenvalues and eigenvectors took {:.2f} seconds".format(df.toc()))
# The true eigenfrequencies are given by 1/omega_inv because we swapped M
# and A above and thus computed the inverse eigenvalues.
omega = 1. / omega_inv
# Sanity check: the eigenfrequencies should occur in +/- pairs.
TOL = 1e-3
positive_freqs = filter(lambda x: x > 0, omega)
negative_freqs = filter(lambda x: x < 0, omega)
freq_pairs = izip(positive_freqs, negative_freqs)
if (n_values % 2 == 0 and len(positive_freqs) != len(negative_freqs)) or \
(n_values % 2 == 0 and len(positive_freqs) - len(negative_freqs) not in [0, 1]) or \
any([abs(x + y) > TOL for (x, y) in freq_pairs]):
logger.warning("The eigenfrequencies should occur in +/- pairs, but this "
"does not seem to be the case (with TOL={})! Please "
"double-check that the results make sense!".format(TOL))
# Find the indices that sort the frequency by absolute value,
# with the positive frequencies occurring before the negative ones (where.
sorted_indices = sorted(np.arange(len(omega)),
key=lambda i: (np.round(abs(omega[i]), decimals=4), -np.sign(omega[i]), abs(omega[i])))
if discard_negative_frequencies:
# Discard indices corresponding to negative frequencies
sorted_indices = filter(lambda i: omega[i] >= 0.0, sorted_indices)
omega = omega[sorted_indices]
# XXX TODO: can we somehow avoid copying the columns to save memory?!?
w = w[:, sorted_indices]
return omega, w
def export_normal_mode_animation(mesh, m0, freq, w, filename, num_cycles=1, num_snapshots_per_cycle=20, scaling=0.2, dm_only=False, save_h5=False):
"""
Save a number of vtk files of different snapshots of a given normal mode.
These can be imported and animated in Paraview.
*Arguments*
mesh : dolfin.Mesh
The mesh on which the magnetisation is defined.
m0 : numpy.array
The ground state of the magnetisation for which the normal mode was computed.
The size must be so that the array can be reshaped to size 3xN.
freq : float
The frequency of the normal mode.
w : numpy.array
The eigenvector representing the normal mode (as returned by `compute_eigenv`
or `compute_eigenv_generalised`).
filename : string
The filename of the exported animation files. Each individual frame will
have the same basename but will be given a suffix indicating the frame
number, too.
num_cycles : int
The number of cycles to be animated.
num_snapshots_per_cycle : int
The number of snapshot per cycle to be exported. Thus the total number of
exported frames is num_cycles * num_snapshots_per_cycle.
scaling : float
If `dm_only` is False, this determines the maximum size of the
oscillation (relative to the magnetisation vector) in the
visualisation. If `dm_only` is True, this has no effect.
dm_only : bool (optional)
If False (the default), plots `m0 + scaling*dm(t)`, where m0 is the
average magnetisation and dm(t) the (spatially varying)
oscillation corresponding to the frequency of the normal mode.
If True, only `dm(t)` is plotted.
"""
if freq.imag != 0 and abs(freq.imag) > 5e-3:
logger.warning("Frequency expected to be a real number. "
"Got: {}. This may lead to unexpected behaviour".format(freq))
freq = freq.real
#basename = os.path.basename(re.sub('\.vtk$', '', filename))
#dirname = os.path.dirname(filename)
# if not os.path.exists(dirname):
# print "Creating directory '{}' as it doesn't exist.".format(dirname)
# os.makedirs(dirname)
#mesh = comp.mesh
#mesh_shape = mesh.mesh_size
m0_array = m0.copy() # we assume that sim is relaxed!!
Q, R, S, Mcross = compute_tangential_space_basis(
m0_array.reshape(3, 1, -1))
Qt = mf_transpose(Q).copy()
n = mesh.num_vertices()
V = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
func = df.Function(V)
func.rename('m', 'magnetisation')
w_3d = mf_mult(Q, w.reshape((2, 1, n)))
w_flat = w_3d.reshape(-1)
phi = np.angle(w_flat) # relative phases of the oscillations
a = np.absolute(w_flat)
a = a / a.max() # normalised amplitudes of the oscillations
t_end = num_cycles * 2 * pi / freq
timesteps = np.linspace(
0, t_end, num_cycles * num_snapshots_per_cycle, endpoint=False)
m_osc = np.zeros(3 * n)
t0 = time()
f = df.File(filename, 'compressed')
field = Field(V, name='m')
for (i, t) in enumerate(timesteps):
logger.debug("Saving animation snapshot for timestep {} ({}/{})".format(t,
i, num_cycles * num_snapshots_per_cycle))
if dm_only is False:
m_osc = (
m0_array + scaling * a * np.cos(t * freq + phi)).reshape(-1)
else:
m_osc = (scaling * a * np.cos(t * freq + phi)).reshape(-1)
#save_vector_field(m_osc, os.path.join(dirname, basename + '_{:04d}.vtk'.format(i)))
func.vector().set_local(m_osc)
f << func
if save_h5:
field.set(func)
field.save_hdf5(filename[0:-4], i)
field.close_hdf5()
t1 = time()
logger.debug(
"Saving the data to file '{}' took {} seconds".format(filename, t1 - t0))
def get_colormap_from_name(cmap_name):
from matplotlib import cm
import custom_colormaps
colormaps = {'coolwarm': cm.coolwarm,
'cool': cm.cool,
'hot': cm.hot,
'afmhot': cm.afmhot,
'rainbow': cm.jet,
'hsv': cm.hsv,
'circular1': custom_colormaps.circular1,
'circular2': custom_colormaps.circular2,
'circular3': custom_colormaps.circular3,
'circular4': custom_colormaps.circular4,
'husl_99_75': custom_colormaps.husl_99_75,
'husl_99_70': custom_colormaps.husl_99_70,
'husl_99_65': custom_colormaps.husl_99_65,
}
try:
if cmap_name == 'rainbow':
logger.warning('The rainbow colormap is strongly discouraged for scientific visualizations, it is '
'highly recommended to choose a different colormap. See for example '
'http://medvis.org/2012/08/21/rainbow-colormaps-what-are-they-good-for-absolutely-nothing/ '
'for more information.')
return colormaps[cmap_name]
except KeyError:
raise ValueError("Unknown colormap name: '{}'. Allowed values: {}".format(
cmap_name, colormaps.keys()))
def extract_mesh_slice(mesh, slice_z):
coords = mesh.coordinates()
xmin = min(coords[:, 0])
xmax = max(coords[:, 0])
ymin = min(coords[:, 1])
ymax = max(coords[:, 1])
nx = int(1 * (xmax - xmin))
ny = int(1 * (ymax - ymin))
slice_mesh = embed3d(
df.RectangleMesh(df.Point(xmin, ymin), df.Point(xmax, ymax), nx, ny), z_embed=slice_z)
V = df.FunctionSpace(mesh, 'CG', 1)
f = df.Function(V)
V_slice = df.FunctionSpace(slice_mesh, 'CG', 1)
f_slice = df.Function(V_slice)
lg = df.LagrangeInterpolator()
def restrict_to_slice_mesh(a):
f.vector().set_local(a)
lg.interpolate(f_slice, f)
return f_slice.vector().array()
return slice_mesh, restrict_to_slice_mesh
def get_phaseplot_ticks_and_labels(num_ticks):
"""
Helper function to define nice ticks for phase plots which are
multiples of pi/2. Currently `num_ticks` must be either 3 or 5.
"""
if num_ticks == 3:
ticks = [-pi, 0, pi]
ticklabels = [u'-\u03C0', u'0', u'\u03C0']
elif num_ticks == 5:
ticks = [-pi, -pi / 2, 0, pi / 2, pi]
ticklabels = [u'-\u03C0', u'-\u03C0/2', u'0', u'\u03C0/2', u'\u03C0']
else:
raise ValueError(
"Number of phase plot ticks must be either 3 or 5. Got: {}".format(num_ticks))
return ticks, ticklabels
def plot_spatially_resolved_normal_mode(
mesh, m0, w, slice_z='z_max', components='xyz', label_components=True,
figure_title=None, yshift_title=0.0, plot_powers=True, plot_phases=True,
label_power='Power', label_phase='Phase', xticks=None, yticks=None,
num_power_colorbar_ticks=5, num_phase_colorbar_ticks=5,
colorbar_fmt='%.2e', cmap_powers='coolwarm', cmap_phases='circular4',
vmin_powers=0.0, show_axis_labels=True, show_axis_frames=True,
show_colorbars=True, figsize=None, outfilename=None, dpi=None):
"""
Plot the normal mode profile across a slice of the sample.
Remark: Due to a bug in matplotlib (see [1]), when saving the
`matplotlib.Figure` object returned from this function the title
and left annotations will likely be cut off. Therefore it is
recommended to save the plot by specifying the argument
`outfilename`.
[1] http://stackoverflow.com/questions/10101700/moving-matplotlib-legend-outside-of-the-axis-makes-it-cutoff-by-the-figure-box
*Arguments*
mesh:
The mesh of the simulation object for which the eigenmode was computed.
m0 : numpy.array
The ground state of the magnetisation for which the normal mode was computed.
The size must be so that the array can be reshaped to size 3xN.
w:
The eigenvector representing the normal mode (for example,
one of the columns of the second return value of
`compute_normal_modes_generalised`).
slice_z:
The z-value of the mesh slice which will be plotted. This can be either
'z_min' or 'z_max' (which correspond to the bottom/top layer of the mesh)
or a numerical value. Note that the mesh must have a layer of nodes with
this z-coordinate, otherwise the plotting routine will fail.
num_power_colorbar_ticks:
The number of tick labels for the power colorbars. Currently
this must be either 3 or 5 (default: 5).
num_phase_colorbar_ticks:
The number of tick labels for the phase colorbars. Currently
this must be either 3 or 5 (default: 5).
outfilename:
If given, the plot will be saved to a file with this name. Any
missing directory components will be created first. Default: None.
dpi:
The resolution of the saved plot (ignored if `outfilename` is None).
*Returns*
The `matplotlib.Figure` containing the plot.
"""
import matplotlib.pyplot as plt
import matplotlib.tri as tri
from matplotlib.ticker import FormatStrFormatter
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})
coords = mesh.coordinates()
if slice_z == 'z_min':
slice_z = min(coords[:, 2])
elif slice_z == 'z_max':
slice_z = max(coords[:, 2])
slice_mesh, restrict_to_submesh = extract_mesh_slice(mesh, slice_z)
m0_array = m0.copy()
Q, R, S, Mcross = compute_tangential_space_basis(
m0_array.reshape(3, 1, -1))
Qt = mf_transpose(Q).copy()
n = mesh.num_vertices()
w_3d = mf_mult(Q, w.reshape((2, 1, n)))
w_x = w_3d[0, 0, :]
w_y = w_3d[1, 0, :]
w_z = w_3d[2, 0, :]
######################################################################
slice_coords = slice_mesh.coordinates()
xvals = slice_coords[:, 0]
yvals = slice_coords[:, 1]
# We use the mesh triangulation provided by dolfin in case the
# mesh has multiple disconnected regions (in which case matplotlib
# would connect them).
mesh_triang = tri.Triangulation(xvals, yvals, slice_mesh.cells())
# Determine the number of rows (<=2) and columns (<=3) in the plot
num_rows = 0
if plot_powers:
num_rows += 1
if plot_phases:
num_rows += 1
if num_rows == 0:
raise ValueError(
"At least one of the arguments `plot_powers`, `plot_phases` must be True.")
num_columns = len(components)
def plot_mode_profile(ax, a, title=None, vmin=None, vmax=None, cmap=None, cticks=None, cticklabels=None):
ax.set_aspect('equal')
vals = restrict_to_submesh(a)
trimesh = ax.tripcolor(mesh_triang, vals, shading='gouraud', cmap=cmap)
ax.set_title(title)
if show_colorbars:
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", "5%", pad="3%")
if vmin is None:
vmin = min(vals)
if vmax is None:
vmax = max(vals)
trimesh.set_clim(vmin=vmin, vmax=vmax)
cbar = plt.colorbar(trimesh, cax=cax, format=FormatStrFormatter(colorbar_fmt),
ticks=cticks)
if cticklabels != None:
cbar.ax.set_yticklabels(cticklabels)
if not show_axis_labels:
ax.set_xticks([])
ax.set_yticks([])
if not show_axis_frames:
ax.axis('off')
fig = plt.figure(figsize=figsize)
if isinstance(cmap_powers, str):
cmap_powers = get_colormap_from_name(cmap_powers)
if isinstance(cmap_phases, str):
cmap_phases = get_colormap_from_name(cmap_phases)
powers = {'x': np.absolute(w_x) ** 2,
'y': np.absolute(w_y) ** 2,
'z': np.absolute(w_z) ** 2}
phases = {'x': np.angle(w_x),
'y': np.angle(w_y),
'z': np.angle(w_z)}
def set_xyticks(ax):
if xticks != None:
ax.set_xticks(xticks)
if yticks != None:
ax.set_yticks(yticks)
cnt = 1
if plot_powers:
cticklabels = None
for comp in components:
ax = fig.add_subplot(num_rows, num_columns, cnt)
if num_power_colorbar_ticks != None:
if vmin_powers != None:
minval = vmin_powers
else:
minval = powers[comp].min()
cticks = np.linspace(
minval, powers[comp].max(), num_power_colorbar_ticks)
else:
cticks = None
comp_title = 'm_{}'.format(comp) if label_components else ''
plot_mode_profile(ax, powers[comp], title=comp_title,
cticks=cticks, cticklabels=cticklabels,
vmin=vmin_powers, cmap=cmap_powers)
set_xyticks(ax)
cnt += 1
if plot_phases:
cticks, cticklabels = get_phaseplot_ticks_and_labels(
num_phase_colorbar_ticks)
for comp in components:
ax = fig.add_subplot(num_rows, num_columns, cnt)
if label_components and not plot_powers:
comp_title = 'm_{}'.format(comp)
else:
comp_title = ''
plot_mode_profile(ax, phases[comp], title=comp_title,
cticks=cticks, cticklabels=cticklabels,
vmin=-pi, vmax=+pi,
cmap=cmap_phases)
set_xyticks(ax)
cnt += 1
bbox_extra_artists = []
if figure_title != None:
txt = plt.text(0.5, 1.0 + yshift_title, figure_title,
horizontalalignment='center',
fontsize=20,
transform=fig.transFigure)
bbox_extra_artists.append(txt)
num_axes = len(fig.axes)
ax_annotate_powers = fig.axes[0]
ax_annotate_phases = fig.axes[(num_axes // 2) if plot_powers else 0]
if plot_powers:
txt_power = plt.text(-0.2, 0.5, label_power,
fontsize=16,
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
# transform=fig.transFigure)
transform=ax_annotate_powers.transAxes)
bbox_extra_artists.append(txt_power)
#
#ax_topleft.text(0, 0, label_power, ha='left', va='center', rotation=90)
#
#from matplotlib.offsetbox import AnchoredOffsetbox, TextArea
#box = TextArea(label_power, textprops=dict(color="k", fontsize=20))
# anchored_box = AnchoredOffsetbox(loc=3,
# child=box, pad=0.,
# frameon=False,
# bbox_to_anchor=(-0.1, 0.5),
# bbox_transform=ax.transAxes,
# borderpad=0.,
# )
# ax_topleft.add_artist(anchored_box)
# bbox_extra_artists.append(anchored_box)
if plot_phases:
txt_phase = plt.text(-0.2, 0.5, label_phase,
fontsize=16,
horizontalalignment='right',
verticalalignment='center',
rotation='vertical',
# transform=fig.transFigure)
transform=ax_annotate_phases.transAxes)
bbox_extra_artists.append(txt_phase)
if outfilename != None:
helpers.create_missing_directory_components(outfilename)
fig.savefig(
outfilename, bbox_extra_artists=bbox_extra_artists, bbox_inches='tight', dpi=dpi)
return fig
| 34,945 | 36.216187 | 147 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/deprecated/normal_modes_deprecated_test.py
|
from finmag.util.mesh_templates import Box, Sphere, Nanodisk, EllipticalNanodisk
from finmag.util.meshes import mesh_info, plot_mesh_with_paraview
from finmag.normal_modes.deprecated.normal_modes_deprecated import *
from finmag import example
from finmag import sim_with, normal_mode_simulation
from math import pi
import logging
import pytest
import matplotlib.pyplot as plt
logger = logging.getLogger("finmag")
@pytest.mark.slow
def test_check_Kittel_mode_for_single_sphere(tmpdir, debug=False):
"""
Compute the eigenmodes of a perfect sphere and check that the
frequency of the base mode equals the analytical value from the
Kittel equation (see Charles Kittel, "Introduction to solid state
physics", 7th edition, Ch. 16, p.505):
omega_0 = gamma * B_0
Here omega_0 is the angular frequency, so the actual frequency is
equal to omega_0 / (2*pi).
"""
os.chdir(str(tmpdir))
sphere = Sphere(r=11)
mesh = sphere.create_mesh(maxh=2.0)
print "[DDD] mesh: {}".format(mesh)
print mesh_info(mesh)
if debug:
plot_mesh_with_paraview(mesh, outfile='mesh_sphere.png')
H_z = 4.42e5 # slightly odd value to make the test a bit more reliable
frequency_unit = 1e9
sim = sim_with(mesh, Ms=1e6, m_init=[
0, 0, 1], A=13e-12, H_ext=[0, 0, H_z], unit_length=1e-9, demag_solver='FK')
sim.relax()
A, M, _, _ = compute_generalised_eigenproblem_matrices(
sim, alpha=0.0, frequency_unit=1e9)
RTOL = 1e-3
n_values = 2
n_values_export = 0
omega, w = compute_normal_modes_generalised(
A, M, n_values=n_values, discard_negative_frequencies=False)
assert(len(omega) == n_values)
# Check that the frequency of the base mode equals the analytical value from the Kittel equation
# (see Charles Kittel, "Introduction to solid state physics", 7th edition, Ch. 16, p.505):
#
# omega_0 = gamma * B_0
#
# The frequency is equal to omega_0 / (2*pi).
#
freq_expected = sim.gamma * H_z / (2 * pi * frequency_unit)
assert(np.allclose(omega[0], +freq_expected, atol=0, rtol=RTOL))
assert(np.allclose(omega[1], -freq_expected, atol=0, rtol=RTOL))
logger.debug("Computed eigenfrequencies: {}".format(omega))
logger.debug(
"Expected frequency of the Kittel mode: {}".format(freq_expected))
# Perform the same test when negative frequencies are discarded
omega_positive, _ = compute_normal_modes_generalised(
A, M, n_values=n_values, discard_negative_frequencies=True)
logger.debug("[DDD] omega_positive: {}".format(omega_positive))
assert(len(omega_positive) == n_values)
assert(np.allclose(omega_positive[0], freq_expected, atol=0, rtol=RTOL))
# Ensure that the frequencies are all positive and sorted by absolute value
assert((np.array(omega_positive) > 0).all())
assert(np.allclose(omega_positive, sorted(omega_positive, key=abs)))
omega_positive_first_half = omega_positive[:(n_values // 2)]
assert(np.allclose(sorted(np.concatenate([omega_positive_first_half, -omega_positive_first_half])),
sorted(omega)))
# Export normal mode animations for debugging
for i in xrange(n_values_export):
freq = omega_positive[i]
export_normal_mode_animation(
sim, freq, w[i], filename='normal_mode_{:02d}__{:.3f}_GHz.pvd'.format(i, freq))
##
# Perform the same test as above but without demag, wich should improve the accuracy.
##
sim = sim_with(mesh, Ms=1e6, m_init=[
0, 0, 1], A=13e-12, H_ext=[0, 0, H_z], unit_length=1e-9, demag_solver=None)
sim.relax()
A, M, _, _ = compute_generalised_eigenproblem_matrices(
sim, alpha=0.0, frequency_unit=1e9)
RTOL = 1e-9
omega, _ = compute_normal_modes_generalised(
A, M, n_values=1, discard_negative_frequencies=True)
logger.debug("Computed eigenfrequencies (without demag): {}".format(omega))
logger.debug(
"Expected frequency of the Kittel mode: {}".format(freq_expected))
assert(np.allclose(omega[0], freq_expected, atol=0, rtol=RTOL))
# The following test doesn't make sense any more with the new
# interface. I'm only keeping it here to remind me that we should
# perhaps have a similar test in the new code. -- Max, 18.3.2014
@pytest.mark.skipif("True")
def test_passing_scipy_eigsh_parameters(tmpdir):
os.chdir(str(tmpdir))
sim = example.normal_modes.disk()
omega1, _, _, _ = sim.compute_normal_modes(n_values=4, tol=0)
omega2, _, _, _ = sim.compute_normal_modes(
n_values=4, tol=0, ncv=20, maxiter=2000, sigma=0.0, which='SM')
logger.debug(
"Note: the following results are not meant to coincide! Their purpose is just to test passing arguments to scipy.sparse.linalg.eigsh")
logger.debug("Computed eigenfrequencies #1: {}".format(omega1))
logger.debug("Computed eigenfrequencies #2: {}".format(omega2))
@pytest.mark.slow
def test_plot_spatially_resolved_normal_mode(tmpdir):
os.chdir(str(tmpdir))
d = 60
h = 2
sep = 5
maxh = 10.0
# Create a mesh consisting of two separate regions to check
# whether matplotlib can handle the space in between them
# correctly (previously it would connect the regions).
center1 = (-0.5 * (d + sep), 0, 0)
center2 = (+0.5 * (d + sep), 0, 0)
nanodisk1 = Nanodisk(d, h, center=center1, name='nanodisk1')
nanodisk2 = Nanodisk(d, h, center=center2, name='nanodisk2')
nanodisks = nanodisk1 + nanodisk2
mesh = nanodisks.create_mesh(maxh, directory='meshes')
# Material parameters for Permalloy
Ms = 8e5
A = 13e-12
m_init = [1, 0, 0]
alpha_relax = 1.0
H_ext_relax = [1e4, 0, 0]
sim = normal_mode_simulation(
mesh, Ms, m_init, alpha=alpha_relax, unit_length=1e-9, A=A, H_ext=H_ext_relax)
sim.relax()
mesh = sim.mesh
m0 = sim.m
N = 3
omega, eigenvecs, rel_errors = sim.compute_normal_modes(n_values=N)
logger.debug("[DDD] Computed {} eigenvalues and {} eigenvectors.".format(
len(omega), len(eigenvecs[0])))
for i in xrange(N):
#sim.export_normal_mode_animation(i, filename='animations/normal_mode_{:02d}/normal_mode_{:02d}.pvd'.format(i, i))
w = eigenvecs[i]
fig = plot_spatially_resolved_normal_mode(mesh, m0, w, slice_z='z_max', components='xyz',
figure_title='Eigenmodes', yshift_title=0.0,
plot_powers=True, plot_phases=True,
show_axis_labels=True, show_colorbars=True,
show_axis_frames=True, figsize=(
12, 4),
outfilename='normal_mode_profile_{:02d}_v1.png'.format(
i),
dpi=300)
# Different combination of parameters
fig = plot_spatially_resolved_normal_mode(mesh, m0, w, slice_z='z_min', components='xz',
plot_powers=True, plot_phases=False,
show_axis_frames=False, show_axis_labels=False,
show_colorbars=False, figsize=(
12, 4),
outfilename='normal_mode_profile_{:02d}_v2.png'.format(i))
with pytest.raises(ValueError):
plot_spatially_resolved_normal_mode(
mesh, m0, w, plot_powers=False, plot_phases=False)
@pytest.mark.slow
def test_plot_spatially_resolved_normal_mode2(tmpdir):
os.chdir(str(tmpdir))
sim = example.normal_modes.disk(relaxed=True)
sim.compute_normal_modes(n_values=3)
sim.plot_spatially_resolved_normal_mode(0, outfilename='normal_mode_00.png')
sim.plot_spatially_resolved_normal_mode(1, slice_z='z_min', components='xz',
figure_title='Title', yshift_title=0.05,
plot_powers=True, plot_phases=False, num_phase_colorbar_ticks=3,
cmap_powers=plt.cm.jet, cmap_phases=plt.cm.hsv, vmin_powers=None,
show_axis_labels=True, show_axis_frames=True, show_colorbars=True,
figsize=(5, 3), outfilename='normal_mode_01.png', dpi=200)
assert(os.path.exists('normal_mode_00.png'))
assert(os.path.exists('normal_mode_01.png'))
@pytest.mark.slow
@pytest.mark.xfail(reason='dolfin 1.5')
def test_plot_spatially_resolved_normal_mode_in_region(tmpdir):
os.chdir(str(tmpdir))
disk1 = Nanodisk(d=60, h=5, center=(-70, 0, 0), name="sphere1")
disk2 = EllipticalNanodisk(
d1=80, d2=40, h=5, center=(+90, 0, 0), name="sphere2")
mesh = (disk1 + disk2).create_mesh(maxh=10.0)
def region_fun(pt):
if pt[0] < 0:
return "disk1"
else:
return "disk2"
sim = normal_mode_simulation(
mesh, Ms=8e5, m_init=[1, 0, 0], unit_length=1e-9, A=13e-12, H_ext=[1e4, 0, 0])
sim.mark_regions(region_fun)
sim.relax()
sim.compute_normal_modes(n_values=3)
sim.plot_spatially_resolved_normal_mode(
0, outfilename='normal_mode_00.png', use_fenicstools=False)
sim.plot_spatially_resolved_normal_mode(
0, outfilename='normal_mode_00_disk1.png', region="disk1", use_fenicstools=False)
sim.plot_spatially_resolved_normal_mode(
0, outfilename='normal_mode_00_disk2.png', region="disk2", use_fenicstools=False)
assert(os.path.exists('normal_mode_00.png'))
assert(os.path.exists('normal_mode_00_disk1.png'))
assert(os.path.exists('normal_mode_00_disk2.png'))
def test_is_hermitian():
"""
Simple test to check if the helper function `is_hermitian` tests
correctly whether a matrix is Hermitian.
"""
A = np.array([[1, 2j, 3 + 4j], [-2j, 1.3, 5 - 6j], [3 - 4j, 5 + 6j, 1.7]])
B = np.array(
[[1, 2j, 3 + 4.0001j], [-2j, 1.3, 5 - 6j], [3 - 4j, 5 + 6j, 1.7]])
assert(is_hermitian(A))
assert(not is_hermitian(B))
assert(is_hermitian(B, atol=1e-2))
if __name__ == '__main__':
test_compute_generalised_eigenproblem_matrices_single_sphere('.')
| 10,328 | 39.347656 | 142 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/deprecated/__init__.py
|
# This file is needed just os that python recognises
# the contents as a module, but we're not actually
# exposing any names here.
| 131 | 32 | 52 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/deprecated/generate_custom_colormaps.py
|
import numpy as np
import matplotlib.colors as mcolors
import logging
import textwrap
import sys
from math import pi, cos, sin
logger = logging.getLogger('finmag')
try:
import husl
except:
logger.error(
"Missing python package: 'husl'. Please install it using 'sudo pip install husl'.")
sys.exit()
try:
from colormath.color_conversions import convert_color
from colormath.color_objects import LabColor, sRGBColor
except:
logger.error(
"Missing python package: 'colormath'. Please install it using 'sudo pip install colormath'.")
sys.exit()
# The following values are derived from a circular path in the CIELab [1]
# color space. The path is defined as follows:
#
# t --> center + radius * [0, cos(t), sin(t)]
#
# (where t ranges from 0 to 2*pi).
#
# This path was sampled at 256 equidistant values of t and the resulting
# CIELab coordinats were converted back into RGB coordinates, resulting in
# the values below.
#
# The center and radius need to be chosen so that the converted coordinates
# all represent valid RGB values.
#
#
# [1] http://dba.med.sc.edu/price/irf/Adobe_tg/models/cielab.html
def rgb2lab(pt):
return convert_color(sRGBColor(pt[0], pt[1], pt[2]), LabColor).get_value_tuple()
def lab2rgb(pt):
return convert_color(LabColor(pt[0], pt[1], pt[2]), sRGBColor).get_value_tuple()
def circular_colormap(center, radius, normal_vector=[1, 0, 0], offset=0):
"""
Define a perceptually linear, circular colormap defined through a
circular path in the CIELab [1] color space. The path is defined
by the arguments `center` and `radius` via the mapping:
t --> center + radius * [0, cos(t + offset), sin(t + offset)]
where t ranges from 0 to 2*pi. The argument `offset` can be used to
shift the colors along the colorscale.
It is up to the user to choose values of `center` and `radius` so
that the entire path lies within the range representing valid RGB
values.
[1] http://dba.med.sc.edu/price/irf/Adobe_tg/models/cielab.html
"""
center = np.asarray(center)
n = np.asarray(normal_vector)
n = n / np.linalg.norm(n)
# arbitrary vector to make sure that e1 below is unlikely to be zero
arbitrary_direction = np.array([0.28, 0.33, 0.71])
# Define two orthogonal vectors e1, e2 lying in the plane orthogonal to
# `normal_vector`.
e1 = np.cross(n, arbitrary_direction)
e2 = np.cross(n, e1)
tvals = np.linspace(0, 2 * pi, 256, endpoint=False)
path_vals = [center + radius *
cos(t + offset) * e1 + radius * sin(t + offset) * e2 for t in tvals]
cmap_vals = np.array([lab2rgb(pt) for pt in path_vals])
cmap = mcolors.ListedColormap(cmap_vals)
return cmap
def linear_colormap(rgb1, rgb2):
"""
Define a perceptually linear colormap defined through a line in the
CIELab [1] color space.
[1] http://dba.med.sc.edu/price/irf/Adobe_tg/models/cielab.html
"""
pt1 = np.array(rgb2lab(rgb1))
pt2 = np.array(rgb2lab(rgb2))
tvals = np.linspace(0, 1, 256)
path_vals = [(1 - t) * pt1 + t * pt2 for t in tvals]
cmap_vals = np.array([lab2rgb(pt) for pt in path_vals])
cmap = mcolors.ListedColormap(cmap_vals)
return cmap
def husl_colormap(saturation, lightness):
"""
Generate a colormap of linearly varying hue while keeping saturation and lightness fixed.
See here for the HUSL color space: http://www.boronine.com/husl/
"""
hvals = np.linspace(0, 360, 256, endpoint=False)
cmap_vals = np.array(
[husl.husl_to_rgb(h, saturation, lightness) for h in hvals])
cmap = mcolors.ListedColormap(cmap_vals)
return cmap
if __name__ == '__main__':
with open('custom_colormaps.py', 'w') as f:
f.write(textwrap.dedent("""
#################################################################
### ###
### DO NOT EDIT THIS FILE!!! ###
### ###
### It was autogenerated from 'generate_custom_colormaps.py'. ###
### ###
#################################################################
import matplotlib.colors as mcolors
from numpy import array
"""))
def write_colormap(name, cmap):
f.write("{}_vals = \\\n{}\n".format(name, repr(cmap.colors)))
f.write(
"{} = mcolors.ListedColormap({}_vals)\n\n\n".format(name, name))
# Define a few colormaps with increasingly lighter colors
write_colormap(
'circular1', circular_colormap(center=[50, 25, 5], radius=52))
write_colormap(
'circular2', circular_colormap(center=[60, 15, 13], radius=51))
write_colormap(
'circular3', circular_colormap(center=[65, 5, 18], radius=49))
write_colormap('circular4', circular_colormap(
center=[60, 6, 24], radius=51, normal_vector=[3, 1, -1]))
write_colormap(
'husl_99_75', husl_colormap(saturation=99, lightness=75))
write_colormap(
'husl_99_70', husl_colormap(saturation=99, lightness=70))
write_colormap(
'husl_99_65', husl_colormap(saturation=99, lightness=65))
| 5,441 | 33.443038 | 101 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/eigensolvers_test.py
|
from __future__ import division
import pytest
import numpy as np
import itertools
from eigensolvers import *
from eigenproblems import *
from helpers import normalise_rows
np.set_printoptions(precision=3)
# NOTE: Don't change this list without adapting the "known_failures" below!
sample_eigensolvers = [
ScipyLinalgEig(),
ScipyLinalgEigh(),
ScipySparseLinalgEigs(sigma=0.0, which='LM', num=10),
ScipySparseLinalgEigsh(sigma=0.0, which='LM', num=10),
SLEPcEigensolver(problem_type='GNHEP', method_type='KRYLOVSCHUR',
which='SMALLEST_MAGNITUDE'),
]
def test_str():
"""
Test the __str__ method for each of the `sample_eigensolvers`.
"""
assert(set([str(s) for s in sample_eigensolvers]) ==
set(["<ScipyLinalgEig>",
"<ScipyLinalgEigh>",
"<ScipySparseLinalgEigs: sigma=0.0, which='LM', num=10>",
"<ScipySparseLinalgEigsh: sigma=0.0, which='LM', num=10>",
"<SLEPcEigensolver: GNHEP, KRYLOVSCHUR, SMALLEST_MAGNITUDE, num=6, tol=1e-12, maxit=100>",
]))
def test_scipy_dense_solvers_num_argument():
"""
By default, the Scipy dense solvers compute all eigenpairs of the
eigenproblem. We can limit the number of solutions returned by
specifying the 'num' argument, either directly when instantiating
the solver or when calling the eigenproblem.solve() method. This
test checks that the expected number of solutions is returned in
all cases.
"""
diagproblem = DiagonalEigenproblem()
# Dense solvers should yield all solutions by default
solver1 = ScipyLinalgEig()
solver2 = ScipyLinalgEigh()
omega1, w1, _ = diagproblem.solve(solver1, N=10, dtype=float)
omega2, w2, _ = diagproblem.solve(solver2, N=10, dtype=float)
assert(len(omega1) == 10)
assert(len(omega2) == 10)
assert(w1.shape == (10, 10))
assert(w2.shape == (10, 10))
# By initialising them with the 'num' argument they should only
# yield the first 'num' solutions.
solver3 = ScipyLinalgEig(num=5)
solver4 = ScipyLinalgEigh(num=3)
omega3, w3, _ = diagproblem.solve(solver3, N=10, dtype=float)
omega4, w4, _ = diagproblem.solve(solver4, N=10, dtype=float)
assert(len(omega3) == 5)
assert(len(omega4) == 3)
assert(w3.shape == (5, 10))
assert(w4.shape == (3, 10))
# We can also provide the 'num' argument in the solve() method
# directly. If provided, this argument should be used. Otherwise
# The fallback value from the solver initialisation is used.
solver5 = ScipyLinalgEig(num=7)
solver6 = ScipyLinalgEig()
solver7 = ScipyLinalgEigh(num=3)
omega5, w5, _ = diagproblem.solve(solver5, N=10, num=5, dtype=float)
omega6, w6, _ = diagproblem.solve(solver6, N=10, num=8, dtype=float)
omega7, w7, _ = diagproblem.solve(solver7, N=10, num=6, dtype=float)
omega8, w8, _ = diagproblem.solve(solver7, N=10, num=None, dtype=float)
assert(len(omega5) == 5)
assert(len(omega6) == 8)
assert(len(omega7) == 6)
assert(len(omega8) == 3)
assert(w5.shape == (5, 10))
assert(w6.shape == (8, 10))
assert(w7.shape == (6, 10))
assert(w8.shape == (3, 10))
def test_scipy_sparse_solvers_num_argument():
"""
We can limit the number of solutions returned by the sparse
solvers specifying the 'num' argument, either directly when
instantiating the solver or when calling the eigenproblem.solve()
method. This test checks that the expected number of solutions is
returned in all cases.
"""
diagproblem = DiagonalEigenproblem()
# By initialising them with the 'num' argument they should only
# yield the first 'num' solutions.
solver1 = ScipySparseLinalgEigs(sigma=0.0, which='LM', num=4)
solver2 = ScipySparseLinalgEigsh(sigma=0.0, which='LM', num=3)
omega1, w1, _ = diagproblem.solve(solver1, N=10, dtype=float)
omega2, w2, _ = diagproblem.solve(solver2, N=10, dtype=float)
assert(len(omega1) == 4)
assert(len(omega2) == 3)
assert(w1.shape == (4, 10))
assert(w2.shape == (3, 10))
# We can also provide the 'num' argument in the solve() method
# directly. If provided, this argument should be used. Otherwise
# The fallback value from the solver initialisation is used.
solver3 = ScipySparseLinalgEigs(sigma=0.0, which='LM', num=7)
solver4 = ScipySparseLinalgEigsh(sigma=0.0, which='LM', num=3)
omega3, w3, _ = diagproblem.solve(solver3, N=10, num=5, dtype=float)
omega4, w4, _ = diagproblem.solve(solver4, N=10, num=6, dtype=float)
omega5, w5, _ = diagproblem.solve(solver4, N=10, num=None, dtype=float)
assert(len(omega3) == 5)
assert(len(omega4) == 6)
assert(len(omega5) == 3)
assert(w3.shape == (5, 10))
assert(w4.shape == (6, 10))
assert(w5.shape == (3, 10))
@pytest.mark.parametrize("dtype, solver",
itertools.product([float, complex],
sample_eigensolvers))
def test_compute_eigenvalues_of_diagonal_matrix(dtype, solver):
N = 60
diagvals = np.arange(1, N + 1, dtype=dtype)
A = np.diag(diagvals)
print("[DDD] Testing eigensolver {} with diagonal matrix of size "
"N={}, dtype={}".format(solver, N, dtype))
omega, w, _ = solver.solve_eigenproblem(A)
print("[DDD] omega: {}".format(omega))
# Compute expected eigenvalues and eigenvectors
k = len(omega)
omega_ref = diagvals[:k]
w_ref = np.eye(N)[:k]
assert(np.allclose(omega, omega_ref))
assert(np.allclose(abs(normalise_rows(w)), w_ref))
@pytest.mark.parametrize("solver", [ScipyLinalgEig(), ScipyLinalgEigh()])
def test_scipy_dense_solvers_accept_sparse_argument(solver):
N = 10
A, _ = DiagonalEigenproblem().instantiate(N=N, dtype=float)
A_LinearOperator = LinearOperator((N, N), matvec=lambda v: np.dot(A, v))
A_petsc = as_petsc_matrix(A)
omega1, w1, _ = solver.solve_eigenproblem(A)
omega2, w2, _ = solver.solve_eigenproblem(A_LinearOperator)
omega3, w3, _ = solver.solve_eigenproblem(A_petsc)
assert(np.allclose(omega1, omega2))
assert(np.allclose(omega1, omega3))
assert(np.allclose(w1, w2))
assert(np.allclose(w1, w3))
# The following test illustrates a strange failure of the scipy
# sparse solver to compute the correct eigenvalues for a diagonal
# matrix. The largest computed eigenvalue is 11 instead of the
# expected value 10. However, I can't reproduce this at the moment
# so the test is commented out.
# #
# def test_weird_wrong_computation():
# solver = ScipySparseLinalgEigsh(sigma=0.0, which='LM', num=10)
# solver = sample_eigensolvers[2]
# diagproblem = DiagonalEigenproblem()
# omega, _ = diagproblem.solve(solver, N=50, dtype=float)
# omega_wrong = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
# assert(np.allclose(omega, omega_wrong))
# We cannot use a Hermitian eigensolver to solve a non-Hermitian problem
def solver_and_problem_are_compatible(solver, eigenproblem):
return not(solver.is_hermitian() and not eigenproblem.is_hermitian())
# Create a set of fixtures where eigensolvers and compatible
# eigenproblems are paired.
fixtures = itertools.product(sample_eigensolvers, available_eigenproblems)
# TODO: Currently we simply skip these and call pytest.xfail directly.
# It would be better to actually execute them and wait for them
# to fail, so that the failures are confirmed. However, this
# might take a long time (due to missing convergence), so we're
# not doing it at the moment. Perhaps we can mark the tests as
# 'long_running' and skip them during normal runs?
# Note: On the other hand, some of these pass on certain computers and
# fail on others. So it might be better to keep this as 'blacklist',
# and document the known failures in the test 'test_document_failures'
# below.
known_failures = \
[ # The first case fails on omicron but passes on hathor...
(sample_eigensolvers[2], # ScipySparseLinalgEigs
available_eigenproblems[2], # Nanostrip1d
200,
float),
(sample_eigensolvers[4], # SLEPc
available_eigenproblems[1], # RingGraphLaplace
101,
float),
(sample_eigensolvers[4], # SLEPc
available_eigenproblems[2], # Nanostrip1d
200,
float),
(sample_eigensolvers[4], # SLEPc
available_eigenproblems[2], # Nanostrip1d
200,
complex),
]
@pytest.mark.parametrize("solver, eigenproblem", fixtures)
def test_eigensolvers(solver, eigenproblem):
print("\n[DDD] solver: {}".format(solver))
print("[DDD] eigenproblem: {}".format(eigenproblem))
for N in [50, 101, 200]:
for dtype in [float, complex]:
print("[DDD] N={}, dtype={}".format(N, dtype))
if (solver, eigenproblem, N, dtype) in known_failures:
pytest.xfail("Known failure: {}, {}, {}, {}".format(
solver, eigenproblem, N, dtype))
if not solver_and_problem_are_compatible(solver, eigenproblem):
with pytest.raises(ValueError):
eigenproblem.solve(solver, N, dtype=dtype, num=40)
continue
# Nanostrip1d can only solve problems of even size
if not iseven(N) and isinstance(eigenproblem, Nanostrip1dEigenproblemFinmag):
with pytest.raises(ValueError):
eigenproblem.solve(solver, N, dtype=dtype, num=40)
continue
omega, w, _ = eigenproblem.solve(solver, N, dtype=dtype, num=40)
print "[DDD] len(omega): {}".format(len(omega))
try:
if isinstance(eigenproblem, Nanostrip1dEigenproblemFinmag):
# The Nanostrip1d seems to be quite ill-behaved
# with the sparse solvers.
tol_eigval = 0.1
elif isinstance(solver, ScipySparseSolver):
# The sparse solvers seem to be less accurate, so
# we use a less strict tolerance.
tol_eigval = 1e-3
elif isinstance(solver, SLEPcEigensolver):
tol_eigval = 1e-13
else:
tol_eigval = 1e-14
eigenproblem.verify_eigenpairs_numerically(zip(omega, w))
eigenproblem.verify_eigenpairs_analytically(
zip(omega, w), tol_eigval=tol_eigval)
except NotImplementedError:
pytest.xfail("Analytical solution not implemented for "
"solver {}".format(solver))
except ValueError:
# Here we capture a spurious failure of one of the tests which
# only occurs on some computers (and not every time).
if (solver, eigenproblem, N, dtype) in [
(sample_eigensolvers[2], # ScipySparseLinalgEigs
available_eigenproblems[2], # Nanostrip1d
50,
float)
]:
pytest.xfail(
"Spurious test failure. This passes on most computers "
"but sometimes fails, which it just did. Ignoring for now")
# XXX TODO: The following test illustrates a spurious problem for N=100, where
# the test hangs because the iterations don't finish. We also get the
# following RuntimeWarning:
#
# /usr/local/lib/python2.7/dist-packages/scipy/linalg/decomp_lu.py:71:
# RuntimeWarning: Diagonal number 100 is exactly zero. Singular matrix.
#
# We skip the test but keep it to illustrate the problem
@pytest.mark.skipif('True')
def test_strange_degenerate_case():
eigenproblem = RingGraphLaplaceEigenproblem()
solver = ScipySparseLinalgEigs(sigma=0.0, which='LM', num=10)
omega, w, _ = eigenproblem.solve(solver, N=100, dtype=float)
def test_document_failures():
"""
This test documents some cases where the eigensolvers fail. This
is valuable if I want to write these results up later.
"""
# The RingGraphLaplaceEigenproblem seems to be very ill-conditioned.
# Strangely, some values of N seem to be more susceptible to failures
# than others...
# TODO: This is duplicated in known_failures, but there it's not currently
# executed, so we run it here instead.
solver = SLEPcEigensolver(problem_type='GNHEP', method_type='KRYLOVSCHUR',
which='SMALLEST_MAGNITUDE')
eigenproblem = RingGraphLaplaceEigenproblem()
N = 101
num = 40
for dtype in [float, complex]:
with pytest.raises(RuntimeError):
eigenproblem.solve(solver, N, dtype=dtype, num=num)
# It seems that this SLEPcEigensolver can't cope with problems where N is
# too large, so it doesn't converge.
solver = SLEPcEigensolver(problem_type='GNHEP', method_type='KRYLOVSCHUR',
which='SMALLEST_MAGNITUDE')
eigenproblem = Nanostrip1dEigenproblemFinmag(13e-12, 8e5, 0, 100)
N = 300
num = 40
for dtype in [float, complex]:
with pytest.raises(RuntimeError):
eigenproblem.solve(solver, N, dtype=dtype, num=num)
| 13,348 | 40.073846 | 106 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/custom_exceptions.py
|
class EigenproblemVerifyError(Exception):
pass
| 51 | 16.333333 | 41 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/eigensolvers.py
|
from __future__ import division
import numpy as np
import dolfin as df
import scipy.linalg
import scipy.sparse.linalg
import logging
from finmag.util.helpers import format_time
from helpers import sort_eigensolutions, as_petsc_matrix, is_hermitian, compute_relative_error, as_dense_array
from types import NoneType
logger = logging.getLogger("finmag")
class AbstractEigensolver(object):
def __repr__(self):
return "<{}{}>".format(self.__class__.__name__, self._extra_info())
def _extra_info(self):
return ""
def is_hermitian(self):
"""
Return True if the solver can only solver Hermitian problems.
"""
return False # by default, solvers are non-Hermitian
def _solve_eigenproblem(self, A, M=None, num=None, tol=None):
# This function should be overridden by the concrete implementations
raise NotImplementedError("Please use one of the concrete "
"eigensolvers, not the abstract one.")
def solve_eigenproblem(self, A, M=None, num=None, tol=None):
"""
Solve the (possibly generalised) eigenvalue problem defined by
A*v = omega*M*v
If `M` is `None`, it uses the identity matrix for `M`.
*Arguments*
A: np.array
The matrix on the left-hand side of the eigenvalue problem.
M: np.array | None
The matrix on the right-hand side of the generalised
eigenvalue problem. Assumes the identity matrix if not
given.
num : int
If given, limit the number of returned eigenvalues and
eigenvectors to at most `num`. Default: `None`.
tol : float
The tolerance for the computed eigensolutions (TODO: what
exactly does this mean?!? Relative or absolute?!?). The
meaning depends on the individual solver. Note that not
all solvers may use/respect this argument (for example,
the dense Scipy solvers don't). The default is None, which
means that whatever the solver's default is will be used.
*Returns*
A pair `(omega, w)` where `omega` is the list of eigenvalues
and `w` the list of corresponding eigenvectors. Both lists are
sorted in in ascending order of the eigenvalues.
"""
def eigenproblem_is_hermitian():
return is_hermitian(A) and (M == None or is_hermitian(M))
if self.is_hermitian() and not eigenproblem_is_hermitian():
raise ValueError("Eigenproblem matrices are non-Hermitian but solver "
"assumes Hermitian matrices. Aborting.")
logger.info("Solving eigenproblem. This may take a while...")
df.tic()
omegas, ws = self._solve_eigenproblem(A, M=M, num=num, tol=tol)
logger.info("Computing the eigenvalues and eigenvectors "
"took {}".format(format_time(df.toc())))
# XXX TODO: Remove this conversion to numpy.arrays once we
# have better support for different kinds of
# matrices (but the conversion would happen in
# compute_relative_error() anyway, so by doing it
# here we avoid doing it multiple times.
if not isinstance(A, np.ndarray):
logger.warning(
"Converting sparse matrix A to dense array to check whether it is "
"Hermitian. This might consume a lot of memory if A is big!.")
A = as_dense_array(A)
if not isinstance(M, (np.ndarray, NoneType)):
logger.warning(
"Converting sparse matrix M to dense array to check whether it is "
"Hermitian. This might consume a lot of memory if M is big!.")
M = as_dense_array(M)
rel_errors = np.array(
[compute_relative_error(A, M, omega, w) for omega, w in zip(omegas, ws)])
return omegas, ws, rel_errors
#
# Dense solvers from scipy.linalg
#
class ScipyDenseSolver(AbstractEigensolver):
_solver_func = None # needs to be instantiated by derived classes
def _solve_eigenproblem(self, A, M=None, num=None, tol=None):
A = as_dense_array(A) # does nothing if A is already a numpy.array
M = as_dense_array(M) # does nothing if M is already a numpy.array
# XXX TODO: For very large eigenproblems it is not advisable to store *all* eigenvectors here
# because this duplicates the size of the eigenproblem matrix. Instead, can we somehow
# ensure that the returned values are sorted and immediately discard
# unneeded vectors?
omega, w = self._solver_func(A, M)
w = w.T # make sure that eigenvectors are stored in rows, not columns
omega, w = sort_eigensolutions(omega, w)
# Return only the number of requested eigenvalues
N, _ = A.shape
num = num or self.num
num = min(num, N - 1)
if num != None:
omega = omega[:num]
w = w[:num]
return omega, w
class ScipyLinalgEig(ScipyDenseSolver):
def __init__(self, num=None):
self.num = num
self._solver_func = scipy.linalg.eig
class ScipyLinalgEigh(ScipyDenseSolver):
def __init__(self, num=None):
self.num = num
self._solver_func = scipy.linalg.eigh
def is_hermitian(self):
return True
#
# Sparse solvers from scipy.sparse.linalg
#
class ScipySparseSolver(AbstractEigensolver):
_solver_func = None # needs to be instantiated by derived classes
def __init__(self, sigma, which, num=6, swap_matrices=False, tol=None):
"""
*Arguments*
sigma:
If given, find eigenvalues near sigma using shift-invert mode.
which:
str, ['LM' | 'SM' | 'LR' | 'SR' | 'LI' | 'SI'], optional
Which `k` eigenvectors and eigenvalues to find:
'LM' : largest magnitude
'SM' : smallest magnitude
'LR' : largest real part
'SR' : smallest real part
'LI' : largest imaginary part
'SI' : smallest imaginary part
When sigma != None, 'which' refers to the shifted eigenvalues w'[i]
(see discussion in 'sigma', above). ARPACK is generally better at
finding large values than small values. If small eigenvalues are
desired, consider using shift-invert mode for better performance.
num: int
The number of eigenvalues to compute (computes all if not
given). Must be provided for the sparse solvers.
"""
self.sigma = sigma
self.which = which
self.num = num
self.swap_matrices = swap_matrices
self.tol = tol or 0. # Scipy's default is 0.0
def _extra_info(self):
return ": sigma={}, which='{}', num={}".format(
self.sigma, self.which, self.num)
def _solve_eigenproblem(self, A, M=None, num=None, tol=None):
N, _ = A.shape
num = num or self.num
num = min(num, N - 2)
tol = tol or self.tol
if self.swap_matrices:
if M is None:
M = id_op(A)
A, M = M, A
# Compute eigensolutions
omega, w = self._solver_func(A, k=num, M=M,
sigma=self.sigma, which=self.which,
tol=tol)
w = w.T # make sure that eigenvectors are stored in rows, not columns
return sort_eigensolutions(omega, w)
def id_op(A):
return scipy.sparse.linalg.LinearOperator(
shape=A.shape, matvec=(lambda v: v), dtype=A.dtype)
class ScipySparseLinalgEigs(ScipySparseSolver):
def __init__(self, *args, **kwargs):
super(ScipySparseLinalgEigs, self).__init__(*args, **kwargs)
self._solver_func = scipy.sparse.linalg.eigs
class ScipySparseLinalgEigsh(ScipySparseSolver):
def __init__(self, *args, **kwargs):
super(ScipySparseLinalgEigsh, self).__init__(*args, **kwargs)
self._solver_func = scipy.sparse.linalg.eigsh
def is_hermitian(self):
return True
class SLEPcEigensolver(AbstractEigensolver):
def __init__(self, problem_type=None, method_type=None, which=None, num=6,
tol=1e-12, maxit=100, shift_invert=False, swap_matrices=False, verbose=True):
"""
*Arguments*
problem_type: str
A string describing the problem type. Must be one of the types
defined in SLEPc.EPS.ProblemType:
- `HEP`: Hermitian eigenproblem.
- `NHEP`: Non-Hermitian eigenproblem.
- `GHEP`: Generalized Hermitian eigenproblem.
- `GNHEP`: Generalized Non-Hermitian eigenproblem.
- `PGNHEP`: Generalized Non-Hermitian eigenproblem
with positive definite ``B``.
- `GHIEP`: Generalized Hermitian-indefinite eigenproblem.
method_type: str
A string describing the method used for solving the eigenproblem.
Must be one of the types defined in SLEPc.EPS.Type:
- `POWER`: Power Iteration, Inverse Iteration, RQI.
- `SUBSPACE`: Subspace Iteration.
- `ARNOLDI`: Arnoldi.
- `LANCZOS`: Lanczos.
- `KRYLOVSCHUR`: Krylov-Schur (default).
- `GD`: Generalized Davidson.
- `JD`: Jacobi-Davidson.
- `RQCG`: Rayleigh Quotient Conjugate Gradient.
- `LAPACK`: Wrappers to dense eigensolvers in Lapack.
which: str
A string describing which piece of the spectrum to compute.
Must be one of the options defined in SLEPc.EPS.Which:
- `LARGEST_MAGNITUDE`: Largest magnitude (default).
- `LARGEST_REAL`: Largest real parts.
- `LARGEST_IMAGINARY`: Largest imaginary parts in magnitude.
- `SMALLEST_MAGNITUDE`: Smallest magnitude.
- `SMALLEST_REAL`: Smallest real parts.
- `SMALLEST_IMAGINARY`: Smallest imaginary parts in magnitude.
- `TARGET_MAGNITUDE`: Closest to target (in magnitude).
- `TARGET_REAL`: Real part closest to target.
- `TARGET_IMAGINARY`: Imaginary part closest to target.
- `ALL`: All eigenvalues in an interval.
- `USER`: User defined ordering.
TODO: Note that `USER` is note supported yet(?!?!?).
num: int
The number of eigenvalues to compute.
tol: float
The solver tolerance.
maxit: num
The maximum number of iterations.
"""
self.problem_type = problem_type # string describing the problem type
self.method_type = method_type # string describing the solution method
self.which = which
self.num = num
self.tol = tol
self.shift_invert = shift_invert
self.swap_matrices = swap_matrices
self.maxit = maxit
self.verbose = verbose
def _extra_info(self):
return ": {}, {}, {}, num={}, tol={:g}, maxit={}".format(
self.problem_type, self.method_type, self.which,
self.num, self.tol, self.maxit)
def is_hermitian(self):
return self.problem_type in ['HEP', 'GHEP', 'GHIEP']
def _create_eigenproblem_solver(self, A, M, num, problem_type, method_type, which, tol, maxit, shift_invert):
"""
Create a SLEPc eigenproblem solver with the operator
"""
# XXX TODO: This import should actually happen at the top, but on some
# systems it seems to be slightly non-trivial to install
# slepc4py, and since we don't use it for the default eigen-
# value methods, it's better to avoid raising an ImportError
# which forces users to try and install it. -- Max, 20.3.2014
from slepc4py import SLEPc
E = SLEPc.EPS()
E.create()
E.setOperators(A, M)
E.setProblemType(getattr(SLEPc.EPS.ProblemType, problem_type))
E.setType(getattr(SLEPc.EPS.Type, method_type))
E.setWhichEigenpairs(getattr(SLEPc.EPS.Which, which))
E.setDimensions(nev=num)
E.setTolerances(tol, maxit)
if shift_invert == True:
st = E.getST()
st.setType(SLEPc.ST.Type.SINVERT)
st.setShift(0.0)
return E
def _solve_eigenproblem(self, A, M=None, num=None, problem_type=None, method_type=None, which=None, tol=1e-12, maxit=100, swap_matrices=None, shift_invert=None):
num = num or self.num
problem_type = problem_type or self.problem_type
method_type = method_type or self.method_type
which = which or self.which
tol = tol or self.tol
maxit = maxit or self.maxit
if problem_type == None:
raise ValueError("No problem type specified for SLEPcEigensolver.")
if method_type == None:
raise ValueError(
"No solution method specified for SLEPcEigensolver.")
if which == None:
raise ValueError("Please specify which eigenvalues to compute.")
if swap_matrices == None:
swap_matrices = self.swap_matrices
if shift_invert == None:
shift_invert = self.shift_invert
A_petsc = as_petsc_matrix(A)
M_petsc = None if (M == None) else as_petsc_matrix(M)
if swap_matrices:
A_petsc, M_petsc = M_petsc, A_petsc
size, _ = A_petsc.size
E = self._create_eigenproblem_solver(
A=A_petsc, M=M_petsc, num=num, problem_type=problem_type,
method_type=method_type, which=which, tol=tol, maxit=maxit, shift_invert=shift_invert)
E.solve()
its = E.getIterationNumber()
eps_type = E.getType()
nev, ncv, mpd = E.getDimensions()
tol, maxit = E.getTolerances()
st_type = E.getST().getType()
nconv = E.getConverged()
if nconv < num:
# XXX TODO: Use a more specific error!
raise RuntimeError("Not all requested eigenpairs converged: "
"{}/{}.".format(nconv, num))
if self.verbose == True:
print("")
print("******************************")
print("*** SLEPc Solution Results ***")
print("******************************")
print("")
print("Number of iterations of the method: %d" % its)
print("Solution method: %s" % eps_type)
print("Spectral Transformation type: %s" % st_type)
print("Number of requested eigenvalues: %d" % nev)
print("Stopping condition: tol=%.4g, maxit=%d" % (tol, maxit))
print("Number of converged eigenpairs: %d" % nconv)
if nconv > 0:
# Create the results vectors
vr, wr = A_petsc.getVecs()
vi, wi = A_petsc.getVecs()
if self.verbose:
print("")
print(" k ||Ax-kx||/||kx|| ")
print("----------------- ------------------")
for i in range(nconv):
k = E.getEigenpair(i, vr, vi)
print(type(E))
print(dir(E))
error = E.computeError(i, etype=1)
if self.verbose:
if k.imag != 0.0:
print(" %9f%+9f j %12g" % (k.real, k.imag, error))
else:
print(" %12f %12g" % (k.real, error))
if self.verbose:
print("")
omegas = []
ws = []
for i in xrange(nconv):
omega = E.getEigenpair(i, vr, vi)
vr_arr = vr.getValues(range(size))
vi_arr = vi.getValues(range(size))
if omega.imag == 0.0:
omegas.append(omega.real)
else:
omegas.append(omega)
if np.all(vi_arr == 0.0):
ws.append(vr_arr)
else:
ws.append(vr_arr + 1j * vi_arr)
omegas = np.array(omegas)
ws = np.array(ws)
logger.warning(
"TODO: Check that the eigensolutions returned by SLEPc are sorted.")
return omegas[:num], ws[:num]
# List of all available eigensolvers
available_eigensolvers = [ScipyLinalgEig, ScipyLinalgEigh,
ScipySparseLinalgEigs, ScipySparseLinalgEigsh,
SLEPcEigensolver,
]
| 16,751 | 35.103448 | 165 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/__init__.py
|
# This file is needed just os that python recognises
# the contents as a module, but we're not actually
# exposing any names here.
| 131 | 32 | 52 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/helpers.py
|
from __future__ import division
import copy
import logging
import numpy as np
import dolfin as df
from finmag.util.helpers import make_human_readable
from scipy.sparse.linalg import LinearOperator
from scipy.sparse import csr_matrix
from scipy.optimize import minimize_scalar
from custom_exceptions import EigenproblemVerifyError
from types import NoneType
logger = logging.getLogger("finmag")
def iseven(n):
"""
Return True if n is an even number and False otherwise.
"""
return (n % 2 == 0)
def is_hermitian(A, rtol=1e-5, atol=1e-8):
if not isinstance(A, np.ndarray):
logger.warning(
"Converting sparse matrix A to dense array to check whether it is "
"Hermitian. This might consume a lot of memory if A is big!.")
A = as_dense_array(A)
return np.allclose(A, np.conj(A.T), rtol=rtol, atol=atol)
def print_eigenproblem_memory_usage(mesh, generalised=False):
"""
Given a mesh, print the amount of memory that the eigenproblem matrix
or matrices (in case of a generalised eigenproblem) for a normal mode
simulation on this mesh will occupy in memory. This is useful when
treating very big problems in order to "interactively" adjust a mesh
until the matrix fits in memory.
"""
N = mesh.num_vertices()
if generalised == False:
byte_size_float = np.zeros(1, dtype=float).nbytes
memory_usage = (2 * N) ** 2 * byte_size_float
else:
byte_size_complex = np.zeros(1, dtype=complex).nbytes
memory_usage = 2 * (2 * N) ** 2 * byte_size_complex
logger.debug("Eigenproblem {} (of {}generalised eigenproblem) "
"for mesh with {} vertices will occupy {} "
"in memory.".format(
'matrices' if generalised else 'matrix',
'' if generalised else 'non-',
N, make_human_readable(memory_usage)))
def compute_relative_error(A, M, omega, w):
if not isinstance(A, np.ndarray) or not isinstance(M, (np.ndarray, NoneType)):
logger.warning(
"Converting sparse matrix to numpy.array as this is the only "
"supported matrix type at the moment for computing relative errors.")
A = as_dense_array(A)
M = as_dense_array(M)
lhs = np.dot(A, w)
rhs = omega * w if (M == None) else omega * np.dot(M, w)
rel_err = np.linalg.norm(lhs - rhs) / np.linalg.norm(omega * w)
return rel_err
def normalise_if_not_zero(v, threshold=1e-12):
v_norm = np.linalg.norm(v)
if v_norm > threshold:
return v / v_norm
else:
return v
def normalise_rows(A, threshold=1e-12):
"""
Return a copy of the matrix `A` where each row vector is
normalised so that its absolute value is 1.
If the norm of a row vector is below `threshold` then the vector is
copied over without being normalised first (this is to ensure that
rows with very small entries are effectively treated as if they
contained all zeros).
"""
B = A.copy()
for i, v in enumerate(A):
a = np.linalg.norm(v)
if a > threshold:
B[i] /= np.linalg.norm(v)
return B
def is_diagonal_matrix(A):
"""
Return `True` if A is a diagonal matrix and False otherwise.
"""
return np.allclose(A, np.diag(np.diag(A)))
def is_scalar_multiple(v, w, tol=1e-12):
"""
Return `True` if the numpy.array `w` is a scalar multiple of the
numpy.array `v` (and `False` otherwise).
"""
v_colvec = v.reshape(-1, 1)
w_colvec = w.reshape(-1, 1)
_, residuals, _, _ = np.linalg.lstsq(v_colvec, w_colvec)
assert(len(residuals) == 1)
rel_err = residuals[0] / np.linalg.norm(v)
return (rel_err < tol)
# a, _, _, _ = np.linalg.lstsq(v_colvec, w_colvec)
# return np.allclose(v, a*w, atol=tol, rtol=tol)
def is_matching_eigenpair(pair1, pair2, tol_eigenval=1e-8, tol_eigenvec=1e-6):
"""
Given two eigenpairs `pair1 = (omega1, w1)` and `pair2 = (omega2, w2)`,
return True if `omega1` and `omega2` coincide (within `tol_eigenval`)
and `w1` is a scalar multiple of `w2` (within `tol_eigenvec`).
"""
omega1, w1 = pair1
omega2, w2 = pair2
w1 = np.asarray(w1)
w2 = np.asarray(w2)
eigenvals_coincide = np.isclose(
omega1, omega2, atol=tol_eigenval, rtol=tol_eigenval)
eigenvecs_coincide = is_scalar_multiple(w1, w2, tol=tol_eigenvec)
return eigenvals_coincide and eigenvecs_coincide
def find_matching_eigenpair((omega, w), ref_eigenpairs,
tol_eigenval=1e-8, tol_eigenvec=1e-6):
"""
Given a pair `(omega, w)` consisting of a computed eigenvalue and
eigenvector, check whether any of the eiganpairs in `ref_eigenpairs`
match the pair `(omega, w)` in the sense that the eigenvalues
coincide (up to `tolerance_eigenval`) and the eigenvectors are
linearly dependent (up to `tolerance_eigenvec`).
"""
matching_indices = \
[i
for (i, pair_ref) in enumerate(ref_eigenpairs)
if is_matching_eigenpair((omega, w), pair_ref,
tol_eigenval=tol_eigenval,
tol_eigenvec=tol_eigenvec)]
if len(matching_indices) >= 2:
raise EigenproblemVerifyError(
"Found more than one matching eigenpair.")
elif matching_indices == []:
return None
else:
return matching_indices[0]
def std_basis_vector(i, N, dtype=None):
"""
Return the `i`-th standard basis vector of length `N`, where `i`
runs from 1 through N.
Examples:
std_basis_vector(2, 4) = [0, 1, 0, 0]
std_basis_vector(1, 6) = [1, 0, 0, 0, 0, 0]
std_basis_vector(2, 6) = [0, 1, 0, 0, 0, 0]
std_basis_vector(6, 6) = [0, 0, 0, 0, 0, 1]
"""
v = np.zeros(N, dtype=dtype)
v[i - 1] = 1.0
return v
def sort_eigensolutions(eigvals, eigvecs):
"""
Sort the lists of eigenvalues and eigenvalues in ascending order
of the eigenvalues.
"""
eigvals = np.asarray(eigvals)
eigvecs = np.asarray(eigvecs)
sort_indices = abs(eigvals).argsort()
eigvals = eigvals[sort_indices]
eigvecs = eigvecs[sort_indices]
return eigvals, eigvecs
def best_linear_combination(v, basis_vecs):
"""
Given a vector `v` and a list <e_i> of basis vectors in `basis_vecs`,
determine the coefficients b_i which minimise the residual:
res = |v - w|
where `w` is the vector
w = \sum_{i} b_i * e_i
Returns the triple (w, [b_i], res).
"""
v = np.asarray(v)
assert(v.ndim == 1)
N = len(v)
num = len(basis_vecs)
v_colvec = np.asarray(v).reshape(-1, 1)
basis_vecs = np.asarray(basis_vecs)
assert(basis_vecs.shape == (num, N))
coeffs, residuals, _, _ = np.linalg.lstsq(basis_vecs.T, v_colvec)
assert(coeffs.shape == (num, 1))
coeffs.shape = (num,)
# XXX TODO: Figure out why it can happen that residuals.shape == (0,)!!
#assert(residuals.shape == (1,))
if residuals.shape == (0,):
logger.warning(
"[DDD] Something went wrong! Assuming the residuals are zero!")
residuals = np.array([0.0])
w = np.dot(basis_vecs.T, coeffs).ravel()
assert(w.shape == v.shape)
return w, coeffs, np.sqrt(residuals[0])
def scipy_sparse_linear_operator_to_dense_array(A, dtype=complex):
"""
Convert a sparse LinearOperator `A` to a dense array.
This is quite inefficient and should be used for debugging only.
"""
m, n = A.shape
A_arr = np.zeros((m, n), dtype=dtype)
# Multiply A by all the standard basis vectors and accumulate the results.
for j, e_j in enumerate(np.eye(n)):
v = A.matvec(e_j)
if dtype == float:
if not(all(v.imag == 0.0)):
raise ValueError("Cannot cast complex vector into real array.")
else:
v = v.real
A_arr[:, j] = v
return A_arr
def petsc_matrix_to_numpy_array(A, dtype=float):
# XXX TODO: Move this import to the top once we have found an easy
# and reliable (semi-)automatic way for users to install
# petsc4py. -- Max, 20.3.2014
from petsc4py import PETSc
if not isinstance(A, PETSc.Mat):
raise TypeError("Matrix must be of type petsc4py.PETSc.Mat, "
"but got: {}".format(type(A)))
indptr, indices, data = A.getValuesCSR()
data = np.asarray(data, dtype=dtype)
A_csr = csr_matrix((data, indices, indptr), shape=A.size)
return A_csr.todense()
def as_dense_array(A, dtype=None):
# XXX TODO: Move this import to the top once we have found an easy
# and reliable (semi-)automatic way for users to install
# petsc4py. -- Max, 20.3.2014
from petsc4py import PETSc
if A == None:
return None
if isinstance(A, np.ndarray):
return np.asarray(A, dtype=dtype)
if dtype == None:
# TODO: Do we have a better option than using 'complex' by default?
dtype = complex
if isinstance(A, LinearOperator):
return scipy_sparse_linear_operator_to_dense_array(A, dtype=dtype)
elif isinstance(A, PETSc.Mat):
return petsc_matrix_to_numpy_array(A, dtype=dtype)
#raise NotImplementedError()
elif isinstance(A, df.PETScMatrix):
# return petsc_matrix_to_dense_array(A.mat(), dtype=dtype)
raise NotImplementedError()
else:
raise TypeError(
"Matrix must be either a scipy LinearOperator, a dolfin "
"PETScMatrix or a petsc4py matrix. Got: {}".format(type(A)))
def as_petsc_matrix(A):
"""
Return a (sparse) matrix of type `petsc4py.PETSc.Mat` containing
the same entries as the `numpy.array` `A`. The returned matrix
will be as sparse as possible (i.e. only the non-zero entries of A
will be set).
"""
# XXX TODO: Move this import to the top once we have found an easy
# and reliable (semi-)automatic way for users to install
# petsc4py. -- Max, 20.3.2014
from petsc4py import PETSc
if isinstance(A, PETSc.Mat):
return A
m, n = A.shape
if isinstance(A, np.ndarray):
def get_jth_column(j):
return A[:, j]
elif isinstance(A, LinearOperator):
def get_jth_column(j):
e_j = np.zeros(m)
e_j[j] = 1.0
return A.matvec(e_j)
else:
raise TypeError("Unkown matrix type: {}".format(type(A)))
A_petsc = PETSc.Mat().create()
A_petsc.setSizes([m, n])
A_petsc.setType('aij') # sparse
A_petsc.setUp()
for j in xrange(0, n):
col = get_jth_column(j)
if col.dtype == complex:
if np.allclose(col.imag, 0.0):
col = col.real
else:
raise TypeError("Array with complex entries cannot be converted "
"to a PETSc matrix.")
for i in xrange(0, m):
# We try to keep A_petsc as sparse as possible by only
# setting nonzero entries.
if col[i] != 0.0:
A_petsc[i, j] = col[i]
A_petsc.assemble()
return A_petsc
def irregular_interval_mesh(xmin, xmax, n):
"""
Create a mesh on the interval [xmin, xmax] with n vertices.
The first and last mesh node coincide with xmin and xmax,
but the other nodes are picked at random from within the
interval.
"""
# Create an 'empty' mesh
mesh = df.Mesh()
# Open it in the MeshEditor as a mesh of topological and geometrical
# dimension 1
editor = df.MeshEditor()
editor.open(mesh, 1, 1)
# We're going to define 5 vertices, which result in 4 'cells' (= intervals)
editor.init_vertices(n)
editor.init_cells(n - 1)
coords = (xmax - xmin) * np.random.random_sample(n - 1) + xmin
coords.sort(0)
# Define the vertices and cells with their corresponding indices
for (i, x) in enumerate(coords):
editor.add_vertex(i, np.array([x], dtype=float))
editor.add_vertex(n - 1, np.array([xmax], dtype=float))
for i in xrange(n - 1):
editor.add_cell(i, np.array([i, i + 1], dtype='uintp'))
editor.close()
return mesh
| 12,261 | 31.099476 | 82 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/helpers_test.py
|
from __future__ import division
import numpy as np
import pytest
from scipy.sparse.linalg import LinearOperator
from helpers import *
def test_iseven():
for n in [0, 2, 6, 1223456, -18]:
assert(iseven(n))
for n in [1, 7, -19, -5, 787823]:
assert(not iseven(n))
def test_is_hermitian():
A1 = np.array([[1, -2, 3, 4],
[-2, 5, 12, -33],
[3, 12, 42, -8],
[4, -33, -8, 0.2]])
assert(is_hermitian(A1))
A2 = np.array([[0.3, 4 - 5j, 0.2 + 3j],
[4 + 5j, 2.0, -1 + 3.3j],
[0.2 - 3j, -1 - 3.3j, -4]])
assert(is_hermitian(A2))
A3 = np.array([[1, 2],
[4, 4]])
assert(not is_hermitian(A3))
A4 = np.array([[1, 2 + 3j],
[2 + 3j, 4]])
assert(not is_hermitian(A4))
A5 = np.array([[1 + 1j, 2 + 3j],
[2 - 3j, 4]])
assert(not is_hermitian(A5))
@pytest.mark.parametrize(
"v, vn_expected",
[([1, 1, 1, 1], [0.5, 0.5, 0.5, 0.5]),
([1, 2, 3, -1, -1], [0.25, 0.5, 0.75, -0.25, -0.25]),
([0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]),
([1e-14, 1e-14, 1e-13, 1e-13], [1e-14, 1e-14, 1e-13, 1e-12]),
])
def test_normalise_if_not_zero(v, vn_expected):
vn = normalise_if_not_zero(v)
assert(np.allclose(vn, vn_expected))
def test_normalise_rows():
A = np.array([[2, 0, 0, 0, 0],
[0, -3, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1e-16, 0],
[0, 3, 0, 0, 4]])
A_normalised = normalise_rows(A)
A_normalised_ref = np.array([[1, 0, 0, 0, 0],
[0, -1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 1e-16, 0],
[0, 3. / 5, 0, 0, 4. / 5]])
assert(np.allclose(A_normalised, A_normalised_ref))
def test_is_diagonal_matrix():
A1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
A2 = np.array([[4, 0, 0],
[0, -5, 0],
[0, 0, 1e-4]])
assert(not is_diagonal_matrix(A1))
assert(is_diagonal_matrix(A2))
@pytest.mark.parametrize("a, tol",
[(0.253, 5e-9),
(1.42e-8, 5e-5),
(5.4e4, 1e-8),
(1.2 + 4.4j, 1e-8)])
def test_is_scalar_multiple(a, tol):
"""
Create two random arrays of dtype `float` and `complex`, respectively.
Multiply each by the scalar factor `a` and check that the result is
recognised as a scalar multiple.
"""
print "[DDD] a={}".format(a)
N = 100
rand_vec = np.random.random_sample(N)
rand_vec[[0, 40, 62]] = 0.0 # set a few values to zero
v = np.asarray(rand_vec, dtype=type(a))
w = a * v
assert(is_scalar_multiple(v, w, tol=tol))
@pytest.mark.parametrize("eps, num_elements",
[(4.2, 1),
(0.155, 1),
(1e-3, 1),
(1e-5, 5),
(5e-6, 50),
])
def test_not_is_scalar_multiple(eps, num_elements):
print "[DDD] eps={}, num_elements={}".format(eps, num_elements)
N = 100
w = np.random.random_sample(N)
v = 3.24 * w
v[range(num_elements)] += eps
assert(not is_scalar_multiple(v, w))
def test_find_matching_eigenpair():
"""
Construct a list of reference eigenpairs and check for a few artificial
'computed' eigenpairs whether they match any of the pairs in the list.
"""
eigenpairs_ref = [
(42.0, [1, 2, 3, 4, 5]),
(23.0, [4, 4, 4, -4, 6]),
(12.4, [-1, -2, 3, 2, -1]),
(23.0, [4, 4, 4, -4, 6])
]
omega1, w1 = (12.4, [-1, -2, 3, 2, -1]) # matches 3rd eigenpair
omega2, w2 = (12.4, [1.9, 3.8, -5.7, -3.8, 1.9]) # matched 3rd eigenpair
omega3, w3 = (42.000000001, [-2, -4, -6, -8, -10]) # matches 1st eigenpair
omega4, w4 = (42.0, [1, 3, 3, 4, 5]) # no match
omega5, w5 = (42.3, [1, 2, 3, 4, 5]) # no match
# duplicate match; should throw error
omega6, w6 = (23.0, [4, 4, 4, -4, 6])
idx1 = find_matching_eigenpair((omega1, w1), eigenpairs_ref)
idx2 = find_matching_eigenpair((omega2, w2), eigenpairs_ref)
idx3 = find_matching_eigenpair((omega3, w3), eigenpairs_ref)
idx4 = find_matching_eigenpair((omega4, w4), eigenpairs_ref)
idx5 = find_matching_eigenpair((omega5, w5), eigenpairs_ref)
assert(idx1 == 2)
assert(idx2 == 2)
assert(idx3 == 0)
assert(idx4 == None)
assert(idx5 == None)
with pytest.raises(EigenproblemVerifyError):
# Duplicate match should raise an exception
find_matching_eigenpair((omega6, w6), eigenpairs_ref)
def test_standard_basis_vector():
e_1_5 = [1, 0, 0, 0, 0]
e_4_5 = [0, 0, 0, 1, 0]
e_5_7 = [0, 0, 0, 0, 1, 0, 0]
assert(np.allclose(e_1_5, std_basis_vector(1, N=5)))
assert(np.allclose(e_4_5, std_basis_vector(4, N=5, dtype=float)))
assert(np.allclose(e_5_7, std_basis_vector(5, N=7, dtype=complex)))
def test_sort_eigensolutions():
w1 = [0, 1, 2, 3, 4, 5]
w2 = [10, 11, 12, 13, 14, 15]
w3 = [20, 21, 22, 23, 24, 25]
w4 = [30, 31, 32, 33, 34, 35]
w5 = [40, 41, 42, 43, 44, 45]
ws = [w1, w2, w3, w4, w5]
omegas_sorted, ws_sorted = sort_eigensolutions([4, 1, 3, 7, 5], ws)
assert(np.allclose(omegas_sorted, [1, 3, 4, 5, 7]))
assert(np.allclose(ws_sorted, [w2, w3, w1, w5, w4]))
omegas_sorted, ws_sorted = sort_eigensolutions([4, 3.3, 2.1, 5.5, 2.9], ws)
assert(np.allclose(omegas_sorted, [2.1, 2.9, 3.3, 4, 5.5]))
assert(np.allclose(ws_sorted, [w3, w5, w2, w1, w4]))
def test_best_linear_combination():
"""
TODO: Write me!!
"""
e1 = [1, 0, 0]
e2 = [0, 1, 0]
e3 = [0, 0, 1]
v = [-2, 1, -3]
w, coeffs, res = best_linear_combination(v, [e1, e2])
assert(np.allclose(w, [-2, 1, 0]))
assert(np.allclose(coeffs, [-2, 1]))
assert(np.allclose(res, 3.0))
w, coeffs, res = best_linear_combination(v, [e1, e3])
assert(np.allclose(w, [-2, 0, -3]))
assert(np.allclose(coeffs, [-2, -3]))
assert(np.allclose(res, 1.0))
w, coeffs, res = best_linear_combination(v, [e1, e2, e3])
assert(np.allclose(w, v))
assert(np.allclose(coeffs, [-2, 1, -3]))
assert(np.allclose(res, 0.0))
# More complicated example
e1 = np.array([1, 0, 3])
e2 = np.array([-2, 4, -6])
a = 0.5
b = 0.25
v0 = np.array([-3, 0, 1])
v = v0 + a * e1 + b * e2
w, coeffs, res = best_linear_combination(v, [e1, e2])
assert(np.allclose(w, a * e1 + b * e2))
assert(np.allclose(coeffs, [a, b]))
assert(np.allclose(res, np.linalg.norm(v0)))
def scipy_sparse_linear_operator_to_dense_array():
"""
Create a random matrix, convert it to a LinearOperator and use
'as_dense_array' to convert it back. Check that the result is
the same as the original matrix.
"""
for N in [10, 20, 30, 50, 100]:
A = np.random.random_sample((N, N))
A_sparse = LinearOperator(shape=(N, N), matvec=lambda v: np.dot(A, v))
A_dense = as_dense_array(A_sparse)
assert(np.allclose(A, A_dense))
def test_as_dense_array():
"""
Define a dense tridiagonal matrix (with 'periodic boundary
conditions') and its equivalents as LinearOperator, PETSc.Mat and
dolfin.PETScMatrix. Then check that as_dense_array() returns the
same array for all of them.
"""
N = 50
# Define dense matrix
A = np.zeros((N, N))
for i in xrange(N):
A[i, i] = 2.4
A[i, i - 1] = 5.5
A[i, (i + 1) % N] = 3.7
# Define equivalent LinearOperator
def A_matvec(v):
# Note that the vectors end up as column vectors, thus the
# direction we need to roll the arrays might seem
# counterintuitive.
return 2.4 * v + 5.5 * np.roll(v, +1) + 3.7 * np.roll(v, -1)
A_LinearOperator = LinearOperator((N, N), matvec=A_matvec)
# Define equivalent PETSc.Mat()
A_petsc = as_petsc_matrix(A)
# Define equivalent dolfin.PETScMatrix
#
# TODO: This only works in the development version of dolfin,
# which is not released yet. Reactivate this test once it's
# available!
#
# A_petsc_dolfin = df.PETScMatrix(A_petsc)
# For numpy.arrays the exact same object should be returned (if
# the dtype is the same)
assert(id(A) == id(as_dense_array(A)))
A_complex = np.asarray(A, dtype=complex)
assert(id(A_complex) == id(as_dense_array(A_complex)))
# Check that the conversion works correctly
assert(as_dense_array(None) == None)
assert(np.allclose(A, as_dense_array(A, dtype=complex)))
assert(np.allclose(A, as_dense_array(A_LinearOperator)))
assert(np.allclose(A, as_dense_array(A_petsc)))
#assert(np.allclose(A, as_dense_array(A_petsc_dolfin)))
def test_as_petsc_matrix():
N = 20
# Create a tridiagonal matrix with random entries
A = np.zeros((N, N))
a = np.random.random_sample(N - 1)
b = np.random.random_sample(N)
c = np.random.random_sample(N - 1)
A += np.diag(a, k=-1)
A += np.diag(b, k=0)
A += np.diag(c, k=+1)
print "[DDD] A:"
print A
# Convert to PETSC matrix
A_petsc = as_petsc_matrix(A)
# Check that the sparsity pattern is as expected
indptr, _, data = A_petsc.getValuesCSR()
indptr_expected = [0] + range(2, 3 * (N - 1), 3) + [3 * N - 2]
assert(all(indptr == indptr_expected))
# Convert back to numpy array
B = as_dense_array(A_petsc)
assert(np.allclose(A, B))
# A numpy array of dtype complex can only be converted to a PETSc
# matrix if the imaginary part is zero.
C = (1.0 + 0.j) * np.random.random_sample((N, N))
assert(C.dtype == complex) # check that we created a complex array
C2 = as_dense_array(as_petsc_matrix(C))
assert(np.allclose(C, C2))
D = 1j * np.random.random_sample((N, N))
assert(D.dtype == complex) # check that we created a complex array
with pytest.raises(TypeError):
as_petsc_matrix(D)
# Check that we can also convert a LinearOperator to a PETScMatrix
A_LinearOperator = LinearOperator(
shape=(N, N), matvec=lambda v: np.dot(A, v))
A_petsc2 = as_petsc_matrix(A_LinearOperator)
A_roundtrip = as_dense_array(A_petsc2)
assert(np.allclose(A, A_roundtrip))
| 10,497 | 31.401235 | 79 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/eigenproblems.py
|
from __future__ import division
import numpy as np
import dolfin as df
import itertools
import inspect
import logging
import sys
import matplotlib.pyplot as plt
from scipy.sparse.linalg import LinearOperator
from finmag.field import Field
from finmag.energies import Exchange
from finmag.util.consts import gamma, mu0
from math import pi
from helpers import normalise_rows, find_matching_eigenpair, \
std_basis_vector, best_linear_combination, as_dense_array, \
irregular_interval_mesh, iseven
from custom_exceptions import EigenproblemVerifyError
color_cycle = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
class AbstractEigenproblem(object):
def __init__(self):
pass
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def _raise_not_implemented_error(self, msg):
raise NotImplementedError("No analytical {} available for eigenproblem class "
"'{}'".format(msg, self.__class__.__name__))
def is_hermitian(self):
"""
Return True if the matrices defining the eigenproblem are Hermitian.
"""
return False # by default, eigenproblems are non-Hermitian
def solve(self, solver, N, dtype, num=None, **kwargs):
"""
Solve the (possibly generalised) eigenvalue problem defined by
A*v = omega*M*v
where `A` and `M` are the matrices returned by `self.instantiate(N)`.
*Arguments*
solver :
The solver to use. This should be an instance of one of
the solver classes in the `eigensolvers` module.
N : int
The size of the eigenvalue problem to be solved (i.e. the
size of the matrices `A` and `M`).
dtype : float | complex
The dtype of the matrices `A` and `M`.
num : int
If given, limit the number of returned eigenvalues and
eigenvectors to at most `num` (but note that fewer may be
returned if the solver was instantiated with a lower
valuer of `num`). If `None` (the default), the number of
returned solutions is limited by the properties of the
solver.
All other keyword arguments are passed on to the specific solver.
*Returns*
A triple `(omega, w, rel_errors)` where `omega` is the list of eigenvalues,
`w` the list of corresponding eigenvectors and `rel_errors` the list of
relative errors, defined as ||Ax-kMx||_2/||kx||_2. All three lists are
sorted in in ascending order of the eigenvalues.
"""
A, M = self.instantiate(N, dtype)
omega, w, rel_errors = solver.solve_eigenproblem(
A, M=M, num=num, **kwargs)
return omega, w, rel_errors
def instantiate(self, N, dtype):
"""
Return a pair of matrices (A, M) which defines a generalised
eigenvalue problem
A*v = omega*M*v
The second matrix `M` may be `None` for some problems, in
which case the generalised eigenproblem reduces to a regular
one.
"""
raise NotImplementedError(
"Please choose one of the concrete eigenproblem classes.")
def print_analytical_eigenvalues(self, num, size=None, unit='GHz'):
if isinstance(size, str):
raise TypeError(
"Wrong value for argument 'size': '{}'. Did you mean to "
"supply the 'unit' argument instead?".format(size))
try:
unit_factor = {'Hz': 1.0,
'KHz': 1e3,
'MHz': 1e6,
'GHz': 1e9,
}[unit]
except KeyError:
raise ValueError("Unknown unit: {}. Please choose one of "
"Hz, KHz, MHz, GHz.".format(unit))
eigenvals = self.get_analytical_eigenvalues(num, size=size)
for omega in eigenvals:
print("{:.3f} {}".format(omega / unit_factor, unit))
def get_analytical_eigenvalues(self, num, size=None):
"""
Return a `numpy.array` of len `num` containing the first `num`
analytical eigenvalues of this eigenproblem.
For most eigenproblems the eigenvalues depend on the size of the
matrix. In this case the argument `size` must be specified.
"""
return np.array([self.get_kth_analytical_eigenvalue(k, size) for k in xrange(num)])
def get_kth_analytical_eigenvalue(self, k, size=None):
"""
Return the k-th analytical eigenvalue of this eigenproblem.
For most eigenproblems the eigenvalues depend on the size of the
matrix. In this case the argument `size` must be specified.
"""
self._raise_not_implemented_error('eigenvalues')
def get_analytical_eigenvectors(self, num, size):
"""
Return a `numpy.array` of shape `(num, size)` containing the
first `num` analytical eigenvectors of this eigenproblem.
"""
return np.array([self.get_kth_analytical_eigenvector(k, size) for k in xrange(num)])
def get_kth_analytical_eigenvector(self, k, size):
"""
Return the k-th analytical eigenvector of this eigenproblem.
"""
self._raise_not_implemented_error('eigenvectors')
def get_kth_analytical_eigenpair(self, k, size):
omega = self.get_kth_analytical_eigenvalue(k, size)
w = self.get_kth_analytical_eigenvector(k, size)
return omega, w
def get_analytical_eigenpairs(self, num, size):
"""
Return the first `num` eigenvalues/eigenvectors for this eigenproblem.
"""
omega = self.get_analytical_eigenvalues(num, size=size)
w = self.get_analytical_eigenvectors(num, size)
return omega, w
def _set_plot_title(self, fig, title):
ax = fig.gca()
ax.set_title(title)
def plot(self, w, fig, label, fmt=None):
"""
Generic function to plot a given eigenvector `w` (which must have
been computed in advance). This function can be overridden by
subclasses if they require more advanced or specialised plotting
functionality (e.g. if the system is not 1-dimensional).
"""
ax = fig.gca()
fmt = fmt or ''
ax.plot(w, fmt, label=label)
def plot_analytical_solutions(self, k_vals, N=None, figsize=None, filename=None):
"""
*Arguments*
k_vals:
List of indices of the analytical solutions to be plotted.
filename:
If given, the plot will be saved to a file with the given name.
"""
fig = plt.figure(figsize=figsize)
for k in k_vals:
omega, w = self.get_kth_analytical_eigenpair(k, N)
label = 'k={} (EV: {:.3g})'.format(k, omega)
self.plot(w, fig=fig, label=label)
h, l = fig.gca().get_legend_handles_labels()
fig.legend(h, l, 'lower center')
title_str = 'Solutions to {}, N={}'.format(self, N)
self._set_plot_title(fig, title_str)
if filename != None:
fig.savefig(filename)
return fig
def plot_computed_solutions(self, k_vals, solver=None, N=None, dtype=None,
num=None, plot_analytical_approximations=True,
tol_eigval=1e-8, figsize=None, filename=None):
"""
*Arguments*
k_vals: list of int
List of indices of the analytical solutions to be plotted.
solver:
The eigensolver to use in order to compute the solutions.
N: int
The size of the matrices defining the eigenvalue problem.
dtype: float | complex
The dtype of the matrices defining the eigenvalue problem.
num: int
The number of solutions to be computed. This argument may
be of interest for the sparse solvers (which may return
different results depending on the number of solutions
requested.)
plot_analytical_approximations: bool
If True (the default), the best approximation in terms of
exact solutions is also plotted along with each computed
solution.
tol_eigval: float
Used to determine the best analytical approximation of the
computed solution. See the docstring of the function
`AbstractEigenproblem.best_analytical_approximation()` for
details.
filename:
If given, the plot will be saved to a file with the given name.
"""
fig = plt.figure(figsize=figsize)
num = num or (max(k_vals) + 1)
omegas, ws, rel_errors = self.solve(solver, N, dtype, num=num)
for (idx, k) in enumerate(k_vals):
# Plot computed solution
omega = omegas[k]
w = ws[k]
rel_err = rel_errors[k]
# Plot analytical approximation if requested
if plot_analytical_approximations:
w_approx, res_approx = \
self.best_analytical_approximation(
omega, w, tol_eigval=tol_eigval)
fmt = '--x{}'.format(color_cycle[idx % len(k_vals)])
label = 'k={}, analyt., res.: {:.2g}'.format(k, res_approx)
self.plot(w_approx, fmt=fmt, fig=fig, label=label)
label = 'k={} (EV: {:.3g}, rel. err.: {:.3g})'.format(
k, omega, rel_err)
fmt = '-{}'.format(color_cycle[idx % len(k_vals)])
self.plot(w, fmt=fmt, fig=fig, label=label)
h, l = fig.gca().get_legend_handles_labels()
fig.legend(h, l, 'lower center')
dtype_str = {float: 'float', complex: 'complex'}[dtype]
# XXX TODO: Make sure the title reflects the specific values
# of the solver used during the 'compute' method.
title_str = 'Solutions to {}, solver={}, N={}, dtype={}'.format(
self, solver, N, dtype_str)
self._set_plot_title(fig, title_str)
if filename != None:
fig.savefig(filename)
return fig
def verify_eigenpair_numerically(self, a, v, tol=1e-8):
"""
Check that the eigenpair `(a, eigenvec)` is a valid eigenpair
of the given eigenproblem. Return `True` if
|A*v - a*v| < tol
and `False` otherwise.
*Arguments*
a : float | complex
The eigenvalue to be verified.
v : numpy.array
The eigenvector to be verified.
tol : float
The tolerance for comparison.
"""
v = np.asarray(v)
if not v.ndim == 1:
raise ValueError("Expected 1D vector as second argument `v`. "
"Got: array of shape {}".format(v.shape))
N = len(v)
A, _ = self.instantiate(N, dtype=v.dtype)
residue = np.linalg.norm(np.dot(A, v) - a * v)
return residue < tol
def verify_eigenpairs_numerically(self, eigenpairs, tol=1e-8):
for omega, w in eigenpairs:
if not self.verify_eigenpair_numerically(omega, w, tol=tol):
return False
return True
def get_analytical_eigenspace_basis(self, eigval, size, tol_eigval=1e-8):
"""
Return a list of all analytical eigenvectors whose eigenvalue is equal
to `eigval` (within relative tolerance `tol_eigval`). Thus the returned
vectors form a basis of the eigenspace associated to `eigval`.
"""
# if not abs(eigval.imag) < 1e-12:
# raise ValueError("Eigenvalue must be real. Got: {}".format(eigval))
indices = []
k_left = None
k_right = None
for k in xrange(size):
a = self.get_kth_analytical_eigenvalue(k, size)
if np.allclose(a, eigval, atol=tol_eigval, rtol=tol_eigval):
indices.append(k)
# We use 'abs' in the following comparisons because the
# eigenvalues may be complex/imaginary.
if abs(a) < abs(eigval):
k_left = k
if abs(a) > abs(eigval):
if k_right == None:
k_right = k
if abs(a) > abs(eigval) * (1. + 2 * tol_eigval):
break
eigenspace_basis = [
self.get_kth_analytical_eigenvector(k, size) for k in indices]
if eigenspace_basis == []:
if k_left != None:
eigval_left = self.get_kth_analytical_eigenvalue(k_left, size)
else:
eigval_left = None
if k_right != None:
eigval_right = self.get_kth_analytical_eigenvalue(
k_right, size)
else:
eigval_right = None
# print "eigval_right - a: {}".format(eigval_right - eigval)
raise ValueError(
"Not an eigenvalue of {}: {} (tolerance: {}). Closest "
"surrounding eigenvalues: ({}, {})".format(
self, eigval, tol_eigval, eigval_left, eigval_right))
return eigenspace_basis
def best_analytical_approximation(self, a, v, tol_eigval=1e-8):
"""
Compute a basis <e_i> of the eigenspace associated with `a` and find
the vector w which minimise the residual:
res = |v - w|
where `w` is constrained to be a linear linear combination of
the basis vectors `e_i`:
w = \sum_{i} b_i * e_i (b_i \in R)
The return value is the pair `(w, res)` consisting of the best
approximation and the residual.
*Arguments*
a: float
The eigenvalue to be verified.
v: numpy.array
The eigenvector to be verified.
tol_eigval: float
Used to determine the eigenspace basis associated with the
given eigenvalue `a`. All those analytical eigenvectors
are considered for the basis whose associated (exact)
eigenvalue lies within `tol_eigval` of `a`.
tol_residual: float
The tolerance for the residual. The given eigenpair `(a,
v)` is accepted as verified iff the minimum of `v` minus
any linear combination of eigenspace basis vectors is less
than `tol_residual`.
"""
v = np.asarray(v)
if (v.ndim != 1):
raise TypeError("Expected 1D array for second argument `v`. "
"Got: '{}'".format(v))
size = len(v)
eigenspace_basis = self.get_analytical_eigenspace_basis(
a, size, tol_eigval=tol_eigval)
w, _, res = best_linear_combination(v, eigenspace_basis)
return w, res
def verify_eigenpair_analytically(self, a, v, tol_residual=1e-8, tol_eigval=1e-8):
"""
Check whether the vector `v` lies in the eigenspace associated
with the eigenvalue `a`.
See `best_analytical_approximation` for details about the
tolerance arguments.
"""
_, res = self.best_analytical_approximation(
a, v, tol_eigval=tol_eigval)
return res < tol_residual
def verify_eigenpairs_analytically(self, eigenpairs, tol_residual=1e-8, tol_eigval=1e-8):
for omega, w in eigenpairs:
if not self.verify_eigenpair_analytically(
omega, w, tol_residual=tol_residual, tol_eigval=tol_eigval):
return False
# XXX TODO: Also verify that we indeed computed the N smallest
# solutions, not just any analytical solutions!
return True
class DiagonalEigenproblem(AbstractEigenproblem):
"""
Eigenproblem of the form
D*v = omega*v
where D is a diagonal matrix of the form
D = diag([1, 2, 3, ..., N])
"""
def instantiate(self, N, dtype):
"""
Return a pair (D, None), where D is a diagonal matrix of the
form D=diag([1, 2, 3, ..., N]).
"""
# XXX TODO: Actually, we shouldn't store these values in 'self'
# because we can always re-instantiate the problem,
# right?
self.N = N
self.dtype = dtype
self.diagvals = np.arange(1, N + 1, dtype=dtype)
return np.diag(self.diagvals), None
def is_hermitian(self):
return True
def get_kth_analytical_eigenvalue(self, k, size=None):
return (k + 1)
def get_kth_analytical_eigenvector(self, k, size):
w = np.zeros(size)
w[k] = 1.0
return w
class RingGraphLaplaceEigenproblem(AbstractEigenproblem):
"""
Eigenproblem of the form
A*v = omega*v
where A is a Laplacian matrix. of the form
[ 2, -1, 0, 0, ...]
[-1, 2, -1, 0, ...]
[ 0, -1, 2, -1, ...]
...
[..., 0, -1, 2, -1]
[..., 0, 0, -1, 2]
"""
def instantiate(self, N, dtype):
"""
Return a pair (A, None), where A is a Laplacian matrix
of the form
[ 2, -1, 0, 0, ...]
[-1, 2, -1, 0, ...]
[ 0, -1, 2, -1, ...]
...
[..., 0, -1, 2, -1]
[..., 0, 0, -1, 2]
"""
# XXX TODO: Actually, we shouldn't store these values in 'self'
# because we can always re-instantiate the problem,
# right?
self.N = N
self.dtype = dtype
A = np.zeros((N, N), dtype=dtype)
A += np.diag(2 * np.ones(N))
A -= np.diag(1 * np.ones(N - 1), k=1)
A -= np.diag(1 * np.ones(N - 1), k=-1)
A[0, N - 1] = -1
A[N - 1, 0] = -1
return A, None
def is_hermitian(self):
return True
def get_kth_analytical_eigenvalue(self, k, size=None):
i = (k + 1) // 2
return 2 - 2 * np.cos(2 * pi * i / size)
def get_kth_analytical_eigenvector(self, k, size):
xs = np.arange(size)
i = (k + 1) // 2
if iseven(k):
res = np.cos(2 * pi * i * xs / size)
else:
res = np.sin(2 * pi * i * xs / size)
return res / np.linalg.norm(res)
def m0_cross(m0, v):
"""
Compute and return the site-wise cross product
of the two vector fields `m0` and `v`.
"""
return np.cross(m0.reshape(3, -1), v.reshape(3, -1), axis=0)
class Nanostrip1dEigenproblemFinmag(AbstractEigenproblem):
"""
Eigenproblem of the form
A*v = omega*v
where A is a matrix that represents the right-hand side of the
action of the linearised LLG equation (without damping):
dv/dt = -gamma * m_0 x H_exchange(v)
"""
def __init__(self, A_ex, Ms, xmin, xmax, unit_length=1e-9, regular_mesh=True):
"""
*Arguments*
A_ex: float
Exchange coupling constant (in J/m).
Ms: float
Saturation magnetisation (in A/m).
xmin, xmax: float
The bounds of the interval on which the 1D system is
defined.
regular_mesh: bool
If True (the default), the mesh nodes will be equally
spaced in the interval [xmin, xmax]. Otherwise they will
be randomly chosen.
"""
self.A_ex = A_ex
self.Ms = Ms
self.xmin = xmin
self.xmax = xmax
self.unit_length = unit_length
self.regular_mesh = regular_mesh
self.L = (self.xmax - self.xmin) * self.unit_length
def compute_exchange_field(self, v):
"""
Compute the exchange field for the given input vector `v`
(which should be a `numpy.array`).
"""
self.exch.m.set_with_numpy_array_debug(v)
return self.exch.compute_field()
def compute_action_rhs_linearised_LLG(self, m0, v):
"""
This function computes the action of the right hand side of
the linearised LLG on the vector `v` and returns the result.
Explicitly, it computes
-gamma * (m0 x H_ex(v))
where `m0` is the equilibrium configuration around which the
LLG was linearised.
"""
H = self.compute_exchange_field(v).reshape(3, -1)
return -gamma * m0_cross(m0, H)
def compute_action_rhs_linearised_LLG_2K(self, v):
"""
Compute the action of the right hand side of the linearised
LLg equation on the vector `v`, which should have a shape
compatible with (2, N). This function assumes that the
equilibrium configuration around which the LLG equation was
linearised is `m0 = (0, 0, 1)^T`.
"""
K = self.K
m0 = np.array([0, 0, 1])
v_3K = np.zeros(3 * K)
v_3K[:2 * K] = v
#v_3K.shape = (3, -1)
res_3K = self.compute_action_rhs_linearised_LLG(m0, v_3K).ravel()
res = res_3K[:2 * K]
return res
def instantiate(self, N, dtype, regular_mesh=None):
"""
Return a pair (A, None), where A is a matrix representing the
action on a vector v given by the right-hand side of the
linearised LLG equation (without damping):
A*v = dv/dt = -gamma * m_0 x H_exchange(v)
"""
if not iseven(N):
raise ValueError("N must be even. Got: {}".format(N))
# XXX TODO: Actually, we shouldn't store these values in 'self'
# because we can always re-instantiate the problem,
# right?
self.N = N
self.dtype = dtype
if regular_mesh == None:
regular_mesh = self.regular_mesh
self.K = N // 2
if regular_mesh:
mesh = df.IntervalMesh(self.K - 1, self.xmin, self.xmax)
else:
mesh = irregular_interval_mesh(self.xmin, self.xmax, self.K)
#raise NotImplementedError()
V = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
v = Field(V)
self.exch = Exchange(A=self.A_ex)
Ms_field = Field(df.FunctionSpace(mesh, 'DG', 0), self.Ms)
self.exch.setup(v, Ms_field, unit_length=self.unit_length)
C_2Kx2K = LinearOperator(
shape=(N, N), matvec=self.compute_action_rhs_linearised_LLG_2K, dtype=dtype)
C_2Kx2K_dense = as_dense_array(C_2Kx2K)
return C_2Kx2K_dense, None
def get_kth_analytical_eigenvalue(self, k, size=None):
i = k // 2
return 1j * (-1) ** k * (2 * self.A_ex * gamma) / (mu0 * self.Ms) * (i * pi / self.L) ** 2
def get_kth_analytical_eigenvector(self, k, size):
assert(iseven(size))
i = k // 2
xs = np.linspace(
self.xmin * self.unit_length, self.xmax * self.unit_length, size // 2)
v1 = np.cos(i * pi / self.L * xs)
v2 = np.cos(i * pi / self.L * xs) * 1j * (-1) ** i
return np.concatenate([v1, v2])
def _set_plot_title(self, fig, title):
fig.suptitle(title, fontsize=16, verticalalignment='bottom')
# fig.subplots_adjust(top=0.55)
# fig.tight_layout()
def plot(self, w, fig, label, fmt=None):
"""
This function plots the real and imaginary parts of the solutions separately,
and in addition splits each soluton eigenvector into two halves (which represent
the x- and y-component of the magnetisation, respectively).
"""
if fig.axes == []:
fig.add_subplot(2, 2, 1)
fig.add_subplot(2, 2, 2)
fig.add_subplot(2, 2, 3)
fig.add_subplot(2, 2, 4)
assert(len(fig.axes) == 4)
ax1, ax2, ax3, ax4 = fig.axes
N = len(w)
K = N // 2
assert(N == 2 * K)
# Scale the vector so that its maximum entry is 1.0
w_max = abs(w).max()
if w_max != 0.0:
w = w / w_max
fmt = fmt or ''
ax1.plot(w[:K].real, fmt, label=label)
ax3.plot(w[:K].imag, fmt, label=label)
ax2.plot(w[K:].real, fmt, label=label)
ax4.plot(w[K:].imag, fmt, label=label)
ax1.set_ylim(-1.1, 1.1)
ax2.set_ylim(-1.1, 1.1)
ax3.set_ylim(-1.1, 1.1)
ax4.set_ylim(-1.1, 1.1)
# NOTE: Don't change this list without adapting the "known_failures"
# in "eigensolvers_test.py" accordingly!
available_eigenproblems = [DiagonalEigenproblem(),
RingGraphLaplaceEigenproblem(),
Nanostrip1dEigenproblemFinmag(13e-12, 8e5, 0, 100),
]
| 24,580 | 32.217568 | 98 |
py
|
finmag
|
finmag-master/src/finmag/normal_modes/eigenmodes/eigenproblems_test.py
|
from __future__ import division
import pytest
import logging
import os
from eigenproblems import *
from eigensolvers import *
from helpers import is_diagonal_matrix
def test_assert_eigenproblems_were_defined():
"""
Check that `available_eigenproblems` is not the empty set and that
a few known eigenproblem types are contained in it.
"""
assert(set(available_eigenproblems) != set())
assert(all([isinstance(ep, AbstractEigenproblem)
for ep in available_eigenproblems]))
assert(any([isinstance(ep, DiagonalEigenproblem)
for ep in available_eigenproblems]))
class MockEigenproblem(AbstractEigenproblem):
eigvals = {0: 0.0,
1: 4.0,
2: 4.0,
3: 7.2,
4: 7.2,
5: 7.2,
6: 10.4,
}
def get_kth_analytical_eigenvalue(self, k, size=None):
return self.eigvals[k]
def get_kth_analytical_eigenvector(self, k, size):
return np.zeros(size)
class AbstractEigenproblemTest(object):
"""
This class provides generic tests that will be called from each of
the individual subclasses below (it won't be executed by py.test
directly, however).
"""
@pytest.mark.requires_X_display
def test_plot_analytical_solutions(self, tmpdir):
os.chdir(str(tmpdir))
self.eigenproblem.plot_analytical_solutions(
[0, 2, 5, 6], N=20, figsize=(12, 3), filename='solutions.png')
assert(os.path.exists('solutions.png'))
@pytest.mark.requires_X_display
def test_plot_computed_solutions(self, tmpdir):
os.chdir(str(tmpdir))
solver = ScipyLinalgEig()
self.eigenproblem.plot_computed_solutions(
[0, 2, 5, 6], solver=solver, N=50, dtype=float, tol_eigval=1e-1,
figsize=(12, 3), filename='solutions.png')
assert(os.path.exists('solutions.png'))
class TestDiagonalEigenproblem(AbstractEigenproblemTest):
def setup(self):
self.eigenproblem = DiagonalEigenproblem()
self.omega_ref = [1, 2, 3, 4]
self.num = 4
self.size = 10
self.w_ref = \
[[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]]
self.w_ref2 = \
[[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 2, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, -3.43, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1.173e-3, 0, 0, 0, 0, 0, 0]]
self.w_wrong = \
[[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0]]
self.eigenpairs_ref = zip(self.omega_ref, self.w_ref)
self.eigenpairs_wrong = zip(self.omega_ref, self.w_wrong)
def test_instantiate(self):
"""
Check that the matrices instantiated by DiagonalEigenproblem are
a diagonal matrix and `None` as expected.
"""
for N in [10, 20, 40]:
for dtype in [float, complex]:
A, M = self.eigenproblem.instantiate(N, dtype=dtype)
assert(is_diagonal_matrix(A))
assert(A.dtype == dtype)
assert(M == None)
def test_solve(self):
"""
Call 'self.solve()' with two different solvers and check that
the solutions are as expected.
"""
solver1 = ScipyLinalgEig(num=4)
solver2 = ScipySparseLinalgEigs(sigma=0.0, which='LM', num=4)
omega1, w1, _ = self.eigenproblem.solve(solver1, N=10, dtype=float)
omega2, w2, _ = self.eigenproblem.solve(solver2, N=10, dtype=complex)
assert(
self.eigenproblem.verify_eigenpairs_analytically(zip(omega1, w1)))
assert(
self.eigenproblem.verify_eigenpairs_analytically(zip(omega2, w2)))
def test_print_analytical_eigenvalues(self):
self.eigenproblem.print_analytical_eigenvalues(10, unit='Hz')
self.eigenproblem.print_analytical_eigenvalues(4, unit='KHz')
self.eigenproblem.print_analytical_eigenvalues(5, unit='MHz')
self.eigenproblem.print_analytical_eigenvalues(20, unit='GHz')
with pytest.raises(TypeError):
# Without explicitly specifying the 'unit' keyword the
# second argument will be interpreted as the problem size,
# which should lead to an error.
self.eigenproblem.print_analytical_eigenvalues(10, 'Hz')
def test_get_kth_analytical_eigenvalue(self):
for k in xrange(self.num):
omega = self.eigenproblem.get_kth_analytical_eigenvalue(k=k)
omega_ref = self.omega_ref[k]
assert(np.allclose(omega, omega_ref))
def test_get_analytical_eigenvalues(self):
omega = self.eigenproblem.get_analytical_eigenvalues(num=self.num)
assert(np.allclose(omega, self.omega_ref))
def test_get_kth_analytical_eigenvector(self):
for k in xrange(self.num):
w = self.eigenproblem.get_kth_analytical_eigenvector(
k=k, size=self.size)
w_ref = self.w_ref[k]
assert(np.allclose(w, w_ref))
def test_get_analytical_eigenvectors(self):
w = self.eigenproblem.get_analytical_eigenvectors(
num=self.num, size=self.size)
assert(np.allclose(w, self.w_ref))
def test_get_kth_analytical_eigenpair(self):
for k in xrange(self.num):
omega, w = self.eigenproblem.get_kth_analytical_eigenpair(
k=k, size=self.size)
omega_ref = self.omega_ref[k]
w_ref = self.w_ref[k]
assert(np.allclose(omega, omega_ref) and np.allclose(w, w_ref))
def test_get_analytical_eigenpairs(self):
omega, w = self.eigenproblem.get_analytical_eigenpairs(
num=self.num, size=self.size)
assert(np.allclose(omega, self.omega_ref))
assert(np.allclose(w, self.w_ref))
def test_get_analytical_eigenspace_basis(self):
N = self.size
omega1 = 1.0
omega4 = 4.0
omega6 = 6.0
eigenvec1 = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
eigenvec4 = [0, 0, 0, 1, 0, 0, 0, 0, 0, 0]
eigenvec6 = [0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
def assert_eigenspace_basis(esp, eigenvec):
esp = np.asarray(esp)
esp_ref = np.asarray([eigenvec])
assert(np.allclose(esp, esp_ref))
esp1 = self.eigenproblem.get_analytical_eigenspace_basis(omega1, N)
esp4 = self.eigenproblem.get_analytical_eigenspace_basis(omega4, N)
esp6 = self.eigenproblem.get_analytical_eigenspace_basis(omega6, N)
assert_eigenspace_basis(esp1, eigenvec1)
assert_eigenspace_basis(esp4, eigenvec4)
assert_eigenspace_basis(esp6, eigenvec6)
# Check that using a non-eigenvalue raises an exception
omega_wrong = 4.2
with pytest.raises(ValueError):
self.eigenproblem.get_analytical_eigenspace_basis(omega_wrong, N)
# Check that with a less strict tolerance we get the expected result
omega4b = 4.0001
esp4b = self.eigenproblem.get_analytical_eigenspace_basis(
omega4b, N, tol_eigval=1e-3)
assert_eigenspace_basis(esp4b, eigenvec4)
# Check some corner cases (e.g. where 'computed' eigenvalues are
# slightly smaller or larger than the exact ones).
a1 = 4.000001
a2 = 3.999999
a3 = 7.200001
a4 = 7.199999
mock_eigenproblem = MockEigenproblem()
esp1 = mock_eigenproblem.get_analytical_eigenspace_basis(
a1, size=50, tol_eigval=1e-3)
esp2 = mock_eigenproblem.get_analytical_eigenspace_basis(
a2, size=50, tol_eigval=1e-3)
esp3 = mock_eigenproblem.get_analytical_eigenspace_basis(
a3, size=50, tol_eigval=1e-3)
esp4 = mock_eigenproblem.get_analytical_eigenspace_basis(
a4, size=50, tol_eigval=1e-3)
assert(len(esp1) == 2)
assert(len(esp2) == 2)
assert(len(esp3) == 3)
assert(len(esp4) == 3)
def test_verify_eigenpair_numerically(self):
"""
Apply the method `verify_eigenpair_numerically()` to the
reference eigenpairs (which are known to be correct) and check
that it returns `True` (= succesful verification). Similarly,
check that it returns wrong on a set of wrong eigenpairs.
"""
# Check all correct eigenpairs (should succeed)
for k in xrange(self.num):
a = self.omega_ref[k]
v = self.w_ref[k]
res = self.eigenproblem.verify_eigenpair_numerically(a, v)
assert(res == True)
# Check a wrong eigenpair (should fail)
a = 3.0
v = std_basis_vector(1, self.size)
res = self.eigenproblem.verify_eigenpair_numerically(a, v, tol=1e-8)
assert(res == False)
with pytest.raises(ValueError):
# v should be a 1D vector, so this should raise an exception
v_wrong_shape = [[1, 2, 3], [4, 5, 6]]
self.eigenproblem.verify_eigenpair_numerically(1.0, v_wrong_shape)
def test_verify_eigenpairs_numerically(self):
assert(self.eigenproblem.verify_eigenpairs_numerically(
self.eigenpairs_ref) == True)
assert(self.eigenproblem.verify_eigenpairs_numerically(
self.eigenpairs_wrong) == False)
def test_verify_eigenpair_analytically(self):
"""
Apply the method `verify_eigenpair_analytically()` to the
reference eigenpairs (which are known to be correct) and check
that it returns `True` (= successful verification). Similarly,
check that it returns wrong on a set of wrong eigenpairs.
"""
# Check all correct eigenpairs (should succeed)
for k in xrange(self.num):
a = self.omega_ref[k]
v = self.w_ref[k]
res = self.eigenproblem.verify_eigenpair_analytically(a, v)
assert(res == True)
# Check a wrong eigenpair (should fail)
a = 3.0
v = std_basis_vector(1, self.size)
res = self.eigenproblem.verify_eigenpair_analytically(
a, v, tol_residual=1e-8, tol_eigval=1e-8)
assert(res == False)
with pytest.raises(TypeError):
# v should be a 1D vector, so this should raise an exception
v_wrong_shape = [[1, 2, 3], [4, 5, 6]]
self.eigenproblem.verify_eigenpair_analytically(1.0, v_wrong_shape)
def test_verify_eigenpairs_analytically(self):
assert(self.eigenproblem.verify_eigenpairs_analytically(
self.eigenpairs_ref) == True)
assert(self.eigenproblem.verify_eigenpairs_analytically(
self.eigenpairs_wrong) == False)
class TestRingGraphLaplaceEigenproblem(AbstractEigenproblemTest):
def setup(self):
self.eigenproblem = RingGraphLaplaceEigenproblem()
def test_instantiate(self):
"""
Check that the matrices instantiated by RingGraphLaplaceEigenproblem
are as expected.
"""
A4, M4 = self.eigenproblem.instantiate(N=4, dtype=float)
assert(M4 == None)
assert(np.allclose(A4, np.array([[2, -1, 0, -1],
[-1, 2, -1, 0],
[0, -1, 2, -1],
[-1, 0, -1, 2]])))
A5, M5 = self.eigenproblem.instantiate(N=5, dtype=complex)
assert(M5 == None)
assert(np.allclose(A5, np.array([[2, -1, 0, 0, -1],
[-1, 2, -1, 0, 0],
[0, -1, 2, -1, 0],
[0, 0, -1, 2, -1],
[-1, 0, 0, -1, 2]])))
for N in [10, 20, 40]:
for dtype in [float, complex]:
A, M = self.eigenproblem.instantiate(N, dtype=dtype)
assert(M == None)
A_ref = np.zeros((N, N), dtype=dtype)
A_ref += np.diag(2 * np.ones(N))
A_ref -= np.diag(np.ones(N - 1), k=1)
A_ref -= np.diag(np.ones(N - 1), k=-1)
A_ref[0, N - 1] = -1
A_ref[N - 1, 0] = -1
assert(np.allclose(A, A_ref))
assert(M == None)
class TestNanostrip1dEigenproblemFinmag(AbstractEigenproblemTest):
def setup(self):
self.eigenproblem = Nanostrip1dEigenproblemFinmag(
13e-12, 8e5, 0, 100, unit_length=1e-9)
| 12,635 | 37.175227 | 79 |
py
|
finmag
|
finmag-master/native/src/cvode/setup.py
|
#!/usr/bin/env python
import os
#$ python setup.py build_ext --inplace
# Set the environment variable SUNDIALS_PATH if sundials
# is installed in a non-standard location.
SUNDIALS_PATH = os.environ.get('SUNDIALS_PATH', '/usr')
print "[DDD] Using SUNDIALS_PATH='{}'".format(SUNDIALS_PATH)
from numpy.distutils.command import build_src
import Cython.Compiler.Main
build_src.Pyrex = Cython
build_src.have_pyrex = False
def have_pyrex():
import sys
try:
import Cython.Compiler.Main
sys.modules['Pyrex'] = Cython
sys.modules['Pyrex.Compiler'] = Cython.Compiler
sys.modules['Pyrex.Compiler.Main'] = Cython.Compiler.Main
return True
except ImportError:
return False
build_src.have_pyrex = have_pyrex
def configuration(parent_package='',top_path=None):
INCLUDE_DIRS = ['/usr/lib/openmpi/include/', os.path.join(SUNDIALS_PATH, 'include')]
LIBRARY_DIRS = [os.path.join(SUNDIALS_PATH, 'lib')]
LIBRARIES = ['sundials_cvodes', 'sundials_nvecparallel', 'sundials_nvecserial']
# PETSc
PETSC_DIR = os.environ.get('PETSC_DIR','/usr/lib/petsc')
PETSC_ARCH = os.environ.get('PETSC_ARCH', 'linux-gnu-c-opt')
if os.path.isdir(os.path.join(PETSC_DIR, PETSC_ARCH)):
INCLUDE_DIRS += [os.path.join(PETSC_DIR, 'include')]
LIBRARY_DIRS += [os.path.join(PETSC_DIR, PETSC_ARCH, 'lib')]
else:
raise Exception('Seems PETSC_DIR or PETSC_ARCH are wrong!')
LIBRARIES += [#'petscts', 'petscsnes', 'petscksp',
#'petscdm', 'petscmat', 'petscvec',
'petsc']
# PETSc for Python
import petsc4py
INCLUDE_DIRS += [petsc4py.get_include()]
print "[DDD] INCLUDE_DIRS = {}".format(INCLUDE_DIRS)
# Configuration
from numpy.distutils.misc_util import Configuration
config = Configuration('', parent_package, top_path)
config.add_extension('cvode_petsc',
sources = ['cvode_petsc.pyx'],
depends = [''],
include_dirs=INCLUDE_DIRS + [os.curdir],
libraries=LIBRARIES,
library_dirs=LIBRARY_DIRS,
runtime_library_dirs=LIBRARY_DIRS)
config.add_extension('llg_petsc',
sources = ['llg_petsc.pyx', 'llg.c'],
depends = [''],
include_dirs=INCLUDE_DIRS + [os.curdir],
libraries=LIBRARIES,
library_dirs=LIBRARY_DIRS,
runtime_library_dirs=LIBRARY_DIRS)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| 2,754 | 35.733333 | 88 |
py
|
finmag
|
finmag-master/native/src/treecode_bem/setup.py
|
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import os
#python setup.py build_ext --inplace
ext_modules = [
Extension("treecode_bem",
sources = ['common.c',
'bem_pbc.c',
'treecode_bem_I.c',
'treecode_bem_II.c',
'treecode_bem_lib.pyx'],
include_dirs = [numpy.get_include()],
libraries=['m'],
#libraries=['m','gomp'],
extra_compile_args=["-fopenmp"],
#extra_link_args=["-g"],
)
]
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 746 | 24.758621 | 51 |
py
|
finmag
|
finmag-master/native/src/fast_sum_lib/setup.py
|
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import os
#python setup.py build_ext --inplace
#NFFT_DIR = os.path.expanduser('~/nfft-3.2.0')
ext_modules = [
Extension("fast_sum_lib",
sources = ['fast_sum.c','fast_sum_lib.pyx'],
include_dirs = [numpy.get_include()],
libraries=['m'],
#extra_compile_args=["-fopenmp"],
#extra_link_args=["-g"],
)
]
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 597 | 22 | 58 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.