Пример #1
0
def test_mesh1():
    mesh = CuboidMesh(nx=5, ny=3, nz=2, dx=0.23, dy=0.41)
    assert len(mesh.coordinates) == 5 * 3 * 2
    assert mesh.ny * mesh.nz == 6
    assert tuple(mesh.coordinates[mesh.index(0, 0, 0)]) == (0.23 / 2, 0.41 / 2, 0.5)
    assert tuple(mesh.coordinates[mesh.index(3, 2, 1)]) == (
        (3 + 0.5) * 0.23, (2 + 0.5) * 0.41, 1 + 0.5)
Пример #2
0
def disable_test_sim_single_spin_llg_stt(do_plot=False):
    ni = Nickel()
    mesh = CuboidMesh(nx=1, ny=1, nz=1)
    mesh.set_material(ni)

    ni.alpha = 0.1
    sim = Sim(mesh, driver='llg_stt')
    sim.set_m((1, 0, 0))

    H0 = 1
    sim.add(Zeeman((0, 0, H0)))

    dt = 1e-12
    ts = np.linspace(0, 200 * dt, 101)

    precession = ni.gamma / (1 + ni.alpha**2)

    mz_ref = []
    mxyz = []
    real_ts = []

    for t in ts:
        sim.run_until(t)
        real_ts.append(sim.t)
        print(sim.t, abs(sim.spin_length()[0] - 1), sim.spin)
        mz_ref.append(np.tanh(precession * ni.alpha * H0 * sim.t))
        mxyz.append(np.copy(sim.spin))

    mxyz = np.array(mxyz)

    if do_plot:
        ts_ns = np.array(real_ts) * 1e9

        plt.plot(ts_ns, mxyz[:, 0], ".-", label="mx")
        plt.plot(ts_ns, mxyz[:, 1], ".-", label="my")
        plt.plot(ts_ns, mxyz[:, 2], ".-", label="mz")
        plt.plot(ts_ns, mz_ref, "-", label="analytical")
        plt.xlabel("time (ns)")
        plt.ylabel("mz")
        plt.title("integrating a macrospin")
        plt.legend()
        plt.savefig("test_llg_stt.png")

        print(("Deviation = {0}".format(np.max(np.abs(mxyz[:, 2] - mz_ref)))))

    assert np.max(np.abs(mxyz[:, 2] - mz_ref)) < 1e-9
Пример #3
0
def test_demag_fft_exact_oommf():
    mesh = CuboidMesh(nx=5, ny=3, nz=2)
    sim = Sim(mesh)

    demag = Demag()
    sim.add(demag)

    def init_m(pos):
        x = pos[0]
        if x <= 2:
            return (1, 0, 0)
        elif x >= 4:
            return (0, 0, 1)
        else:
            return (0, 1, 0)

    sim.set_m(init_m)
    fft = demag.compute_field()
    exact = demag.compute_exact()
    # print fft,exact
    print np.max(np.abs(fft - exact))

    assert np.max(np.abs(fft - exact)) < 1e-15
Пример #4
0
def setup_domain_wall_cobalt(node_count=NODE_COUNT,
                             A=A_Co,
                             Ms=Ms_Co,
                             K1=K1_Co,
                             length=LENGTH,
                             do_precession=True,
                             unit_length=UNIT_LENGTH):
    a = length / node_count  # cell size
    mesh = CuboidMesh(dx=a,
                      dy=a,
                      dz=a,
                      nx=node_count,
                      ny=1,
                      nz=1,
                      unit_length=unit_length)
    sim = Sim(mesh, "dw_cobalt")
    sim.Ms = Ms
    sim.set_m(lambda r: initial_m(r, length))
    sim.do_precession = do_precession
    sim.add(UniformExchange(A))
    sim.add(UniaxialAnisotropy(K1, (0, 0, 1)))
    sim.pins = lambda r: 1 if (r[0] < a or r[0] > LENGTH - a) else 0
    return sim
Пример #5
0
def create_sim():

    mesh = CuboidMesh(nx=121, ny=121, nz=1)
    sim = Sim(mesh, name='relax')

    sim.alpha = 1.0
    sim.gamma = 0.5
    sim.mu_s = mu_s

    sim.set_m(init_m)

    J = 1.0
    exch = UniformExchange(J)
    sim.add(exch)

    D = 0.08
    dmi = DMI(D)
    sim.add(dmi)

    K = 4e-3
    anis = Anisotropy(K, direction=(0, 0, 1), name='Ku')
    sim.add(anis)

    return sim
