def test_compare_exchange_for_two_dolfin_meshes(): """ Check that a mesh expressed in nanometers gives the same results as a mesh expressed in meters for the exchange interaction. """ mesh_nm = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), n, n, n) # in nm m_nm, H_nm, E_nm = exchange(mesh_nm, unit_length=1e-9) mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1e-9, 1e-9, 1e-9), n, n, n) m, H, E = exchange(mesh, unit_length=1) rel_diff_m = np.max(np.abs(m_nm - m)) # norm m = 1 print "Difference of magnetisation is {:.2f}%.".format(100 * rel_diff_m) assert rel_diff_m < REL_TOL rel_diff_E = abs((E_nm - E) / E) print "Relative difference between E_nm = {:.5g} and E_m = {:.5g} is d = {:.2f}%.".format( E_nm, E, 100 * rel_diff_E) assert rel_diff_E < REL_TOL max_diff_H = np.max(np.abs(H_nm - H) / np.max(H)) print "Maximum of relative difference between the two fields is d = {:.2f}%.".format( 100 * max_diff_H) assert np.max(np.abs(H)) > 0 assert max_diff_H < REL_TOL
def test_build_mesh(): """ Create a few meshes, extract the vertices and cells from them and pass them to build_mesh() to rebuild the mesh. Then check that the result is the same as the original. """ def assert_mesh_builds_correctly(mesh): coords = mesh.coordinates() cells = mesh.cells() mesh_new = build_mesh(coords, cells) assert np.allclose(coords, mesh_new.coordinates()) assert np.allclose(cells, mesh_new.cells()) mesh1 = df.RectangleMesh(df.Point(0, 0), df.Point(20, 10), 12, 8) assert_mesh_builds_correctly(mesh1) mesh2_temp = mshr.Circle(df.Point(2.0, -3.0), 10) mesh2 = mshr.generate_mesh(mesh2_temp, 10) assert_mesh_builds_correctly(mesh2) mesh3 = df.BoxMesh(df.Point(0, 0, 0), df.Point(20, 10, 5), 12, 8, 3) assert_mesh_builds_correctly(mesh3) mesh4_temp = mshr.Sphere(df.Point(2.0, 3.0, -4.0), 10) mesh4 = mshr.generate_mesh(mesh4_temp, 10) assert_mesh_builds_correctly(mesh4)
def mesh3d(width, depth, height, nx, ny, nz): mesh = dolfin.BoxMesh(Point(0., 0., 0.), Point(width, depth, height), nx, ny, nz) boundary = (dolfin.MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0), {}) for f in dolfin.facets(mesh): if dolfin.near(f.midpoint()[2], 0.): boundary[0][f] = 1 # bottom boundary[1]['bottom'] = 1 elif dolfin.near(f.midpoint()[2], height): boundary[0][f] = 2 # top boundary[1]['top'] = 2 elif dolfin.near(f.midpoint()[0], 0.): boundary[0][f] = 3 # left boundary[1]['left'] = 3 elif dolfin.near(f.midpoint()[0], width): boundary[0][f] = 4 # right boundary[1]['right'] = 4 elif dolfin.near(f.midpoint()[1], 0): boundary[0][f] = 5 # front boundary[1]['front'] = 5 elif dolfin.near(f.midpoint()[1], depth): boundary[0][f] = 6 # back boundary[1]['back'] = 6 # Definition of measures and normal vector: n = dolfin.FacetNormal(mesh) dx = dolfin.Measure("dx", mesh) ds = dolfin.Measure("ds", subdomain_data=boundary[0]) mesh_xdmf = dolfin.XDMFFile(mpi_comm_world(), "data/mesh_3D.xdmf") mesh_xdmf.write(boundaries[0]) return (mesh, boundary, n, dx, ds)
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
def macrospin_box(Ms=0.86e6, m_init=(1, 0, 0), H_ext=(0, 0, 1e6), alpha=0.1, name='macrospin'): """ Cubic mesh of length 1 nm along each edge, with eight vertices located in the corners of the cube. No anisotropy, exchange coupling or demag is present so that magnetic moments at the vertices behave identical under the influence of the external field. Default values for the arguments: Ms = 0.86e6 (saturation magnetisation in A/m) m_init = (1, 0, 0) (initial magnetisation pointing along the x-axis) H_ext = (0, 0, 1e6) (external field in A/m) alpha = 0.1 (Gilbert damping coefficient) """ mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1) sim = sim_with(mesh, Ms=0.86e6, alpha=alpha, unit_length=1e-9, A=None, H_ext=H_ext, m_init=(1, 0, 0), name=name) return sim
def FunctionFromSamples(g_samples, grid, offset=0.0): """ Given an array of function samples at the points of a grid, construct a callable dolfin function by interpolation. Inputs: g_samples (np.array): 2D or 3D array of function samples grid (Grid): grid of Points at which function was sampled Returns: Callable dolfin function of 2D or 3D coordinate array p """ n, nd = np.shape(g_samples), len(np.shape(g_samples)) x, y, z = grid.xtics, grid.ytics, grid.ztics vmin, vmax = [x[0], y[0], z[0]], [x[-1], y[-1], z[-1]] pmin, pmax = df.Point(vmin[0:nd]), df.Point(vmax[0:nd]) if nd == 2: mesh = df.RectangleMesh(pmin, pmax, n[0], n[1]) else: mesh = df.BoxMesh(pmin, pmax, n[0], n[1], n[2]) grid_space = df.FunctionSpace(mesh, 'Lagrange', 1) g = df.Function(grid_space) v = g.vector() delta = [t[2] - t[1] if len(t) > 1 else 1.0 for t in [x, y, z]] for i, p in enumerate(grid_space.tabulate_dof_coordinates()): n = [int(round((p[d] - pmin[d]) / delta[d])) for d in range(nd)] v[i] = g_samples[tuple(n)] + offset g.set_allow_extrapolation(True) return g
def bar(name='bar', demag_solver_type=None): """Py bar with dimensions 30x30x100nm, initial field pointing in (1,0,1) direction. Same as example 2 in Nmag manual. This function returns a simulation object that is 'ready to go'. Useful commands to run this for a minute:: times = numpy.linspace(0, 3.0e-11, 6 + 1) for t in times: # Integrate sim.run_until(t) """ xmin, ymin, zmin = 0, 0, 0 # one corner of cuboid xmax, ymax, zmax = 30, 30, 100 # other corner of cuboid # number of subdivisions (use ~2nm edgelength) nx, ny, nz = 15, 15, 50 mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax), nx, ny, nz) sim = finmag.sim_with(mesh, Ms=0.86e6, alpha=0.5, unit_length=1e-9, A=13e-12, m_init=(1, 0, 1), name=name, demag_solver_type=demag_solver_type) return sim
def demo1(): # create example simulation import finmag import dolfin as df xmin, ymin, zmin = 0, 0, 0 # one corner of cuboid xmax, ymax, zmax = 6, 6, 11 # other corner of cuboid nx, ny, nz = 3, 3, 6 # number of subdivisions (use ~2nm edgelength) mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax), nx, ny, nz) # standard Py parameters sim = finmag.sim_with(mesh, Ms=0.86e6, alpha=0.5, unit_length=1e-9, A=13e-12, m_init=(1, 0, 1)) filename = 'data.txt' ndt = Tablewriter(filename, sim, override=True) times = np.linspace(0, 3.0e-11, 6 + 1) for i, time in enumerate(times): print("In iteration {}, computing up to time {}".format(i, time)) sim.run_until(time) ndt.save() # now open file for reading f = Tablereader(filename) print f.timesteps() print f['m_x']
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 test_hysteresis(tmpdir): os.chdir(str(tmpdir)) sim = barmini() mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 1, 1, 1) H_ext_list = [(1, 0, 0), (2, 0, 0), (3, 0, 0), (4, 0, 0)] N = len(H_ext_list) # Run a relaxation and save a vtk snapshot at the end of each stage; # this should result in three .vtu files (one for each stage). sim1 = sim_with(mesh, Ms=1e6, m_init=(0.8, 0.2, 0), alpha=1.0, unit_length=1e-9, A=None, demag_solver=None) sim1.schedule('save_vtk', at_end=True, filename='barmini_hysteresis.pvd') res1 = sim1.hysteresis(H_ext_list=H_ext_list) assert (len(glob('barmini_hysteresis*.vtu')) == N) assert (res1 == None) # Run a relaxation with a non-trivial `fun` argument and check # that we get a list of return values. sim2 = sim_with(mesh, Ms=1e6, m_init=(0.8, 0.2, 0), alpha=1.0, unit_length=1e-9, A=None, demag_solver=None) res2 = sim2.hysteresis(H_ext_list=H_ext_list, fun=lambda sim: sim.m_average[0]) assert (len(res2) == N)
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 three_dimensional_problem(): x_max = 100e-9 y_max = z_max = 1e-9 x_n = 20 y_n = z_n = 1 dolfin_mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(x_max, y_max, z_max), x_n, y_n, z_n) print dolfin_mesh.num_vertices() oommf_mesh = mesh.Mesh((x_n, y_n, z_n), size=(x_max, y_max, z_max)) def m_gen(rs): xs = rs[0] return np.array([ xs / x_max, np.sqrt(1 - (0.9 * xs / x_max)**2 - 0.01), 0.1 * np.ones(len(xs)) ]) from finmag.util.oommf.comparison import compare_anisotropy return compare_anisotropy(m_gen, Ms, K1, (0, 0, 1), dolfin_mesh, oommf_mesh, dims=3, name="3D")
def test_compute_main(): Ms = 1700e3 A = 2.5e-6 * 1e-5 Hz = [10e3 * Oersted_to_SI(1.), 0, 0] mesh = df.BoxMesh(0, 0, 0, 50, 50, 10, 6, 6, 2) mesh = df.BoxMesh(0, 0, 0, 5, 5, 5, 1, 1, 1) print mesh # Find the ground state sim = Simulation(mesh, Ms) sim.set_m([1, 0, 0]) sim.add(Demag()) sim.add(Exchange(A)) sim.add(Zeeman(Hz)) sim.relax()
def test_crossprod(): """ Compute the cross product of two functions f and g numerically using `helpers.crossprod` and compare with the analytical expression. """ xmin = ymin = zmin = -2 xmax = ymax = zmax = 3 nx = ny = nz = 10 mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax), nx, ny, nz) V = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3) u = df.interpolate(df.Expression(['x[0]', 'x[1]', '0'], degree=1), V) v = df.interpolate(df.Expression(['-x[1]', 'x[0]', 'x[2]'], degree=1), V) w = df.interpolate( df.Expression(['x[1]*x[2]', '-x[0]*x[2]', 'x[0]*x[0]+x[1]*x[1]'], degree=1), V) a = u.vector().array() b = v.vector().array() c = w.vector().array() axb = crossprod(a, b) assert (np.allclose(axb, c))
def mesh(Lx=1., Ly=1., Lz=2., grid_spacing=1./16, **namespace): m = df.BoxMesh(df.Point(0., 0., 0.), df.Point(Lx, Ly, Lz), int(Lx/(2*grid_spacing)), int(Ly/(2*grid_spacing)), int(Lz/(2*grid_spacing))) m = df.refine(m) return m
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_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 hyper_rectangle(first_point, second_point, n_points=10): assert isinstance(first_point, (tuple, list)) assert isinstance(second_point, (tuple, list)) dim = len(first_point) assert dim == 2 or dim == 3 assert len(second_point) == dim assert all( all(isinstance(x, float) for x in p) for p in (first_point, second_point)) assert all(y - x > 0.0 for x, y in zip(first_point, second_point)) corner_points = (dlfn.Point(*first_point), dlfn.Point(*second_point)) assert isinstance(n_points, (int, tuple, list)) if isinstance(n_points, (tuple, list)): assert all(isinstance(n, int) and n > 0 for n in n_points) assert len(n_points) == dim else: n_points > 0 n_points = (n_points, ) * dim # mesh generation if dim == 2: mesh = dlfn.RectangleMesh(*corner_points, *n_points) else: mesh = dlfn.BoxMesh(*corner_points, *n_points) assert dim == mesh.topology().dim() # subdomains for boundaries facet_marker = dlfn.MeshFunction("size_t", mesh, dim - 1) facet_marker.set_all(0) # mark boundaries BoundaryMarkers = HyperCubeBoundaryMarkers gamma01 = dlfn.CompiledSubDomain("near(x[0], val) && on_boundary", val=first_point[0]) gamma02 = dlfn.CompiledSubDomain("near(x[0], val) && on_boundary", val=second_point[0]) gamma03 = dlfn.CompiledSubDomain("near(x[1], val) && on_boundary", val=first_point[1]) gamma04 = dlfn.CompiledSubDomain("near(x[1], val) && on_boundary", val=second_point[1]) gamma01.mark(facet_marker, BoundaryMarkers.left.value) gamma02.mark(facet_marker, BoundaryMarkers.right.value) gamma03.mark(facet_marker, BoundaryMarkers.bottom.value) gamma04.mark(facet_marker, BoundaryMarkers.top.value) if dim == 3: gamma05 = dlfn.CompiledSubDomain("near(x[2], val) && on_boundary", val=first_point[2]) gamma06 = dlfn.CompiledSubDomain("near(x[2], val) && on_boundary", val=second_point[2]) gamma05.mark(facet_marker, BoundaryMarkers.back.value) gamma06.mark(facet_marker, BoundaryMarkers.front.value) return mesh, facet_marker
def test_mesh_is_periodic(tmpdir): """ """ os.chdir(str(tmpdir)) # Create a bunch of 2D meshes with different periodicity # and check that we detect this periodicity correctly. mesh1 = create_periodic_mesh(periodicity='none', dim=2) assert not mesh_is_periodic(mesh1, 'x') #assert not mesh_is_periodic(mesh1, 'y') assert not mesh_is_periodic(mesh1, 'xy') mesh2 = create_periodic_mesh(periodicity='x', dim=2) assert mesh_is_periodic(mesh2, 'x') #assert not mesh_is_periodic(mesh2, 'y') assert not mesh_is_periodic(mesh2, 'xy') mesh3 = create_periodic_mesh(periodicity='y', dim=2) assert not mesh_is_periodic(mesh3, 'x') #assert mesh_is_periodic(mesh3, 'y') assert not mesh_is_periodic(mesh3, 'xy') mesh4 = create_periodic_mesh(periodicity='xy', dim=2) assert mesh_is_periodic(mesh4, 'x') #assert mesh_is_periodic(mesh4, 'y') assert mesh_is_periodic(mesh4, 'xy') mesh_rectangle = df.RectangleMesh(df.Point(0, 0), df.Point(20, 10), 12, 8) assert mesh_is_periodic(mesh_rectangle, 'x') #assert mesh_is_periodic(mesh_rectangle, 'y') assert mesh_is_periodic(mesh_rectangle, 'xy') # Repeat this process for a bunch of 3D meshes with # different periodicity. mesh5 = create_periodic_mesh(periodicity='none', dim=3) assert not mesh_is_periodic(mesh5, 'x') #assert not mesh_is_periodic(mesh5, 'y') assert not mesh_is_periodic(mesh5, 'xy') mesh6 = create_periodic_mesh(periodicity='x', dim=3) assert mesh_is_periodic(mesh6, 'x') #assert not mesh_is_periodic(mesh6, 'y') assert not mesh_is_periodic(mesh6, 'xy') mesh7 = create_periodic_mesh(periodicity='y', dim=3) assert not mesh_is_periodic(mesh7, 'x') #assert mesh_is_periodic(mesh7, 'y') assert not mesh_is_periodic(mesh7, 'xy') mesh8 = create_periodic_mesh(periodicity='xy', dim=3) assert mesh_is_periodic(mesh8, 'x') #assert mesh_is_periodic(mesh8, 'y') assert mesh_is_periodic(mesh8, 'xy') mesh_box = df.BoxMesh(df.Point(0, 0, 0), df.Point(20, 10, 5), 12, 8, 3) assert mesh_is_periodic(mesh_box, 'x') #assert mesh_is_periodic(mesh_box, 'y') assert mesh_is_periodic(mesh_box, 'xy')
def main(): Nx = 12 Ny = Nx Nz = 40 * Nx mesh = df.BoxMesh(df.Point(0., 0., 0.), df.Point(1., 1., 40.), Nx, Ny, Nz) h5f = df.HDF5File(mesh.mpi_comm(), "simple_duct.h5", "w") h5f.write(mesh, "mesh") h5f.close()
def test_pbc2d_3dmesh2(): mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(50, 50, 3), 15, 15, 1) mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 1), 2, 2, 1) pbc = PeriodicBoundary2D(mesh) S = df.VectorFunctionSpace(mesh, "Lagrange", 1, constrained_domain=pbc) expr = df.Expression(('cos(x[0]+x[2])', 'sin(x[0]+x[2])', '0'), degree=1) M = df.interpolate(expr, S) #file = df.File('poisson.pvd') #file << M # df.plot(M) # df.interactive() print abs(M(0, 0, 1) - M(0.5, 0.5, 1))
def do_3d(self, sym, saved_ccube_pa=None): self.vkl_mesh = d.BoxMesh( d.Point(self.logvmin, self.khatmin, self.lmin), d.Point(self.logvmax, self.khatmax, self.lmax), self.nv, self.nk, self.nl ) self.ccube = ThreeDCoordinates(sym, self, 'P', 1) self.ccube.do_to_cube().do_dvk(saved_ccube_pa).do_dll().do_source_term() return self
def test_exchange_periodic_boundary_conditions(): mesh1 = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 0.1), 2, 2, 1) mesh2 = df.UnitCubeMesh(10, 10, 10) print(""" # for debugging, to make sense of output # testrun 0, 1 : mesh1 # testrun 2,3 : mesh2 # testrun 0, 2 : normal # testrun 1,3 : pbc """) testrun = 0 for mesh in [mesh1, mesh2]: pbc = PeriodicBoundary2D(mesh) S3_normal = df.VectorFunctionSpace(mesh, "Lagrange", 1) S3_pbc = df.VectorFunctionSpace(mesh, "Lagrange", 1, constrained_domain=pbc) for S3 in [S3_normal, S3_pbc]: print("Running test {}".format(testrun)) testrun += 1 FIELD_TOLERANCE = 6e-7 ENERGY_TOLERANCE = 0.0 m_expr = df.Expression(("0", "0", "1"), degree=1) m = Field(S3, m_expr, name='m') exch = Exchange(1) exch.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), 1)) field = exch.compute_field() energy = exch.compute_energy() print("m.shape={}".format(m.vector().array().shape)) print("m=") print(m.vector().array()) print("energy=") print(energy) print("shape=") print(field.shape) print("field=") print(field) H = field print "Asserted zero exchange field for uniform m = (1, 0, 0) " + \ "got H =\n{}.".format(H.reshape((3, -1))) print "np.max(np.abs(H)) =", np.max(np.abs(H)) assert np.max(np.abs(H)) < FIELD_TOLERANCE E = energy print "Asserted zero exchange energy for uniform m = (1, 0, 0), " + \ "Got E = {:g}.".format(E) assert abs(E) <= ENERGY_TOLERANCE
def test_dipolar_field_class(tmpdir): os.chdir(str(tmpdir)) H_dipole = DipolarField(pos=[0, 0, 0], m=[1, 0, 0], magnitude=3e9) mesh = df.BoxMesh(df.Point(-50, -50, -50), df.Point(50, 50, 50), 20, 20, 20) V = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3) m_field = Field(V, value=df.Constant((1, 0, 0))) H_dipole.setup(m_field, Field(df.FunctionSpace(m.mesh(), 'DG', 0), 8.6e5), unit_length=1e-9)
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 test_dmi_pbc2d(): mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(1, 1, 0.1), 2, 2, 1) pbc = PeriodicBoundary2D(mesh) S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, constrained_domain=pbc) m_expr = df.Expression(("0", "0", "1"), degree=1) m = Field(S3, m_expr, name='m') dmi = DMI(1) dmi.setup(m, Field(df.FunctionSpace(mesh, 'DG', 0), 1)) field = dmi.compute_field() assert np.max(field) < 1e-15
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 test_llb_sundials(do_plot=False): mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(2, 2, 2), 1, 1, 1) mat = Material(mesh, name='FePt', unit_length=1e-9) mat.set_m((1, 0, 0)) mat.T = 10 mat.alpha = 0.1 sim = LLB(mat) sim.set_up_solver() H0 = 1e5 sim.add(Zeeman((0, 0, H0))) dt = 1e-12 ts = np.linspace(0, 1000 * dt, 101) precession_coeff = sim.gamma_LL mz_ref = [] mxyz = [] mz = [] real_ts = [] for t in ts: sim.run_until(t) real_ts.append(sim.t) mz_ref.append(np.tanh(precession_coeff * mat.alpha * H0 * sim.t)) mz.append(sim.m[-1]) # same as m_average for this macrospin problem sim.m.shape = (3, -1) mxyz.append(sim.m[:, -1].copy()) sim.m.shape = (-1,) mxyz = np.array(mxyz) mz = np.array(mz) print np.sum(mxyz ** 2, axis=1) - 1 if do_plot: ts_ns = np.array(real_ts) * 1e9 plt.plot(ts_ns, mz, "b.", label="computed") plt.plot(ts_ns, mz_ref, "r-", label="analytical") plt.xlabel("time (ns)") plt.ylabel("mz") plt.title("integrating a macrospin") plt.legend() plt.savefig(os.path.join(MODULE_DIR, "test_llb.png")) print("Deviation = {}".format(np.max(np.abs(mz - mz_ref))))
def test_llb_save_data(): mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(10, 10, 5), 2, 2, 1) def region1(coords): if coords[2] < 0.5: return True else: return False def region2(coords): return not region1(coords) def init_Ms(coords): if region1(coords) > 0: return 8.6e5 else: return 8.0e5 def init_T(pos): return 1 * pos[2] mat = Material(mesh, name='FePt', unit_length=1e-9) mat.Ms = init_Ms mat.set_m((1, 0, 0)) mat.T = init_T mat.alpha = 0.1 assert(mat.T[0] == 0) sim = LLB(mat, name='test_llb') sim.set_up_solver() ts = np.linspace(0, 1e-11, 11) H0 = 1e6 sim.add(Zeeman((0, 0, H0))) sim.add(Exchange(mat)) demag = Demag(solver='FK') sim.add(demag) sim.save_m_in_region(region1, name='bottom') sim.save_m_in_region(region2, name='top') sim.schedule('save_ndt', every=1e-12) for t in ts: print 't===', t sim.run_until(t)