Exemplo n.º 1
0
def test_anisotropy_energy_analytical(fixt):
    """
    Compare one UniaxialAnisotropy energy with the corresponding analytical result.

    The magnetisation is m = (0, sqrt(1 - x^2), x) and the easy axis still
    a = (0, 0, 1). The squared dot product in the energy integral thus gives
    dot(a, m)^2 = x^2. Integrating x^2 gives (x^3)/3 and the analytical
    result with the constants we have chosen is 1 - 1/3 = 2/3.

    """
    mesh = df.UnitCubeMesh(1, 1, 1)
    functionspace = df.VectorFunctionSpace(mesh, "Lagrange", 1)
    K1 = 1
    Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1)
    a = df.Constant((0, 0, 1))
    m = Field(functionspace)
    m.set(df.Expression(("0", "sqrt(1 - pow(x[0], 2))", "x[0]"), degree=1))
    anis = UniaxialAnisotropy(K1, a)
    anis.setup(m, Ms)

    E = anis.compute_energy()
    expected_E = float(2) / 3

    print "With m = (0, sqrt(1-x^2), x), expecting E = {}. Got E = {}.".format(
        expected_E, E)
    #assert abs(E - expected_E) < TOLERANCE
    assert np.allclose(E, expected_E, atol=1e-14, rtol=TOLERANCE)
Exemplo n.º 2
0
def test_anisotropy_field_supported_methods(fixt):
    """
    Check that all supported methods give the same results as the default method.

    """
    TOLERANCE = 1e-13

    fixt["m"].set(df.Constant((1 / np.sqrt(2), 0, 1 / np.sqrt(2))))
    H_default = fixt["anis"].compute_field()

    supported_methods = list(UniaxialAnisotropy._supported_methods)
    # No need to compare default method with itself.
    supported_methods.remove(fixt["anis"].method)

    for method in supported_methods:
        anis = UniaxialAnisotropy(fixt["K1"], fixt["a"], method=method)
        anis.setup(fixt["m"], fixt["Ms"])
        H = anis.compute_field()
        print(
            textwrap.dedent("""
                  With method '{}',
                      expecting: H = {},
                      got:       H = {}.
                  """.format(method,
                             H_default.reshape((3, -1)).mean(axis=1),
                             H.reshape((3, -1)).mean(axis=1))))
        assert np.allclose(H, H_default, atol=0, rtol=TOLERANCE)
Exemplo n.º 3
0
def create_simulation(mesh):

    sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)

    sim.set_m((1, 0, 0))
    sim.add(UniaxialAnisotropy(-1e5, (0, 0, 1), name='Kp'))
    sim.add(UniaxialAnisotropy(1e4, (1, 0, 0), name='Kx'))

    return sim
Exemplo n.º 4
0
def compute_finmag_anis(m_gen, Ms, K1, axis, dolfin_mesh):
    S3 = df.VectorFunctionSpace(dolfin_mesh, "Lagrange", 1, dim=3)
    coords = np.array(zip(*dolfin_mesh.coordinates()))
    m0 = m_gen(coords).flatten()
    m = Field(S3)
    m.set_with_numpy_array_debug(m0)

    anis = UniaxialAnisotropy(K1, axis)
    anis.setup(m, Field(df.FunctionSpace(dolfin_mesh, 'DG', 0), Ms))

    anis_field = df.Function(S3)
    anis_field.vector()[:] = anis.compute_field()
    return anis_field
Exemplo n.º 5
0
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()
Exemplo n.º 6
0
def fixt():
    """
    Create an UniaxialAnisotropy object that will be re-used during testing.

    """
    mesh = df.UnitCubeMesh(1, 1, 1)
    functionspace = df.VectorFunctionSpace(mesh, "Lagrange", 1)
    K1 = 1
    Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1)
    a = df.Constant((0, 0, 1))
    m = Field(functionspace)
    anis = UniaxialAnisotropy(K1, a)
    anis.setup(m, Ms)
    return {"anis": anis, "m": m, "a": a, "Ms": Ms, "K1": K1}
