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 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_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 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)
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_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 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 test_scipy_advance_time_zero_first(): mesh = df.UnitIntervalMesh(10) sim = Simulation(mesh, Ms=1, unit_length=1e-9, integrator_backend="scipy") sim.set_m((1, 0, 0)) sim.advance_time(0) sim.advance_time(1e-12) sim.advance_time(2e-12) sim.advance_time(2e-12) sim.advance_time(2e-12)
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 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 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 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 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)
def test_spatially_varying_alpha_using_Simulation_class(): """ test that I can change the value of alpha through the property sim.alpha and that I get an df.Function back. """ length = 20 simplices = 10 mesh = df.IntervalMesh(simplices, 0, length) sim = Simulation(mesh, Ms=1, unit_length=1e-9) sim.alpha = 1 expected_alpha = np.ones(simplices + 1) assert np.array_equal(sim.alpha.vector().array(), expected_alpha)
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)
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))
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 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 compare_with_analytic_solution(alpha=0.5, max_t=1e-9): """ Compares the C/dolfin/odeint solution to the analytical one. """ print "Running comparison with alpha={0}.".format(alpha) # define 3d mesh x0 = y0 = z0 = 0 x1 = y1 = z1 = 10e-9 nx = ny = nz = 1 mesh = dolfin.BoxMesh(dolfin.Point(x0, x1, y0), dolfin.Point(y1, z0, z1), nx, ny, nz) sim = Simulation(mesh, Ms=1) sim.alpha = alpha sim.set_m((1, 0, 0)) sim.add(Zeeman((0, 0, 1e6))) # plug in an integrator with lower tolerances sim.set_tol(abstol=1e-12, reltol=1e-12) ts = numpy.linspace(0, max_t, num=100) ys = numpy.array([(sim.advance_time(t), sim.m.copy())[1] for t in ts]) tsfine = numpy.linspace(0, max_t, num=1000) m_analytical = make_analytic_solution(1e6, alpha, sim.gamma) save_plot(ts, ys, tsfine, m_analytical, alpha) TOLERANCE = 1e-6 # tolerance on Ubuntu 11.10, VM Hans, 25/02/2012 rel_diff_maxs = list() for i in range(len(ts)): m = numpy.mean(ys[i].reshape((3, -1)), axis=1) m_ref = m_analytical(ts[i]) diff = numpy.abs(m - m_ref) diff_max = numpy.max(diff) rel_diff_max = numpy.max(diff / numpy.max(m_ref)) rel_diff_maxs.append(rel_diff_max) print "t= {0:.3g}, diff_max= {1:.3g}.".format(ts[i], diff_max) msg = "Diff at t= {0:.3g} too large.\nAllowed {1:.3g}. Got {2:.3g}." assert diff_max < TOLERANCE, msg.format(ts[i], TOLERANCE, diff_max) print "Maximal relative difference: " print numpy.max(numpy.array(rel_diff_maxs))
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
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
def t_test_sim_ode_parallel(do_plot=False): mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(2, 2, 2), 1, 1, 1) sim = Sim(mesh, 8.6e5, unit_length=1e-9, pbc='2d', parallel=True) sim.alpha = alpha sim.set_m((1, 0, 0)) sim.set_tol(1e-10, 1e-14) H0 = 1e5 sim.add(Zeeman((0, 0, H0))) # sim.add(Exchange(1.3e-11)) dt = 1e-12 ts = np.linspace(0, 500 * dt, 100) precession_coeff = sim.gamma / (1 + alpha**2) mz_ref = np.tanh(precession_coeff * alpha * H0 * ts) mzs = [] length_error = [] for t in ts: sim.run_until(t) mm = sim.m.copy() # mm.shape=(3,-1) # mx,my,mz = mm[:,0] # same as m_average for this macrospin problem mzs.append(mm[-1]) #length = np.sqrt(mx**2+my**2+mz**2) # length_error.append(abs(length-1.0)) if do_plot: ts_ns = ts * 1e9 plt.plot(ts_ns, mzs, "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_sim_ode.png")) print("Deviation = {}, total value={}".format(np.max(np.abs(mzs - mz_ref)), mz_ref)) assert np.max(np.abs(mzs - mz_ref)) < 1e-9
def create_simulation(): from finmag.util.meshes import ellipsoid #mesh = df.IntervalMesh(10,0,30) #mesh = df.RectangleMesh(0,0,10,2,5,1) mesh = ellipsoid(30, 10, 10, maxh=3.0) sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9) sim.set_m((1, 1, 1)) sim.add(Exchange(1.3e-11)) sim.add(UniaxialAnisotropy(-1e5, (0, 0, 1), name='Kp')) sim.add(UniaxialAnisotropy(1e4, (1, 0, 0), name='Kx')) return sim
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
def setup_sim(self, m0): SX, SY, SZ = 116, 60, 20 nx, ny, nz = 29, 15, 5 # Fe, ref: PRB 69, 174428 (2004) # A = 2.5e-6 erg/cm^3 # M_s = 1700 emu/cm^3 # gamma = 2.93 GHz/kOe Ms = 1700e3 A = 2.5e-6*1e-5 gamma_wrong = 2.93*1e6/Oersted_to_SI(1.) # wrong by a factor of 6 (?) Hzeeman = [10e3*Oersted_to_SI(1.), 0, 0] mesh = df.BoxMesh(0, 0, 0, SX, SY, SZ, nx, ny, nz) sim = Simulation(mesh, Ms) sim.set_m(m0) sim.add(Demag()) sim.add(Exchange(A)) sim.add(Zeeman(Hzeeman)) return sim
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
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()
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
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"))
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