Пример #6
0
def test_compute_field():
    """In an infinite film, we expect the demag tensor to be (0, 0, -1), and thus the
    magnetisation, if aligned in 0, 0, 1 direction, to create a demag field pointing
    with equal strength in the opposite direction.
    """

    mesh = CuboidMesh(nx=1, ny=1, nz=1, dx=2.0, dy=2.0, dz=2.0,
                      unit_length=1e-9, periodicity=(True, True, False))

    sim = Sim(mesh, name='relax')

    sim.driver.set_tols(rtol=1e-10, atol=1e-14)
    sim.alpha = 0.5
    sim.gamma = 2.211e5
    sim.Ms = 8.6e5
    sim.do_precession = False

    sim.set_m((0, 0, 1))

    demag = Demag(pbc_2d=True)
    sim.add(demag)
    field = demag.compute_field()
    print((1 + field[2] / 8.6e5))
    assert abs(1 + field[2] / 8.6e5) < 1e-10
Пример #7
0
import numpy as np

from fidimag.common import CuboidMesh
from fidimag.micro import Sim
from fidimag.micro import UniformExchange
from fidimag.micro import UniaxialAnisotropy
from fidimag.micro import DMI

import matplotlib.pyplot as plt

mesh = CuboidMesh(dx=2, nx=150, x0=-150, unit_length=1e-9)


def m_init_dw(pos):

    x = pos[0]

    if x < -10:
        return (1, 0, 0)
    elif x > 10:
        return (-1, 0, 0)
    else:
        return (0, 1, 0)


def analytical(xs, A=1.3e-11, D=4e-4, K=8e4):

    delta = np.sqrt(A / (K - D * D / (4 * A))) * 1e9

    phi = D / (2 * A) * xs * 1e-9
Пример #8
0
    A = 1.3e-11
    exch = UniformExchange(A=A)
    sim.add(exch)

    sim.relax(dt=1e-13,
              stopping_dmdt=0.5,
              max_steps=5000,
              save_m_steps=None,
              save_vtk_steps=50)

    np.save('m0.npy', sim.spin)


if __name__ == '__main__':

    mesh = CuboidMesh(nx=501,
                      ny=501,
                      nz=1,
                      dx=2.0,
                      dy=2.0,
                      dz=2.0,
                      unit_length=1e-9,
                      periodicity=(True, True, False))

    #relax_system(mesh)
    relax_system_only_exchange(mesh)

    # apply_field1(mesh)
    # deal_plot()