Exemplo n.º 7
0
def create_simulation():

    from finmag.util.meshes import ellipsoid
    #mesh = df.IntervalMesh(10,0,30)
    #mesh = df.RectangleMesh(0,0,10,2,5,1)
    mesh = ellipsoid(30, 10, 10, maxh=3.0)

    sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)

    sim.set_m((1, 1, 1))
    sim.add(Exchange(1.3e-11))
    sim.add(UniaxialAnisotropy(-1e5, (0, 0, 1), name='Kp'))
    sim.add(UniaxialAnisotropy(1e4, (1, 0, 0), name='Kx'))

    return sim
Exemplo n.º 8
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
Exemplo n.º 9
0
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))
Exemplo n.º 10
0
def test_interaction_accepts_name(fixt):
    """
    Check that the interaction accepts a 'name' argument and has a 'name' attribute.
    """
    K1 = 1
    a = df.Constant((0, 0, 1))

    anis = UniaxialAnisotropy(K1, a, name='MyAnisotropy')
    assert hasattr(anis, 'name')
Exemplo n.º 11
0
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())
Exemplo n.º 12
0
def test_anisotropy():
    mesh = df.IntervalMesh(1, 0, 1)
    sim = Simulation(mesh, Ms, unit_length=1e-9)
    sim.set_m((mx, my, mz))

    sim.add(UniaxialAnisotropy(K1, axis=[1, 0, 0]))

    expected = 2 * K1 / (mu0 * Ms) * mx
    field = sim.effective_field()
    assert abs(field[0] - expected) / Ms < 1e-15
Exemplo n.º 13
0
def test_spatially_varying_anisotropy_axis(tmpdir, debug=False):
    Ms = 1e6
    A = 1.3e-11
    K1 = 6e5
    lb = bloch_parameter(A, K1)

    unit_length = 1e-9
    nx = 20
    Lx = nx * lb / unit_length
    mesh = df.IntervalMesh(nx, 0, Lx)

    # anisotropy axis goes from (0, 1, 0) at x=0 to (1, 0, 0) at x=Lx
    expr_a = df.Expression(("x[0] / sqrt(pow(x[0], 2) + pow(Lx-x[0], 2))",
                            "(Lx-x[0]) / sqrt(pow(x[0], 2) + pow(Lx-x[0], 2))",
                            "0"), Lx=Lx, degree=1)
    # in theory, a discontinuous Galerkin (constant over the cell) is a good
    # choice to represent material parameters. In this case though, the
    # parameter varies linearly, so we use the usual CG.
    V = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
    a = Field(V, expr_a)

    sim = Simulation(mesh, Ms, unit_length)
    sim.set_m((1, 1, 0))
    sim.add(UniaxialAnisotropy(K1, a))
    sim.relax()

    # probe the easy axis and the magnetisation along the interval
    points = 100
    xs = np.linspace(0, Lx, points)
    axis_xs = np.zeros((points, 3))
    m_xs = np.zeros((points, 3))

    for i, x in enumerate(xs):
        axis_xs[i] = a(x)
        m_xs[i] = sim.m_field(x)

    # we want to the magnetisation to follow the easy axis
    # it does so, except at x=0, what is happening there?
    diff = np.abs(m_xs - axis_xs)
    assert diff.max() < 0.02

    if debug:
        old = os.getcwd()
        os.chdir(tmpdir)
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(xs, axis_xs[:, 0], "b+", label="a_x")
        ax.plot(xs, m_xs[:, 0], "r--", label="m_x")
        ax.legend(loc="upper left")
        ax.set_ylim((0, 1.05))
        ax.set_xlabel("x (nm)")
        plt.savefig('spatially_varying_easy_axis.png')
        plt.close()
        sim.m_field.save_pvd('spatially_varying_easy_axis.pvd')
        os.chdir(old)
