예제 #1
0
def ring_down(m0=(1, 0.01, 0), pbc=None):

    n = 49

    assert n >= 1 and n % 2 == 1

    Ms = 8.6e5

    sim = Simulation(mesh, Ms, unit_length=1e-9, name='dy', pbc='1d')
    sim.alpha = 1e-3

    sim.set_m(m0)
    sim.set_tol(1e-8, 1e-8)

    parameters = {
        'absolute_tolerance': 1e-10,
        'relative_tolerance': 1e-10,
        'maximum_iterations': int(1e5)
    }

    Ts = []
    for i in range(-n / 2 + 1, n / 2 + 1):
        Ts.append((10. * i, 0, 0))

    demag = Demag(Ts=Ts)

    demag.parameters['phi_1'] = parameters
    demag.parameters['phi_2'] = parameters

    sim.add(demag)
    sim.add(Exchange(1.3e-11))

    sim.schedule('save_ndt', every=2e-12)

    sim.run_until(4e-9)
예제 #2
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
예제 #3
0
def run_finmag(demagsolver):
    """Run the finmag simulation and store data in (demagsolvertype)averages.txt."""

    sim = Sim(mesh, Ms, unit_length=unit_length)
    sim.alpha = 0.5
    sim.set_m((1, 0, 1))

    exchange = Exchange(13.0e-12)
    sim.add(exchange)
    demag = Demag(solver=demagsolver)
    sim.add(demag)

    fh = open(os.path.join(MODULE_DIR, demagsolver + "averages.txt"), "w")
    fe = open(os.path.join(MODULE_DIR, demagsolver + "energies.txt"), "w")

    # Progressbar
    bar = pb.ProgressBar(maxval=60, \
                    widgets=[pb.ETA(), pb.Bar('=', '[', ']'), ' ', pb.Percentage()])

    logger.info("Time integration")
    times = np.linspace(0, 3.0e-10, 61)
    #times = np.linspace(0, 3.0e-10, 100000)
    for counter, t in enumerate(times):
        bar.update(counter)

        # Integrate
        sim.run_until(t)
        print counter
        print("press return to continue")
        _ = raw_input()

        # Save averages to file
        mx, my, mz = sim.m_average
        fh.write(str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")

        # Energies
        E_e = exchange.compute_energy()
        E_d = demag.compute_energy()
        fe.write(str(E_e) + " " + str(E_d) + "\n")

        # Energy densities
        if counter == 10:
            exch_energy = exchange.energy_density_function()
            demag_energy = demag.demag.energy_density_function()
            finmag_exch, finmag_demag = [], []
            R = range(100)
            for i in R:
                finmag_exch.append(exch_energy([15, 15, i]))
                finmag_demag.append(demag_energy([15, 15, i]))
            # Store data
            np.save(
                os.path.join(MODULE_DIR,
                             "finmag%s_exch_density.npy" % demagsolver),
                np.array(finmag_exch))
            np.save(
                os.path.join(MODULE_DIR,
                             "finmag%s_demag_density.npy" % demagsolver),
                np.array(finmag_demag))
    fh.close()
    fe.close()
예제 #4
0
def compute_field(mesh, nx=1, ny=1, m0=(1, 0, 0), pbc=None):

    Ms = 1e6
    sim = Simulation(mesh, Ms, unit_length=1e-9, name='dy', pbc=pbc)

    sim.set_m(m0)

    parameters = {
        'absolute_tolerance': 1e-10,
        'relative_tolerance': 1e-10,
        'maximum_iterations': int(1e5)
    }

    demag = Demag(macrogeometry=MacroGeometry(nx=nx, ny=ny))

    demag.parameters['phi_1'] = parameters
    demag.parameters['phi_2'] = parameters

    sim.add(demag)

    field = sim.llg.effective_field.get_dolfin_function('Demag')

    # XXX TODO: Would be good to compare all the field values, not
    #           just the value at a single point!  (Max, 25.7.2014)
    return field(0, 0, 0) / Ms
예제 #5
0
파일: energy.py 프로젝트: whshangl/finmag
def relax_system():
    Ms = 8.6e5
    sim = Simulation(mesh, Ms, unit_length=1e-9, name = 'dy')
    
    sim.alpha = 0.001
    sim.set_m(np.load('m_000088.npy'))
    
    #sim.set_tol(1e-6, 1e-6)

    A = 1.3e-11
    
    sim.add(Exchange(A))
    
    
    parameters = {
            'absolute_tolerance': 1e-10,
            'relative_tolerance': 1e-10,
            'maximum_iterations': int(1e5)
    }
    
    demag = Demag()
    
    demag.parameters['phi_1'] = parameters
    demag.parameters['phi_2'] = parameters
    
    print demag.parameters
    
    sim.add(demag)
    
    sim.schedule('save_ndt', every=2e-12)
    sim.schedule('save_vtk', every=2e-12, filename='vtks/m.pvd')
    sim.schedule('save_m', every=2e-12, filename='npys/m.pvd')
    
    sim.run_until(1e-9)
예제 #6
0
파일: run.py 프로젝트: whshangl/finmag
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))
예제 #7
0
def test_dmi_pbc2d_1D(plot=False):
    def m_init_fun(p):
        if p[0] < 10:
            return [0.5, 0, 1]
        else:
            return [-0.5, 0, -1]

    mesh = df.RectangleMesh(df.Point(0, 0), df.Point(20, 2), 10, 1)
    m_init = vector_valued_function(m_init_fun, mesh)

    Ms = 8.6e5
    sim = Simulation(mesh, Ms, pbc='2d', unit_length=1e-9)

    sim.set_m(m_init_fun)

    A = 1.3e-11
    D = 5e-3
    sim.add(Exchange(A))
    sim.add(DMI(D))

    sim.relax(stopping_dmdt=0.0001)

    if plot:
        sim.m_field.plot_with_dolfin()

    mx = [sim.m_field.probe([x + 0.5, 1])[0] for x in range(20)]

    assert np.max(np.abs(mx)) < 1e-6