Пример #9
0
def simulation(nx,
               ny,
               nz,
               dx,
               dy,
               dz,
               j,
               d,
               kc,
               bz,
               mu_s,
               sim_name,
               add_image=None,
               add_interpolations=None,
               add_images_folder=None,
               stopping_dydt=None,
               max_steps=None,
               save_m_every=None,
               integrator='sundials',
               integrator_stepsize=1e-3,
               interpolation_method='rotation',
               variable_spring_forces=None,
               interpolation_energy='polynomial'):

    if add_interpolations:
        if (len(add_image) - 1) != len(add_interpolations):
            raise Exception('(N interpolations) != (N images - 1)')

    mesh = CuboidMesh(nx=nx,
                      ny=ny,
                      nz=nz,
                      dx=dx,
                      dy=dy,
                      dz=dz,
                      x0=-nx * 0.5,
                      y0=-ny * 0.5,
                      z0=-nz * 0.5,
                      unit_length=1.,
                      periodicity=(True, True, False))

    # Simulation
    sim = Sim(mesh, name=sim_name)
    sim.mu_s = mu_s
    sim.add(Exchange(j))
    sim.add(DMI(d, dmi_type='bulk'))
    sim.add(Zeeman((0.0, 0.0, bz * 1e-3)))
    if np.abs(kc) > 0.0:
        sim.add(CubicAnisotropy(kc))

    # GNEBM simulation ........................................................

    if add_interpolations:
        # Set the initial images from the list
        init_images = [np.load(image) for image in add_image]
        interpolations = [i for i in add_interpolations]
    elif add_images_folder:
        if add_images_folder.endswith('_LAST'):
            dir_list = glob.glob(add_images_folder[:-5] + '*')
            dir_list = sorted(
                dir_list,
                key=lambda f: int(re.search(r'(?<=_)[0-9]+$', f).group(0)))
            add_images_folder = dir_list[-1]

        flist = sorted(os.listdir(add_images_folder))
        init_images = [
            np.load(os.path.join(add_images_folder, image)) for image in flist
        ]
        interpolations = []
    else:
        raise Exception('Specify an option to add images')

    # Start a NEB simulation passing the Simulation object and all the NEB
    # parameters
    string = StringMethod(sim,
                          init_images,
                          interpolations=interpolations,
                          name=sim_name,
                          openmp=True,
                          integrator=integrator,
                          interpolation_method=interpolation_method)

    if integrator == 'verlet':
        string.integrator.mass = 1
        string.integrator.stepsize = integrator_stepsize
        dt = integrator_stepsize * 10
    else:
        dt = integrator_stepsize

    # .........................................................................

    for fdir in ['interpolations', 'ndts']:
        if not os.path.exists(fdir):
            os.makedirs(fdir)

    # Finally start the energy band relaxation
    string.relax(max_iterations=max_steps,
                 save_vtks_every=save_m_every,
                 save_npys_every=save_m_every,
                 stopping_dYdt=stopping_dydt,
                 dt=dt)

    # Produce a file with the data from a cubic interpolation for the band
    interp_data = np.zeros((200, 2))
    if interpolation_energy == 'polynomial':
        string.compute_polynomial_factors()
        (interp_data[:, 0],
         interp_data[:,
                     1]) = string.compute_polynomial_approximation_energy(200)
    elif interpolation_energy == 'Bernstein':
        string.compute_Bernstein_polynomials()
        (interp_data[:, 0],
         interp_data[:,
                     1]) = string.compute_Bernstein_approximation_energy(200)
    else:
        raise Exception('No valid interpolation method')

    np.savetxt('interpolations/{}_interpolation.dat'.format(sim_name),
               interp_data)

    # Clean files
    shutil.move(sim_name + '_energy.ndt',
                'ndts/{}_energy.ndt'.format(sim_name))
    shutil.move(sim_name + '_dYs.ndt', 'ndts/{}_dYs.ndt'.format(sim_name))
Пример #10
0
    qx = np.fft.fftfreq(nx,dx)*2*np.pi
    qy = np.fft.fftfreq(ny,dy)*2*np.pi

    qx = np.fft.fftshift(qx)
    qy = np.fft.fftshift(qy)

    
    plt.figure(figsize=(5,5))
    #plt.imshow(np.abs(Mz)**2, aspect=1, interpolation='none', origin='lower', extent=(qx.min(), qx.max(), qy.min(), qy.max()))
    plt.imshow(np.abs(Mz)**2, aspect=1, origin='lower', extent=(qx.min(), qx.max(), qy.min(), qy.max()))
    #plt.axis('equal')
    plt.xlim(-0.5, 0.5)
    plt.ylim(-0.5, 0.5)
    plt.xlabel('qx (1/nm)')
    plt.ylabel('qy (1/nm)')
    plt.tight_layout()
    plt.savefig('skx.png')




if __name__ == '__main__':

    mesh = CuboidMesh(nx=Rx*2, ny=Ry, nz=1, dx=1.0, dy=1.0, dz=1.0, unit_length=1e-9, periodicity = (True, True, False))

    relax_system(mesh)

    plot_mz()

    do_fft()
Пример #11
0
        #sim.save_vtk()


def save_plot():

    data = DataReader('dyn_K.txt')
    ts = data['time']
    xs = data['m_x']

    fig = plt.figure()
    plt.plot(ts, xs)

    data = DataReader('dyn_D.txt')
    ts = data['time']
    xs = data['m_x']

    plt.plot(ts, xs, '+')

    fig.savefig('test.pdf')


if __name__ == "__main__":

    mesh = CuboidMesh(nx=1000, ny=1, nz=1, dx=2, dy=2, dz=2, unit_length=1e-9)
    relax_system(mesh)

    excite_system_D(mesh)
    excite_system_K(mesh)

    save_plot()
