def test_exchange_energy_analytical_2(): """ Compare one Exchange energy with the corresponding analytical result. """ REL_TOLERANCE = 5e-5 lx = 6 ly = 3 lz = 2 nx = 300 ny = nz = 1 mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(lx, ly, lz), nx, ny, nz) unit_length = 1e-9 functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3) Ms = Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 8e5) A = 13e-12 m = Field(functionspace) m.set( df.Expression(['0', 'sin(2*pi*x[0]/l_x)', 'cos(2*pi*x[0]/l_x)'], l_x=lx, degree=1)) exch = Exchange(A) exch.setup(m, Ms, unit_length=unit_length) E_expected = A * 4 * pi ** 2 * \ (ly * unit_length) * (lz * unit_length) / (lx * unit_length) E = exch.compute_energy() print "expected energy: {}".format(E) print "computed energy: {}".format(E_expected) assert abs((E - E_expected) / E_expected) < REL_TOLERANCE
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()
def test_exchange_field_supported_methods(fixt): """ Check that all supported methods give the same results as the default method. """ A = 1 REL_TOLERANCE = 1e-12 mesh = df.UnitCubeMesh(10, 10, 10) Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1) functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3) m = Field(functionspace) m.set(df.Expression(("0", "sin(x[0])", "cos(x[0])"), degree=1)) exch = Exchange(A) exch.setup(m, Ms) H_default = exch.compute_field() supported_methods = list(Exchange._supported_methods) # no need to compare default method with itself supported_methods.remove(exch.method) # the project method for the exchange is too bad supported_methods.remove("project") for method in supported_methods: exch = Exchange(A, method=method) exch.setup(m, Ms) H = exch.compute_field() print "With method '{}', expecting H =\n{}\n, got H =\n{}.".format( method, H_default.reshape((3, -1)).mean(1), H.reshape((3, -1)).mean(1)) rel_diff = np.abs((H - H_default) / H_default) assert np.nanmax(rel_diff) < REL_TOLERANCE
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 fixt(): """ Create an Exchange object that will be re-used during testing. """ mesh = df.UnitCubeMesh(10, 10, 10) functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3) Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1) A = 1 m = Field(functionspace) exch = Exchange(A) exch.setup(m, Ms) return {"exch": exch, "m": m, "A": A, "Ms": Ms}
def compute_finmag_exc(dolfin_mesh, m_gen, Ms, A): 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) exchange = Exchange(A) exchange.setup(m, Field(df.FunctionSpace(dolfin_mesh, 'DG', 0), Ms)) finmag_exc_field = df.Function(S3) finmag_exc_field.vector()[:] = exchange.compute_field() return finmag_exc_field
def H_eff(self): """Very temporary function to make things simple.""" H_app = project((Constant((0, 1e5, 0))), self.S3) H_ex = Function(self.S3) # Comment out these two lines if you don't want exchange. exch = Exchange(1.3e-11) print "About to call setup" exch.setup(self._m_field, self.Ms) H_ex.vector().array()[:] = exch.compute_field() H_eff = H_ex + H_app return H_eff
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)
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 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()
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
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()
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)
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))
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
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
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()
def test_differentiate_heff(): ns = [2, 2, 2] mesh = df.BoxMesh(0, 0, 0, 1, 1, 1, *ns) sim = Simulation(mesh, 1.2) sim.set_m([1, 0, 0]) sim.add(Demag()) sim.add(Exchange(2.3 * mu0)) compute_H = compute_H_func(sim) # Check that H_eff is linear without Zeeman np.random.seed(1) m1 = fnormalise(np.random.randn(*sim.m.shape)) m2 = fnormalise(np.random.randn(*sim.m.shape)) # TODO: need to use a non-iterative solver here to increase accuracy assert np.max( np.abs(compute_H(m1) + compute_H(m2) - compute_H(m1 + m2))) < 1e-6 # Add the zeeman field now sim.add(Zeeman([2.5, 3.5, 4.3])) # Check that both fd2 and fd4 give the same result assert np.max( np.abs( differentiate_fd4(compute_H, m1, m2) - differentiate_fd2(compute_H, m1, m2))) < 1e-10
def test_compute_skyrmion_number_2d_pbc(): mesh = df.RectangleMesh(df.Point(0, 0), df.Point(100, 100), 40, 40) Ms = 8.6e5 sim = Simulation(mesh, Ms, pbc='2d', unit_length=1e-9) sim.set_m(init_skx_down) sim.add(Exchange(1.3e-11)) sim.add(DMI(D=4e-3)) sim.add(Zeeman((0, 0, 0.45 * Ms))) sim.do_precession = False sim.relax(stopping_dmdt=1, dt_limit=1e-9) #df.plot(sim.m_field.f) #df.interactive() print np.max(sim.m_field.as_array()) sky_num = compute_skyrmion_number_2d(sim.m_field.f) print 'sky_num = %g' % sky_num assert sky_num < -0.95 and sky_num > -1.0
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)
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))
def test_interaction_accepts_name(): """ Check that the interaction accepts a 'name' argument and has a 'name' attribute. """ exch = Exchange(13e-12, name='MyExchange') assert hasattr(exch, 'name')
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 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
def example_simulation(): Ms = 8.6e5 mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(40, 20, 20), 10, 5, 5) example = Simulation(mesh, Ms, name="sim_with_scheduling") example.set_m((0.1, 1, 0)) example.add(Exchange(13.0e-12)) example.add(Demag()) example.add(Zeeman((Ms/2, 0, 0))) return example
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'))
def run_simulation(stop_when_mx_eq_zero): """ Runs the simulation using field #1 from the problem description. Stores the average magnetisation components regularly, as well as the magnetisation when the x-component of the average magnetisation crosses the value 0 for the first time. """ mesh = from_geofile(os.path.join(MODULE_DIR, "bar.geo")) sim = Simulation(mesh, Ms, name="dynamics", unit_length=1e-9) sim.alpha = alpha sim.gamma = gamma sim.set_m(np.load(m_0_file)) sim.add(Demag()) sim.add(Exchange(A)) """ Conversion between mu0 * H in mT and H in A/m. mu0 * H = 1 mT = 1 * 1e-3 T = 1 * 1e-3 Vs/m^2 divide by mu0 with mu0 = 4pi * 1e-7 Vs/Am gives H = 1 / 4pi * 1e4 A/m with the unit A/m which is indeed what we want. Consequence: Just divide the value of mu0 * H in Tesla by mu0 to get the value of H in A/m. """ Hx = -24.6e-3 / mu0 Hy = 4.3e-3 / mu0 Hz = 0 sim.add(Zeeman((Hx, Hy, Hz))) def check_if_crossed(sim): mx, _, _ = sim.m_average if mx <= 0: print "The x-component of the spatially averaged magnetisation first crossed zero at t = {}.".format( sim.t) np.save(m_at_crossing_file, sim.m) # When this function returns True, it means this event is done # and doesn't need to be triggered anymore. # When we return False, it means we want to stop the simulation. return not stop_when_mx_eq_zero sim.schedule(check_if_crossed, every=1e-12) sim.schedule('save_averages', every=10e-12, at_end=True) sim.schedule('save_vtk', every=10e-12, at_end=True, overwrite=True) sim.run_until(2.0e-9) return sim.t
def test_exchange_energy_analytical(fixt): """ Compare one Exchange energy with the corresponding analytical result. """ REL_TOLERANCE = 1e-7 A = 1 mesh = df.UnitCubeMesh(10, 10, 10) Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1) functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3) m = Field(functionspace) m.set(df.Expression(("x[0]", "x[2]", "-x[1]"), degree=1)) exch = Exchange(A) exch.setup(m, Ms) E = exch.compute_energy() # integrating the vector laplacian, the latter gives 3 already expected_E = 3 print "With m = (0, sqrt(1-x^2), x), " + \ "expecting E = {}. Got E = {}.".format(expected_E, E) assert abs(E - expected_E) / expected_E < REL_TOLERANCE
def excite_system(): Ms = 8.6e5 sim = Simulation(mesh, Ms, pbc='1d', unit_length=1e-9) sim.alpha = 0.0001 sim.set_m(np.load('relaxed.npy')) alpha_expr = AlphaExpression() alpha_mult = df.interpolate(alpha_expr, sim.llg.S1) sim.spatial_alpha(0.0001, alpha_mult) #df.plot(alpha_mult) #df.interactive() #xs=find_skyrmion_center(sim.llg._m) # #assert(1==2) A = 1.3e-11 D = 4e-3 sim.add(Exchange(A)) sim.add(DMI(D)) sim.add(Zeeman((0, 0, 0.4 * Ms))) GHz = 1e9 omega = 50 * 2 * np.pi * GHz def time_fun(t): return np.sinc(omega * (t - 50e-12)) h0 = 1e3 kc = 1.0 / 45.0 H0 = MyExpression(h0, kc) sim.add(TimeZeemanPython(H0, time_fun)) xs = find_skyrmion_center(sim.llg._m) ts = np.linspace(0, 8e-9, 4001) np.save('xs.npy', xs) sim.create_integrator() sim.integrator.integrator.set_scalar_tolerances(1e-8, 1e-8) index = 0 for t in ts: sim.run_until(t) np.save('data/m_%d.npy' % index, sim.llg.m) index += 1
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