예제 #8
0
def run_finmag():
    # Setup
    setupstart = time.time()
    mesh = df.Box(0, 0, 0, 30, 30, 100, 15, 15, 50)
    sim = Simulation(mesh, Ms=0.86e6, unit_length=1e-9)
    sim.set_m((1, 0, 1))
    demag = Demag("FK")
    demag.parameters["poisson_solver"]["method"] = "cg"
    demag.parameters["poisson_solver"]["preconditioner"] = "jacobi"
    demag.parameters["laplace_solver"]["method"] = "cg"
    demag.parameters["laplace_solver"]["preconditioner"] = "bjacobi"
    sim.add(demag)
    sim.add(Exchange(13.0e-12))

    # Dynamics
    dynamicsstart = time.time()
    sim.run_until(3.0e-10)
    endtime = time.time()

    # Write output to results.txt
    output = open(os.path.join(MODULE_DIR, "results.txt"), "a")
    output.write("\nBackend %s:\n" % df.parameters["linear_algebra_backend"])
    output.write("\nSetup: %.3f sec.\n" % (dynamicsstart - setupstart))
    output.write("Dynamics: %.3f sec.\n\n" % (endtime - dynamicsstart))
    output.write(str(default_timer))
    output.close()
예제 #9
0
def test_current_time():
    size = 20e-9
    simplices = 4
    mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(size, size, size), simplices,
                      simplices, simplices)

    Ms = 860e3
    A = 13.0e-12

    sim = Sim(mesh, Ms)
    sim.set_m((1, 0, 0))
    sim.add(Exchange(A))
    sim.add(Demag())

    t = 0.0
    t_max = 1e-10
    dt = 1e-12

    while t <= t_max:
        t += dt
        sim.run_until(t)
        # cur_t is equal to whatever time the integrator decided to probe last
        assert not sim.integrator.cur_t == 0.0
        # t is equal to our current simulation time
        assert abs(sim.t - t) < epsilon
예제 #10
0
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
예제 #11
0
def test_thin_film_demag_against_real_demag():
    sim = Sim(
        df.BoxMesh(df.Point(0, 0, 0), df.Point(500e-9, 500e-9, 1e-9), 50, 50,
                   1), Ms)
    sim.set_m((0, 0, 1))

    tfdemag = ThinFilmDemag()
    sim.add(tfdemag)
    H_tfdemag = tfdemag.compute_field().view().reshape((3, -1)).mean(1)
    demag = Demag()
    sim.add(demag)
    H_demag = demag.compute_field().view().reshape((3, -1)).mean(1)

    diff = np.abs(H_tfdemag - H_demag) / Ms
    print "Standard Demag:\n", H_demag
    print "ThinFilmDemag:\n", H_tfdemag
    print "Difference relative to Ms:\n", diff
    assert np.allclose(H_tfdemag, H_demag, atol=0.05 * Ms)  # 5% of Ms

    sim.set_m((1, 0, 0))
    H_tfdemag = tfdemag.compute_field().view().reshape((3, -1)).mean(1)
    H_demag = demag.compute_field().view().reshape((3, -1)).mean(1)

    print "Running again, changed m in the meantime."
    diff = np.abs(H_tfdemag - H_demag) / Ms
    print "Standard Demag:\n", H_demag
    print "ThinFilmDemag:\n", H_tfdemag
    print "Difference relative to Ms:\n", diff
    assert np.allclose(H_tfdemag, H_demag, atol=0.005 * Ms)  # 0.5% of Ms