Пример #12
0
def simulation(nx,
               ny,
               nz,
               dx,
               dy,
               dz,
               j,
               d,
               kc,
               mu_s,
               sim_name,
               bz_min,
               bz_max,
               bz_steps,
               bz_hysteresis=False,
               initial_state_one_bobber=None,
               initial_state_two_bobbers=None,
               initial_state_two_bobbers_asymm=None,
               initial_state_sk_tube=None,
               initial_state_one_dim_mod=None,
               initial_state_helix_angle_x=(None, None),
               stopping_dmdt=1e-5,
               max_steps=4000,
               save_initial_state=None):

    mesh = CuboidMesh(nx=nx,
                      ny=ny,
                      nz=nz,
                      dx=dx,
                      dy=dy,
                      dz=dz,
                      x0=-nx * 0.5,
                      y0=-ny * 0.5,
                      z0=-nz * 0.5,
                      unit_length=1.,
                      periodicity=(True, True, False))

    # J = 1.
    # D = 0.628  # L_D = 2 PI a J / D = 10 * a => D / J = 2 PI / 10.
    # Bz = 0.2   # B_z == (B_z mu_s / J)
    # mu_s = 1.

    sim = Sim(mesh, name=sim_name, integrator='sundials_openmp')

    sim.mu_s = mu_s
    sim.add(Exchange(j))
    sim.add(DMI(d, dmi_type='bulk'))
    sim.add(Zeeman((0.0, 0.0, bz_min * 1e-3)), save_field=True)
    if np.abs(kc) > 0.0:
        sim.add(CubicAnisotropy(kc))

    # .........................................................................

    sim.driver.alpha = 0.9
    sim.driver.do_precession = False

    if not os.path.exists('npys/{}'.format(sim_name)):
        os.makedirs('npys/{}'.format(sim_name))

    if not os.path.exists('txts'):
        os.makedirs('txts')

    for i, B_sweep in enumerate(np.linspace(bz_min, bz_max, bz_steps)):

        print('Bz = {:.0f} mT '.format(B_sweep).ljust(80, '-'))

        Zeeman_int = sim.get_interaction('Zeeman')
        Zeeman_int.update_field((0.0, 0.0, B_sweep * 1e-3))

        if (not bz_hysteresis) or (bz_hysteresis and i < 1):

            if initial_state_one_dim_mod:
                sim.set_m(lambda r: one_dim_mod(r, B_sweep * 1e-3, d))
            elif initial_state_helix_angle_x[0]:
                angle = initial_state_helix_angle_x[0] * np.pi / 180.
                periodic = initial_state_helix_angle_x[1]
                sim.set_m(lambda r: helix_angle_x(r, angle, periodic))
            elif initial_state_sk_tube:
                sk_rad = initial_state_sk_tube
                sim.set_m(
                    lambda r: sk_tube(r, B_sweep * 1e-3, d, sk_rad=sk_rad))
            elif initial_state_two_bobbers:
                bobber_length = initial_state_two_bobbers
                sim.set_m(lambda r: two_bobbers(r,
                                                B_sweep * 1e-3,
                                                d,
                                                mesh.Lz,
                                                bobber_rad=3.,
                                                bobber_length=bobber_length))
            elif initial_state_two_bobbers_asymm:
                bobber_length = initial_state_two_bobbers_asymm
                sim.set_m(
                    lambda r: two_bobbers_asymm(r,
                                                B_sweep * 1e-3,
                                                d,
                                                mesh.Lz,
                                                bobber_rad=3.,
                                                bobber_length=bobber_length))
            elif initial_state_one_bobber:
                bobber_length = initial_state_one_bobber
                sim.set_m(lambda r: one_bobber(r,
                                               B_sweep * 1e-3,
                                               d,
                                               mesh.Lz,
                                               bobber_rad=3.,
                                               bobber_length=bobber_length))
            else:
                raise Exception('Not a valid initial state')

        if save_initial_state:
            save_vtk(sim, sim_name + '_INITIAL', field_mT=B_sweep)
            name = 'npys/{}/m_{}_INITIAL_Bz_{:06d}.npy'.format(
                sim.driver.name, sim_name, int(B_sweep))
            np.save(name, sim.spin)

        # .....................................................................

        sim.relax(stopping_dmdt=stopping_dmdt,
                  max_steps=max_steps,
                  save_m_steps=None,
                  save_vtk_steps=None)

        # .....................................................................

        save_vtk(sim, sim_name, field_mT=B_sweep)
        name = 'npys/{}/m_{}_Bz_{:06d}.npy'.format(sim.driver.name, sim_name,
                                                   int(B_sweep))
        np.save(name, sim.spin)

        sim.driver.reset_integrator()

    shutil.move(sim_name + '.txt', 'txts/{}.txt'.format(sim_name))