Exemplo n.º 14
0
def run_simulation(plot=False):
    mu0 = 4.0 * np.pi * 10**-7  # vacuum permeability N/A^2
    Ms = 1.0e6  # saturation magnetisation A/m
    A = 13.0e-12  # exchange coupling strength J/m
    Km = 0.5 * mu0 * Ms**2  # magnetostatic energy density scale kg/ms^2
    lexch = (A / Km)**0.5  # exchange length m
    unit_length = 1e-9
    K1 = Km

    L = lexch / unit_length
    nx = 10
    Lx = nx * L
    ny = 1
    Ly = ny * L
    nz = 30
    Lz = nz * L
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(Lx, Ly, Lz), nx, ny, nz)

    # Anisotropy easy axis is (0, 0, 1) in the lower half of the film and
    # (1, 0, 0) in the upper half. This is a toy model of the exchange spring
    # systems that Bob Stamps is working on.
    boundary = Lz / 2.0
    expr_a = df.Expression(("x[2] <= b ? 0 : 1", "0", "x[2] <= b ? 1 : 0"),
                           b=boundary,
                           degree=1)
    V = df.VectorFunctionSpace(mesh, "DG", 0, dim=3)
    a = Field(V, expr_a)

    sim = Simulation(mesh, Ms, unit_length)
    sim.set_m((1, 0, 1))
    sim.add(UniaxialAnisotropy(K1, a))
    sim.add(Exchange(A))
    sim.relax()

    if plot:
        points = 200
        zs = np.linspace(0, Lz, points)
        axis_zs = np.zeros((points, 3))  # easy axis probed along z-axis
        m_zs = np.zeros((points, 3))  # magnetisation probed along z-axis

        for i, z in enumerate(zs):
            axis_zs[i] = a((Lx / 2.0, Ly / 2.0, z))
            m_zs[i] = sim.m_field((Lx / 2.0, Ly / 2.0, z))

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(zs, axis_zs[:, 0], "-o", label="a_x")
        ax.plot(zs, axis_zs[:, 2], "-x", label="a_z")
        ax.plot(zs, m_zs[:, 0], "-", label="m_x")
        ax.plot(zs, m_zs[:, 2], "-", label="m_z")
        ax.set_xlabel("z (nm)")
        ax.legend(loc="upper left")
        plt.savefig(os.path.join(MODULE_DIR, "profile.png"))
        sim.m_field.save_pvd(os.path.join(MODULE_DIR, 'exchangespring.pvd'))
Exemplo n.º 15
0
def test_anisotropy_energy_simple_configurations(fixt, m, expected_E):
    """
    Test some parallel and orthogonal configurations of m and a.

    """
    mesh = df.UnitCubeMesh(1, 1, 1)
    functionspace = df.VectorFunctionSpace(mesh, "Lagrange", 1)
    K1 = 1
    Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1)
    a = df.Constant((0, 0, 1))
    m_field = Field(functionspace)
    m_field.set(df.Constant(m))
    anis = UniaxialAnisotropy(K1, a)
    anis.setup(m_field, Ms)

    E = anis.compute_energy()

    print "With m = {}, expecting E = {}. Got E = {}.".format(m, expected_E, E)
    #assert abs(E - expected_E) < TOLERANCE
    assert np.allclose(E, expected_E, atol=1e-14, rtol=TOLERANCE)
Exemplo n.º 16
0
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)
Exemplo n.º 17
0
def run_simulation(lfactor, m_init, m_init_name=""):
    L = lfactor * lexch
    divisions = int(round(lfactor * 2))  # that magic number influences L
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(L, L, L), divisions,
                      divisions, divisions)

    exchange = Exchange(A)
    anisotropy = UniaxialAnisotropy(K1, [0, 0, 1])
    demag = Demag()

    sim = Simulation(mesh, Ms)
    sim.set_m(m_init)
    sim.add(exchange)
    sim.add(anisotropy)
    sim.add(demag)
    sim.relax()

    # Save average magnetisation.
    mx, my, mz = sim.m_average
    with open(os.path.join(MODULE_DIR, "data_m.txt"), "a") as f:
        t = time.asctime()
        f.write("{} {} {} {} {} {}\n".format(m_init_name, lfactor, mx, my, mz,
                                             t))

    # Save energies.
    # We could call sim.total_energy, but we want the individual contributions.
    e_exc = exchange.compute_energy() / (sim.Volume * Km)
    e_anis = anisotropy.compute_energy() / (sim.Volume * Km)
    e_demag = demag.compute_energy() / (sim.Volume * Km)
    e_total = e_exc + e_anis + e_demag  # relative total energy density

    with open(os.path.join(MODULE_DIR, "data_energies.txt"), "a") as f:
        t = time.asctime()
        f.write("{} {} {} {} {} {} {}\n".format(m_init_name, lfactor, e_total,
                                                e_exc, e_anis, e_demag, t))

    return e_total