예제 #12
0
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()
예제 #13
0
def compute_field(n=1, m0=(1, 0, 0), pbc=None):

    assert n >= 1 and n % 2 == 1

    Ms = 1e6
    sim = Simulation(mesh, Ms, unit_length=1e-9, name='dy', pbc=pbc)

    sim.set_m(m0)

    parameters = {
        'absolute_tolerance': 1e-10,
        'relative_tolerance': 1e-10,
        'maximum_iterations': int(1e5)
    }

    Ts = []
    for i in range(-n / 2 + 1, n / 2 + 1):
        Ts.append((10. * i, 0, 0))

    demag = Demag(Ts=Ts)

    demag.parameters['phi_1'] = parameters
    demag.parameters['phi_2'] = parameters

    sim.add(demag)

    sim.set_m((1, 0, 0))
    field1 = sim.llg.effective_field.get_dolfin_function('Demag')

    sim.set_m((0, 0, 1))
    field2 = sim.llg.effective_field.get_dolfin_function('Demag')

    return (field1(0, 0, 0) / Ms, field2(0, 0, 0) / Ms)
예제 #14
0
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()
예제 #15
0
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)
예제 #16
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
예제 #17
0
def angles_after_a_nanosecond(initial_M, pins=[]):
    sim = Sim(mesh, Ms)
    sim.set_m(initial_M, L=length)
    sim.add(Exchange(A))
    sim.pins = pins
    sim.run_until(1e-9)

    m = vectors(sim.m)
    angles = np.array([angle(m[i], m[i + 1]) for i in xrange(len(m) - 1)])
    return angles
예제 #18
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
예제 #19
0
def test_deviations_over_alpha_and_tol(number_of_alphas=5, do_plot=False):
    alphas = numpy.linspace(0.01, 1.00, number_of_alphas)

    max_deviationss = []
    for rtol_power_of_ten in rtols_powers_of_ten:
        rtol = pow(10, rtol_power_of_ten)
        print "#### New series for rtol={0}. ####".format(rtol)

        # One entry in this array corresponds to the maximum deviation between
        # the analytical solution and the computed solution for one value of alpha.
        max_deviations = []
        for alpha in alphas:
            print "Solving for alpha={0}.".format(alpha)

            sim = Simulation(mesh, 1, unit_length=1e-9)
            sim.alpha = alpha
            sim.set_m((1, 0, 0))
            sim.add(Zeeman((0, 0, 1e5)))

            ts = numpy.linspace(0, 1e-9, num=50)
            ys = odeint(sim.llg.solve_for,
                        sim.llg._m_field.get_numpy_array_debug(),
                        ts,
                        rtol=rtol,
                        atol=rtol)

            # One entry in this array corresponds to the deviation between the two
            # solutions for one particular moment during the simulation.
            deviations = []
            M_analytical = make_analytic_solution(1e5, alpha, sim.gamma)
            for i in range(len(ts)):
                M_computed = numpy.mean(ys[i].reshape((3, -1)), 1)
                M_ref = M_analytical(ts[i])
                # The difference of the two vectors has 3 components. The
                # deviation is the average over these components.
                deviation = numpy.mean(numpy.abs(M_computed - M_ref))
                assert deviation < TOLERANCE
                deviations.append(deviation)

            # This represents the addition of one point to the graph.
            max_deviations.append(numpy.max(deviations))

        # This represents one additional series in the graph.
        max_deviationss.append(max_deviations)

    if do_plot:
        for i in range(len(rtols_powers_of_ten)):
            label = r"$rtol=1\cdot 10^{" + str(rtols_powers_of_ten[i]) + r"}$"
            plt.plot(alphas, max_deviationss[i], ".", label=label)
        plt.legend()
        plt.title(r"Influence of $\alpha$ and rtol on the Deviation")
        plt.ylabel("deviation")
        plt.xlabel(r"$\alpha$")
        plt.ylim((0, 1e-6))
        plt.savefig(os.path.join(MODULE_DIR, "deviation_over_alpha_rtols.pdf"))