Пример #13
0
    sim.mu_s = const.mu_s_1
    sim.T = temperature_gradient

    sim.set_m(np.load("m0.npy"))

    J = 50.0 * const.k_B
    exch = UniformExchange(J)
    sim.add(exch)

    D = 0.5 * J
    dmi = DMI(D)
    sim.add(dmi)

    Hz = 0.2 * J / const.mu_s_1
    zeeman = Zeeman([0, 0, Hz])
    sim.add(zeeman)

    dt = 2e-14 * 50  # 1e-12
    ts = np.linspace(0, 1000 * dt, 501)
    for t in ts:
        sim.run_until(t)
        sim.save_vtk()
        sim.save_m()
        print 'sim t=%g' % t


if __name__ == '__main__':
    mesh = CuboidMesh(nx=150, ny=50, nz=1,  periodicity=(True, True, False))
    relax_system(mesh)
    #excite_system(mesh)
Пример #14
0
def cylinder(pos):

    # Relative position
    x, y = pos[0] - radius, pos[1] - radius

    if x**2 + y**2 < radius**2:
        return Ms
    else:
        return 0


# We will generate a 50 nm wide and 5nm thick disk The finite difference
# elements are 2nmx2nm cubes along the disk plane and they have a thickness of
# 1 nm
# Finite differences mesh
mesh = CuboidMesh(nx=25, ny=25, nz=5, dx=2, dy=2, dz=1, unit_length=1e-9)


# Initial magnetisation profile to get the skyrmion
# We create a small core pointing in the +z direction
def init_m(pos):

    x, y = pos[0] - radius, pos[1] - radius

    if x**2 + y**2 < radius**2:
        return (0, 0, 1)
    else:
        return (0, 0, -1)


# Prepare simulation
Пример #15
0
def test_m_average():
    mesh = CuboidMesh(nx=3, ny=4, nz=5)
    sim = Sim(mesh)
    sim.set_m((0, 0, 1))
    a = sim.compute_average()
    assert a[2] == 1.0
Пример #16
0
def test_save_vector_field(tmpdir):
    mesh = CuboidMesh(4, 3, 2, 4, 3, 2)
    s = vector_field(mesh, lambda r: (r[0], r[1], r[2]))
    vtk = VTK(mesh, directory=str(tmpdir), filename="save_vector")
    vtk.save_vector(s, name="s")
    assert same_as_ref(vtk.write_file(), REF_DIR)
Пример #17
0
    def start(self):
        self.t1 = time.clock()

    def end(self):
        self.t2 = time.clock()

    def interval(self):
        return self.t2 - self.t1


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

# 1D chain of 50 spins with a lattice constant of 0.27 A
mesh = CuboidMesh(
    nx=50,
    dx=0.27,
    unit_length=1e-9,
)