Exemplo n.º 18
0
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))
Exemplo n.º 19
0
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
Exemplo n.º 20
0
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)
D = 3e-3
Ms = 0.86e6
Ku = 0.4e6
initial_sk_diam = 10

sim = Sim(mesh, Ms=Ms, unit_length=1e-9, name="1d_Cnv")
sim.set_m((0, 0.1, 0.9))

# -----------------------------------------------------------------------------

# Exchange Energy
sim.add(Exchange(A))
# DMI
sim.add(DMI(D, dmi_type='interfacial'))
# Uniaxial Anisotropy
sim.add(UniaxialAnisotropy(Ku, (0, 0, 1), name='Ku'))

# -----------------------------------------------------------------------------

sim.do_precession = False
sim.alpha = 0.9

if not os.path.exists('vtks'):
    # shutil.rmtree('vtks')
    os.mkdir('vtks')

sim.relax()
sim.save_vtk(filename='vtks/1d_Cnv.pvd', overwrite=True)
sim.save_field('m', '1d_Cnv.npy', overwrite=True)

xs = sim.mesh.coordinates()
Exemplo n.º 22
0
else:
    sim = Sim(mesh, args.Ms, unit_length=1e-9, pbc='2d', name=args.sim_name)

# Add energies
sim.add(Exchange(args.A))

if args.D != 0:
    sim.add(DMI(args.D * 1e-3, dmi_type='interfacial'))

# Zeeman field in the z direction (in Tesla)
# if it is not zero
if args.B != 0:
    sim.add(Zeeman((0, 0, args.B / finmag.util.consts.mu0)))

if args.k_u:
    sim.add(UniaxialAnisotropy(args.k_u, (0, 0, 1), name='Ku'))

# No Demag in 2D
# sim.add(Demag())

# sim.llg.presession = False

if args.alpha:
    sim.alpha = args.alpha

# Pin the magnetisation vectors at the borders if specified
if args.pin_borders:

    def borders_pinning(pos):
        x, y = pos[0], pos[1]
Exemplo n.º 23
0
def test_domain_wall_profile(do_plot=False):

    simplices = 500
    L = 504e-9
    dim = 3
    mesh = df.IntervalMesh(simplices, 0, L)
    V = df.VectorFunctionSpace(mesh, "CG", 1, dim=dim)

    m0 = df.Function(V)
    coor = mesh.coordinates()
    n = len(m0.vector().array())

    print "Double check that the length of the vectors are equal: %g and %g" \
        % (n, len(coor) * dim)
    assert n == len(coor) * dim

    # Setup LLG
    sim = Sim(mesh, Ms)
    exchange = Exchange(A)
    sim.add(exchange)
    anisotropy = UniaxialAnisotropy(K1, (0, 0, 1))
    sim.add(anisotropy)

    # TODO: Find out how one are supposed to pin.
    # llg.pins = [0,1,-2,-1] # This is not so good
    # MA: because you pin by index -2 and -1 won't work like you'd expect.

    sim.alpha = 1.0

    # set initial magnetization
    x, y, z = M0(coor)
    m0.vector()[:] = np.array([x, y, z]).reshape(n)
    sim.set_m(np.array([x, y, z]).reshape(n))

    # Time integration
    # f=open('data.txt','w')
    for t in np.arange(0.0, 2e-10, 1e-11):
        sim.run_until(t)
        #Eani = anisotropy.compute_energy()/L
        #Eex = exchange.compute_energy()/L
        #f.write('%g\t%g\t%g\n' % (r.t,Eani,Eex))
        print "Integrating time: %g" % t
    # f.close()
    print timer

    mz = []
    x = np.linspace(0, L, simplices + 1)
    for xpos in x:
        mz.append(sim.m_field.probe(xpos)[2])
    mz = np.array(mz) * Ms

    if do_plot:
        # Plot magnetisation in z-direction
        pylab.plot(x, mz, 'o', label='finmag')
        pylab.plot(x, Mz_exact(x), '-', label='analytic')
        pylab.legend(("Finmag", "Analytical"))
        pylab.title("Domain wall example - Finmag vs analytical solution")
        pylab.xlabel("Length")
        pylab.ylabel("M.z")
        pylab.savefig('1d-domain-wall-profile.png')

    try:
        import scipy.optimize
    except ImportError:
        pass
    else:
        popt, pcov = scipy.optimize.curve_fit(
            Mz_exact, x, mz, p0=(x0 * 1.1, A * 1.1, Ms * 1.1))
        print "popt=", popt

        fittedx0, fittedA, fittedMs = popt
        print "Error in fitted x0: %9.7f%%" % ((fittedx0 - x0) / x0 * 100)
        print "Error in fitted Ms: %9.7f%%" % ((fittedMs - Ms) / Ms * 100)
        print "Error in fitted A : %9.7f%%" % ((fittedA - A) / A * 100)
        print "fitted A  : %9g" % (fittedA)
        print "correct A : %9g" % (A)
        print "difference A : %9g" % (fittedA - A)
        print "rel difference A : %9g" % ((fittedA - A) / A)
        print "quotient A/fittedA and fittedA/A : %9g %g" % (A / fittedA, fittedA / A)
        assert abs(fittedA - A) / A < 0.004, "Fitted A too inaccurate"

    # Maximum deviation:
    maxdiff = max(abs(mz - Mz_exact(x)))
    print "Absolute deviation in Mz", maxdiff
    assert maxdiff < 1200
    maxreldiff = maxdiff / max(Mz_exact(x))
    print "Relative deviation in Mz", maxreldiff
    assert maxreldiff < 0.0009