예제 #20
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)
예제 #21
0
파일: run.py 프로젝트: whshangl/finmag
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'))
예제 #22
0
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))
예제 #23
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()
예제 #24
0
def create_sim(mesh):

    Ms = 3.84e5  # A/m
    A = 8.78e-12  # J/m
    D = 1.58e-3  # J/m**2

    sim = Sim(mesh, Ms, unit_length=1e-9)
    sim.set_m((0, 0, 1))
    sim.set_tol(reltol=1e-10, abstol=1e-10)

    sim.add(Exchange(A))
    sim.add(DMI(D))

    return sim
예제 #25
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)
예제 #26
0
def compare_with_demag_from_initial_m(H_gen, m_init, atol=0, rtol=0):
    sim = Sim(df.UnitCubeMesh(2, 2, 2), Ms, unit_length=1e-9)
    sim.set_m(m_init)

    demag = ThinFilmDemag()
    sim.add(demag)
    H_computed = demag.compute_field()
    H_expected = H_gen(sim.m)

    diff = np.abs(H_computed - H_expected)
    print "Expected, with shape {}:\n".format(H_expected.shape), H_expected
    print "Got, with shape {}:\n".format(H_computed.shape), H_computed
    print "Difference:\n", diff
    assert np.allclose(H_computed, H_expected, atol=atol, rtol=rtol)
예제 #27
0
def test_uniform_external_field():
    TOLERANCE = 3.5e-10

    mesh = df.UnitCubeMesh(2, 2, 2)
    sim = Sim(mesh, Ms)
    sim.set_m((1, 0, 0))
    sim.add(Zeeman((0, Ms, 0)))
    sim.alpha = 1.0
    sim.run_until(1e-9)

    m = sim.m.reshape((3, -1)).mean(-1)
    expected_m = np.array([0, 1, 0])
    diff = np.abs(m - expected_m)
    assert np.max(diff) < TOLERANCE
예제 #28
0
def cubic_anisotropy(K1=520e3, K2=0, K3=0):
    mesh = df.RectangleMesh(df.Point(0, 0), df.Point(50, 2), 20, 1)

    sim = Simulation(mesh, Ms, unit_length=1e-9)
    sim.set_m(m_init)

    sim.add(
        CubicAnisotropy(K1=K1,
                        K2=K2,
                        K3=K3,
                        u1=(1, 0, 0),
                        u2=(0, 1, 0),
                        assemble=False))

    field1 = sim.effective_field()
예제 #29
0
파일: energy.py 프로젝트: whshangl/finmag
def excite_system():
    Ms = 8.0e5
    sim = Simulation(mesh, Ms, unit_length=1e-9, name='dy')

    sim.alpha = 0.001
    sim.set_m((1, 0, 0))
    sim.set_tol(1e-6, 1e-6)

    A = 1.3e-11

    sim.add(Exchange(A))
    sim.add(Zeeman(varying_field))

    sim.schedule('save_ndt', every=2e-12)
    sim.run_until(0.5e-9)
예제 #30
0
def run_finmag():
    """Run the finmag simulation and store data in averages.txt."""

    sim = Sim(mesh, Ms, unit_length=unit_length)
    sim.alpha = 0.5
    sim.set_m((1, 0, 1))

    exchange = Exchange(13.0e-12)
    sim.add(exchange)
    demag = Demag(solver="FK")
    sim.add(demag)

    fh = open(os.path.join(MODULE_DIR, "averages.txt"), "w")
    fe = open(os.path.join(MODULE_DIR, "energies.txt"), "w")

    logger.info("Time integration")
    times = np.linspace(0, 3.0e-10, 61)
    for counter, t in enumerate(times):

        # Integrate
        sim.run_until(t)

        # Save averages to file
        mx, my, mz = sim.m_average
        fh.write(str(t) + " " + str(mx) + " " + str(my) + " " + str(mz) + "\n")

        # Energies
        E_e = exchange.compute_energy()
        E_d = demag.compute_energy()
        fe.write(str(E_e) + " " + str(E_d) + "\n")

        # Energy densities
        if counter == 10:
            exch_energy = exchange.energy_density_function()
            demag_energy = demag.energy_density_function()
            finmag_exch, finmag_demag = [], []
            R = range(100)
            for i in R:
                finmag_exch.append(exch_energy([15, 15, i]))
                finmag_demag.append(demag_energy([15, 15, i]))
            # Store data
            np.save(os.path.join(MODULE_DIR, "finmag_exch_density.npy"),
                    np.array(finmag_exch))
            np.save(os.path.join(MODULE_DIR, "finmag_demag_density.npy"),
                    np.array(finmag_demag))

    fh.close()
    fe.close()