# Simulation Function
def relax_neb(k, maxst, simname, init_im, interp, save_every=10000):
    """
    Execute a simulation with the NEB function of the FIDIMAG code

    The simulations are made for a specific spring constant 'k' (a float),
    number of images 'init_im', interpolations between images 'interp'
    (an array) and a maximum of 'maxst' steps.
    'simname' is the name of the simulation, to distinguish the
    output files.
Пример #18
0
    fname = "m_{}_Bz_{:06d}".format(sim_name, int(field_mT)) + ".vtk"
    sim.driver.VTK.vtk_data.tofile(
        os.path.join('vtks/{}'.format(sim_name), fname))


# FIELD = 80
for FIELD in range(0, 181, 20):

    nx, ny, nz = 30, 30, 30
    dx, dy, dz = 1, 1, 1
    mesh = CuboidMesh(nx=nx,
                      ny=ny,
                      nz=nz,
                      dx=dx,
                      dy=dy,
                      dz=dz,
                      x0=-nx * 0.5,
                      y0=-ny * 0.5,
                      z0=-nz * 0.5,
                      unit_length=1.,
                      periodicity=(True, True, False))

    sim_name = 'sk_helix'
    sim = Sim(mesh, name=sim_name, integrator='sundials_openmp')

    sim.mu_s = 1
    sim.add(Exchange(1))
    sim.add(DMI(0.727, dmi_type='bulk'))
    bz_min = FIELD
    sim.add(Zeeman((0.0, 0.0, bz_min * 1e-3)), save_field=True)
    kc = -0.05
    #            )


# Mesh ------------------------------------------------------------------------


# Define an elongated cylinder along the y direction
def cylinder(r, centre, radius):
    if (r[0] - centre[0])**2. + (r[2] - centre[1])**2 <= radius**2.:
        return Ms
    else:
        return 0


# Finite differences mesh
mesh = CuboidMesh(nx=6, ny=35, nz=6, dx=2, dy=2, dz=2, unit_length=1e-9)

centre = (np.max(mesh.coordinates[:, 0]) * 0.5,
          np.max(mesh.coordinates[:, 2]) * 0.5)

# Prepare simulation ----------------------------------------------------------


def elongated_part_sim():
    sim = Sim(mesh)
    sim.Ms = lambda r: cylinder(r, centre, 8)
    sim.add(UniformExchange(A=A))
    sim.add(UniaxialAnisotropy(Kx, axis=(0, 1, 0)))  # Anisotropy along y
    sim.add(Demag())

    return sim
Пример #20
0
# --------------------------------------------------------------------------

# Mesh ---------------------------------------------------------------------

nx = int(args.box_length / args.fd_max_plane)
ny = int(args.box_width / args.fd_max_plane)
nz = int(args.box_thickness / args.fd_max_thick)
dx = args.fd_max_plane
dy = args.fd_max_plane
dz = args.fd_max_thick

if not args.PBC_2D:
    mesh = CuboidMesh(nx=nx,
                  ny=ny,
                  nz=nz,
                  dx=dx,
                  dy=dy,
                  dz=dz,
                  unit_length=1e-9,
                  )
else:
    print 'Using Periodic Boundary Conditions!'
    mesh = CuboidMesh(nx=nx,
                  ny=ny,
                  nz=nz,
                  dx=dx,
                  dy=dy,
                  dz=dz,
                  unit_length=1e-9,
                  pbc='xy'
                  )
Пример #21
0
    mxyz = sim.spin.copy()
    mxyz.shape = (3, -1)

    save_plot(xs, mxyz, mx, my, mz)


def save_plot(xs, mxyz, mx, my, mz):
    fig = plt.figure()
    mxyz.shape = (3, -1)
    plt.plot(xs, mxyz[0], '.', label='mx')
    plt.plot(xs, mxyz[1], '.', label='my')
    plt.plot(xs, mxyz[2], '.', label='mz')

    plt.plot(xs, mx, '-')
    plt.plot(xs, my, '-')
    plt.plot(xs, mz, '-')

    plt.ylabel('mxyz')
    plt.xlabel('x/a')
    plt.legend(loc=1)
    plt.grid()
    #plt.xlim([-150, 150])
    plt.ylim([-1.2, 1.2])
    fig.savefig('dw_dmi.pdf')


if __name__ == '__main__':
    mesh = CuboidMesh(nx=300, ny=40, nz=1)
    relax_system(mesh)
    #excite_system(mesh)
Пример #22
0
def test_initialise_vector():
    mesh = CuboidMesh(1, 1, 1, 1, 1, 1)
    v = vector_field(mesh, lambda r: 2 * r)
    assert very_close(v, np.array((1, 1, 1)))
Пример #23
0
    new_path = os.path.join(MODULE_DIR, field)

    command = ('rm', '-rf', new_path)
    cmd = ' '.join(command)
    os.system(cmd)

    return m


def compute_dmi_field(mesh, init_m0, Ms=8e5, D=4e-3, field='DMExchange6Ngbr'):

    gen_oommf_conf(mesh, Ms=Ms, init_m0=init_m0, D=D, field=field)
    run_oommf(field)

    m = get_field(mesh, field=field)

    new_path = os.path.join(MODULE_DIR, field)

    command = ('rm', '-rf', new_path)
    cmd = ' '.join(command)
    os.system(cmd)

    return m


if __name__ == "__main__":

    mesh = CuboidMesh(nx=5, ny=2, nz=1, dx=1.0, dy=1.0, dz=1.0)
    m = compute_demag_field(mesh, init_m0='return "1 0 0"')
    print(m)
Пример #24
0
def test_initialise_scalar():
    mesh = CuboidMesh(1, 1, 1, 1, 1, 1)
    f = scalar_field(mesh, lambda r: r[0] + r[1] + r[2])
    assert very_close(f, np.array((1.5)))
Пример #25
0
    neb = NEBM_Cartesian(sim,
                         init_images,
                         interpolations=[6, 6],
                         name='neb',
                         spring_constant=1e8)

    # neb.add_noise(0.1)

    neb.relax(dt=1e-8,
              max_iterations=5000,
              save_vtks_every=500,
              save_npys_every=500,
              stopping_dYdt=100)


if __name__ == "__main__":

    mesh = CuboidMesh(nx=160,
                      ny=1,
                      nz=1,
                      dx=4.0,
                      dy=4.0,
                      dz=4.0,
                      unit_length=1e-9)

    sim = create_simulation(mesh)
    # relax_two_state(mesh)
    relax_system(sim)
    # plot_energy_2d('neb')
    # plot_energy_3d('neb')
"""