Exemplo n.º 24
0
A = 1e-11
K1 = 3e5
K1_axis = (0, 0, 1)
H_baseline = 2 * K1 / Ms_Tesla
H_mult = [0.95, 1.2, 2.8]
H_axis = -spherical_to_cartesian((1.0, 1.0 * np.pi / 180, 0))
mesh = cylinder(6, 20, 2.0)

start_clock = time.clock()

for H in H_mult:
    sim = Simulation(mesh, Ms, unit_length=1e-9)
    sim.alpha = 0.02
    sim.set_m(K1_axis)
    sim.add(Exchange(A))
    sim.add(UniaxialAnisotropy(K1, K1_axis))
    sim.add(Demag())
    sim.add(Zeeman(H * H_baseline * H_axis))

    print "Running simulation for H = {} T.".format(H)
    print sim.mesh_info()

    t = 0
    dt = 1e-12
    t_failsafe = 2e-9
    dt_output = 100e-12

    ts = []
    mzs = []
    while True:
        sim.run_until(t)
Exemplo n.º 25
0
from finmag import NormalModeSimulation as Sim
from finmag.energies import Exchange, DMI, UniaxialAnisotropy, Zeeman
from finmag.util.dmi_helper import find_skyrmion_center_2d
from finmag.util.helpers import set_logging_level
from finmag.util import meshes
import finmag

rdir = '../results/relax'
os.chdir(rdir)

h5_file = df.HDF5File(df.mpi_comm_world(), 'relaxed-nanotrack-1e-7.h5', 'r')
mesh = df.Mesh()
h5_file.read(mesh, 'mesh', False)

sim = Sim(mesh=mesh, Ms=5.8e5, unit_length=1e-9, pbc=None)
sim.add(UniaxialAnisotropy(K1=6e5, axis=[0, 0, 1]))
sim.add(Exchange(A=1.5e-11))
sim.add(DMI(D=3e-3))
sim.add(Zeeman((0, 0, 1e5)))
sim.alpha = 0.5

print('Trying to load relaxed state')
m = hlp.load_h5_field(sim, 'relaxed-nanotrack-1e-7.h5')
sim.set_m(m)
sim.do_precession = False

print('Computing eigenmodes!\n\n\n')
n_eigenmodes = 50  # Calculate the first 50 eigenmodes.
complex_freqs = sim.compute_normal_modes(n_values=n_eigenmodes)
f_array = np.real(complex_freqs[0])