def two_part(pos):

    x = pos[0]

    if x > 6 or x < 3:
        return Ms
    else:
        return 0

# Finite differences mesh
mesh = CuboidMesh(nx=3,
                  ny=1,
                  nz=1,
                  dx=3, dy=3, dz=3,
                  unit_length=1e-9
                  )


# Simulation Function
def relax_neb(k, maxst, simname, init_im, interp, save_every=10000,
              coordinates='Cartesian'):
    """
    Execute a simulation with the NEB function of the FIDIMAG code, for an
    elongated particle (long cylinder)

    The simulations are made for a specific spring constant 'k' (a float),
    number of images 'init_im', interpolations between images 'interp'
    (an array) and a maximum of 'maxst' steps.
    'simname' is the name of the simulation, to distinguish the
Пример #27
0
    np.save('m0.npy', sim.spin)


def save_plot():
    fig = plt.figure()
    data = np.load('m0.npy')
    data.shape = (3, -1)
    print data

    plt.plot(data[0], '-', label='Sx')
    plt.plot(data[1], '-', label='Sy')
    plt.plot(data[2], '-', label='Sz')

    plt.ylim([-1.2, 1.2])
    plt.ylabel('S')
    plt.xlabel('x/a')
    plt.legend(loc=1)
    plt.grid()
    fig.savefig('mxyz.pdf')


if __name__ == '__main__':

    mesh = CuboidMesh(nx=300, dx=0.5, dy=1, dz=1, unit_length=1e-9)

    relax_system(mesh)
    print 'relax system done'
    save_plot()
    # spin_wave(mesh,m0)
Пример #28
0
    sim = Sim(mesh, name='fidimag', driver='llg_stt')

    sim.driver.set_tols(rtol=1e-8, atol=1e-8)
    sim.driver.alpha = 0.1
    sim.driver.gamma = 2.211e5
    sim.Ms = 8.0e5
    sim.driver.p = 1

    sim.set_m(np.load('npys/m0_cpu.npy'))

    A = 1.3e-11
    exch = UniformExchange(A=A)
    sim.add(exch)

    sim.add(Demag())

    sim.driver.jx = -1e12
    sim.driver.beta = 0.05

    ts = np.linspace(0, 8e-9, 801)

    for t in ts:
        print('time', t)
        sim.driver.run_until(t)


if __name__ == '__main__':

    mesh = CuboidMesh(nx=20, ny=20, nz=2,dx=5, dy=5, dz=5.0, unit_length=1e-9)
    excite_system(mesh)
Пример #29
0
    sim.add(exch)

    mT = 795.7747154594767
    zeeman = Zeeman([-100 * mT, 4.3 * mT, 0], name='H')
    sim.add(zeeman, save_field=True)

    demag = Demag()
    sim.add(demag)

    ONE_DEGREE_PER_NS = 17453292.52

    sim.relax(dt=1e-12,
              stopping_dmdt=0.01,
              max_steps=5000,
              save_m_steps=100,
              save_vtk_steps=50)

    np.save('m0.npy', sim.spin)


if __name__ == "__main__":

    mesh = CuboidMesh(nx=20,
                      ny=20,
                      nz=1,
                      dx=2.5,
                      dy=2.5,
                      dz=3,
                      unit_length=1e-9)
    relax_system(mesh)
Пример #30
0
def test_skx_num_micromagnetic():
    """

    Compute the skyrmion number from a micromagnetic simulation,
    using the continuum topological charge expression for a
    2D layer:
                          _
               1         /       dM     dM
       Q   =  ---  *    /   M .  --  X  --   dx dy
              4 PI   _ /         dx     dy

    The skyrmion is generated in an Iron based sample, whose
    magnetic parameters are in: PRL 114, 177203 (2015)

    """

    # A 6 nm by 6 nm square sample with enough resolution for a
    # skyrmion with Q ~= -1
    mesh = CuboidMesh(nx=60,
                      ny=60,
                      nz=1,
                      dx=0.1,
                      dy=0.1,
                      dz=0.4,
                      unit_length=1e-9,
                      periodicity=(True, True, False))

    sim = microSim(mesh, name='skx_num_micro')
    sim.driver.set_tols(rtol=1e-6, atol=1e-6)
    sim.driver.alpha = 1.0
    sim.driver.gamma = 1.0
    sim.Ms = 1.1e6

    sim.set_m(lambda pos: init_m(pos, x0=3, y0=3, r=1))

    sim.do_precession = False

    A = 2e-12
    exch = microUniformExchange(A)
    sim.add(exch)

    D = 3.9e-3
    dmi = microDMI(D, dmi_type='interfacial')
    sim.add(dmi)

    zeeman = microZeeman([0, 0, 2])
    sim.add(zeeman)

    Ku = 2.5e6
    sim.add(microUniaxialAnisotropy(Ku, (0, 0, 1), name='Ku'))

    sim.relax(stopping_dmdt=1e-2,
              max_steps=1000,
              save_m_steps=None,
              save_vtk_steps=None)

    sim.save_vtk()

    skn = sim.skyrmion_number()

    print('skx_number', skn)
    print(sim._skx_number)
    assert skn > -1 and skn < -0.99
Пример #31
0
# Mesh ---------------------------------------------------------------------

nx = int(args.box_length / args.fd_max_plane)
ny = int(args.box_width / args.fd_max_plane)
nz = int(args.box_thickness / args.fd_max_thick)
dx = args.fd_max_plane
dy = args.fd_max_plane
dz = args.fd_max_thick

if not args.PBC_2D:
    mesh = CuboidMesh(
        nx=nx,
        ny=ny,
        nz=nz,
        dx=dx,
        dy=dy,
        dz=dz,
        unit_length=1e-9,
    )
else:
    print 'Using Periodic Boundary Conditions!'
    mesh = CuboidMesh(nx=nx,
                      ny=ny,
                      nz=nz,
                      dx=dx,
                      dy=dy,
                      dz=dz,
                      unit_length=1e-9,
                      pbc=(True, True, False))
Пример #32
0
def test_skx_num_atomistic():
    """
    Test the *finite spin chirality* or skyrmion number for
    a discrete spins simulation in a two dimensional lattice

    The expression is (PRL 108, 017601 (2012)) :

    Q =     S_i \dot ( S_{i+1}  X  S_{j+1} )
         +  S_i \dot ( S_{i-1}  X  S_{j-1} )

    which measures the chirality taking two triangles of spins
    per lattice site i:
        S_{i} , S_{i + x} , S_{i + y}    and
        S_{i} , S_{i - x} , S_{i - y}

    The area of the two triangles cover a unit cell, thus the sum
    cover the whole area of the atomic lattice

    We also test the Berg and Luscher definition for a topological
    charge (see the hexagonal mesh test for details) in a
    square lattice.

    This test generate a skyrmion pointing down with unrealistic
    paremeters.

    """

    mesh = CuboidMesh(nx=120, ny=120, nz=1, periodicity=(True, True, False))

    sim = Sim(mesh, name='skx_num')
    sim.driver.set_tols(rtol=1e-6, atol=1e-6)
    sim.driver.alpha = 1.0
    sim.driver.gamma = 1.0
    sim.mu_s = 1.0

    sim.set_m(lambda pos: init_m(pos, 60, 60, 20))

    sim.do_precession = False

    J = 1.0
    exch = UniformExchange(J)
    sim.add(exch)

    D = 0.09
    dmi = DMI(D)
    sim.add(dmi)

    zeeman = Zeeman([0, 0, 5e-3])
    sim.add(zeeman)

    sim.relax(dt=2.0,
              stopping_dmdt=1e-2,
              max_steps=1000,
              save_m_steps=None,
              save_vtk_steps=None)

    skn = sim.skyrmion_number()
    print('skx_number', skn)

    skn_BL = sim.skyrmion_number(method='BergLuscher')
    print('skx_number_BergLuscher', skn_BL)

    # Test the finite chirality method
    assert skn > -1 and skn < -0.99

    # Test the Berg-Luscher method
    assert np.abs(skn_BL - (-1)) < 1e-4 and np.sign(skn_BL) < 0

    # Test guiding center
    Rx, Ry = compute_RxRy(mesh, sim.spin)
    print('Rx=%g, Ry=%g' % (Rx, Ry))
    assert Rx < 60 and Rx > 58
    assert Ry < 60 and Ry > 58