def run_sim(sim): # Specify magnetic material, parameters chosen as in example 1 Py = nmag.MagMaterial(name="Py", Ms=SI(1e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m")) # Load the mesh sim.load_mesh('sphere.nmesh.h5', [('sphere', Py)], unit_length=SI(1e-9, 'm')) # Set the initial magnetisation sim.set_m([1, 0, 0]) # Save the demagnetisation field sim.save_data(fields=['H_demag']) # Probe the demagnetisation field at ten points within the sphere results = [] for i in range(-5, 6): x = i * 1e-9 Hdemag = sim.probe_subfield_siv('H_demag', [x, 0, 0]) results.append(Hdemag) print "x=", x, ": H_demag = ", Hdemag return results
def main(): MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) L = 10 mesh_unit = SI(1e-9, "m") # mesh unit (1 nm) layers = [(0.0, L)] # the mesh discretization = 0.1 # discretization # Initial magnetization xfactor = float(SI("m") / (L * mesh_unit)) def m0(r): return [ np.cos(r[0] * np.pi * xfactor), np.sin(r[0] * np.pi * xfactor), 0 ] mat_Py = nmag.MagMaterial(name="Py", Ms=SI(1, "A/m")) sim = nmag.Simulation("Hans' configuration", do_demag=False) mesh_file_name = '1d.nmesh' mesh_lists = unidmesher.mesh_1d(layers, discretization) unidmesher.write_mesh(mesh_lists, out=mesh_file_name) sim.load_mesh(mesh_file_name, [("Py", mat_Py)], unit_length=mesh_unit) sim.set_m(m0) np.save(os.path.join(MODULE_DIR, "nmag_hansconf.npy"), sim.get_subfield("E_exch_Py"))
def simulate_resonance(freq, amplitude=A_mag, dt=SI(5 * 1e-12, "s"), time_steps=800): sim.set_m([0, 0, 1]) angle_step = (2 * math.pi * freq * dt).value result = [] for i in range(time_steps): h_ext = [amplitude.value * math.sin(i * angle_step), 0, 0] sim.set_H_ext(h_ext, SI(1, "A/m")) sim.advance_time(i * dt) a = sim.get_subfield_average_siv("M", "Py") result.append((i * dt, h_ext, a)) return result
def advance_time(self, target_time, max_it=-1): # To get the time in SI units you could do as follows, for now time_su = float(target_time / SI("s")) # ^^^ dividing an SI("s") object by an SI("s") object you get # an SI(1) object, which can be safely cast to a float number. # if target_time is not a SI("s"), but - for example - an SI("m") # then the float will fail: # float(SI("m")/SI("s")) == float(SI("m/s")) delta_t = SI(1e-12, "s") self.clock['time'] += delta_t self.clock['stage_time'] += delta_t self.clock['step'] += 1 self.clock['stage_step'] += 1 return self.clock['time']
def pinning(p): x, y, z = p tmp = float(SI(x, "m")/(mesh_unit*hl)) if abs(tmp) >= 0.999: return 0.0 else: return 1.0
def amplitude(f_GHz): res = simulate_resonance(SI(f_GHz * 1e9, "1/s")) osc = [[r[0].value, r[2][0], r[2][1], r[2][2]] for r in res[400:]] # skip lead_in (f, params) = nmag.fit_oscillation(osc) a = math.sqrt(sum([p[1] * p[1] for p in params])) return -a # we minimize -(amplitude)!
def generate_anisotropy_data(anis, name='anis'): # Create the material mat_Py = nmag.MagMaterial(name="Py", Ms=SI(Ms, "A/m"), anisotropy=anis) # Create the simulation object sim = nmag.Simulation(name, do_demag=False) # Load the mesh sim.load_mesh("bar.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9, "m")) # Set the initial magnetisation sim.set_m(lambda r: m_gen(np.array(r) * 1e9)) #sim.advance_time(SI(1e-12, 's') ) # Save the exchange field and the magnetisation once at the beginning # of the simulation for comparison with finmag np.savetxt("H_%s_nmag.txt" % name, sim.get_subfield("H_anis_Py")) np.savetxt("m0_nmag.txt", sim.get_subfield("m_Py"))
def my_stage(sim): # run the function before every stage start H_ext = sim.get_subfield_average_siv('H_ext') print('Set new H_ext of stage %d with H_ext %s' %(sim.stage, str(H_ext))) def set_H(position): x = position[0] y = position[1] z = position[2] return H_ext sim.set_H_ext(set_H, unit=SI(1,'A/m'))
def amplitude(freq_GHz): a_data = simulate_resonance(SI(freq_GHz * 1e9, "1/s")) o_data = [[a[0].value, a[2][0], a[2][1], a[2][2]] for a in a_data] (fit_freq, fit_params) = nmag.fit_oscillation(o_data[5000:]) # skip lead-in a = math.sqrt(sum([p[1] * p[1] for p in fit_params])) print "Freq: %.2f GHz -- Amplitude: %f" % (freq_GHz, a) r.write("Freq: %.2f GHz -- Amplitude: %f\n" % (freq_GHz, a)) # DDD r.flush() # DDD r2.write(" ]\n\n\n") r2.flush() return -a # we minimize the *negative* amplitude here!
def run_simulation(simname, meshfile, hmatrix=None, tol=0.000001): T_start = time.time() sim = nmag.Simulation(name=simname, phi_BEM=hmatrix) Ni = nmag.MagMaterial(name="Ni", Ms=SI(493380, "A/m"), exchange_coupling=SI(7.2e-12, "J/m"), llg_damping=1.0) ps = SI(1e-12, "s") sim.load_mesh(meshfile, [("thinfilm", Ni)], unit_length=SI(1e-9, "m")) sim.set_m([0.05, 0.02, 1.00]) sim.set_params(ts_abs_tol=tol, ts_rel_tol=tol) sim.set_H_ext([0, 0, 0], SI('A/m')) dt = SI(5e-12, "s") T_end = time.time() T_setup = T_end - T_start T_start = time.time() sim.relax(save=[('averages', every('time', 10 * ps))]) T_end = time.time() T_sim = T_end - T_start sim.save_data(['m']) number_nodes = len(sim.mesh.points) mem_rss = get_memory_of_process() / 1024.0 return [number_nodes, mem_rss, T_setup, T_sim]
def run_simulation(sim_name, initial_m, damping, stopping_dm_dt, j, P=0.0, save=[], do=[], do_demag=True): # Define the material mat = nmag.MagMaterial( name="mat", Ms=SI(0.8e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m"), llg_damping=damping, llg_xi=SI(0.01), llg_polarisation=P) # Create the simulation object and load the mesh sim = nmag.Simulation(sim_name, do_demag=do_demag) sim.load_mesh(mesh_name, [("np", mat)], unit_length=mesh_unit) # Set the pinning at the top and at the bottom of the nanopillar def pinning(p): x, y, z = p tmp = float(SI(x, "m")/(mesh_unit*hl)) if abs(tmp) >= 0.999: return 0.0 else: return 1.0 sim.set_pinning(pinning) if type(initial_m) == str: # Set the initial magnetisation sim.load_m_from_h5file(initial_m) # a) from file if a string is provided else: sim.set_m(initial_m) # b) from function/vector, otherwise if j != 0.0: # Set the current, if needed sim.set_current_density([j, 0.0, 0.0], unit=SI("A/m^2")) # Set additional parameters for the time-integration and run the simulation sim.set_params(stopping_dm_dt=stopping_dm_dt, ts_rel_tol=1e-7, ts_abs_tol=1e-7) sim.relax(save=save, do=do) return sim
def run_sim(tol): """Function that is called repeatedly with different tolerance values. Each function call is carrying out one simulation. """ mat_Py = nmag.MagMaterial(name="Py", Ms=SI(0.86e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m"), llg_damping=0.5) #compose name of simulation to inlude value of tolerance sim = nmag.Simulation("bar_%.6f" % tol) sim.load_mesh("bar30_30_100.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9, "m")) sim.set_m([1, 0, 1]) #set tolerance (has to be called after set_m()) sim.set_params(ts_abs_tol=tol, ts_rel_tol=tol) dt = SI(2.5e-12, "s") timing = 0 #initialise variable to measure execution time for i in range(0, 121): timing -= time.time() #start measuring time sim.advance_time(dt * i) #compute time development for 300ps timing += time.time() #stop measuring time #we exclude time required to save data sim.save_data() #save averages every 2.5 ps #at end of simulation, write performance data into summary file f = open('resultsummary.txt', 'a') #open file to append f.write('%g %d %g\n' % (tol, sim.clock['step'], timing)) f.close()
def simulate_resonance( freq, amplitude=A_mag, dt=SI(1e-12, "s"), # 1 ps time step is reasonable here. time_steps=6000 # We simulate six full oscillations at 1 GHz ): sim.set_m([0, 0, 1]) angle_step = (2 * math.pi * freq * dt).value result = [] for i in range(time_steps): h_ext = [amplitude.value * math.sin(i * angle_step), 0, 0] r.write("T=%s h_ext=%s" % (str(i * dt), str(h_ext))) sim.set_H_ext(h_ext, SI(1, "A/m")) sim.advance_time(i * dt) avg = sim.get_subfield_average_siv( "M", "Py") # XXX Why is this not in the manual? # XXX Note: counter-intuitive: get_subfield_average_siv("M","M_Py") does not work! r.write(" AVG=%s\n" % repr(avg)) r2.write(" [%f,%f,%f],\n" % (i, avg[0], avg[1])) r2.flush() result.append((i * dt, h_ext, avg)) return result
def check_switching_field(s): m = s.get_subfield_average('m') mz = abs(m[2]) if len(reference_mz) == 0: reference_mz.append(mz) else: (mz0, ) = reference_mz if mz < 0.05*mz0: f = open("switching_fields.dat", "a") H = [float(Hi/SI('A/m')) for Hi in Hs[s.stage-1]] f.write("%g %g %g %g\n" % tuple([pb.angle] + H)) s.hysteresis_exit() f.close() print "check_switching_field: done!"
from nmag import SI, every, at from nsim.si_units import si import math # Create simulation object (no demag field!) sim = nmag.Simulation(do_demag=False) # Function to compute the scalar product of the vectors a and b def scalar_product(a, b): return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] # Here we define a function which returns the energy for a uniaxial # anisotropy of order 4. K1 = SI(43e3, "J/m^3") K2 = SI(21e3, "J/m^3") axis = [0, 0, 1] # The (normalised) axis def my_anisotropy(m): a = scalar_product(axis, m) return -K1 * a**2 - K2 * a**4 my_material = nmag.MagMaterial(name="MyMat", Ms=SI(1e6, "A/m"), exchange_coupling=SI(10e-12, "J/m"), anisotropy=my_anisotropy, anisotropy_order=4)
import nmag from nmag import SI, mesh import os mat_Py = nmag.MagMaterial(name="Py", Ms=SI(1e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m")) #sim = nmag.Simulation() sim = nmag.Simulation(ddd_use_linalg_machine=True) sim.set_H_ext([0, 0, 0], SI(1, "A/m")) meshfile = os.path.join("barmini.nmesh.h5") if os.path.exists(meshfile): sim.load_mesh(meshfile, [("PyX", mat_Py)], unit_length=SI(1e-9, "m")) else: sim.defregion("Py", mesh.box([0.0, 0.0, 0.0], [20, 20, 80]), mat_Py) mesh = sim.generate_mesh( ([0.0, 0.0, 0.0], [20.0, 20.0, 80.0]), # bounding box a0=4.0, max_steps=10, unit_length=SI(1e-9, "m")) mesh.save(meshfile) def initial_magnetization(xyz, mag_type): import math return [math.cos(xyz[2]), math.sin(xyz[2]), 0.0]
import nmag from nmag import SI import math # define magnetic material Py = nmag.MagMaterial(name="Py", Ms=SI(1e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m"), llg_damping=SI(0.02, "")) # lattice spacings along the main axes; # the value must be zero for no periodic copies, # equal to the mesh dimension along the # given axis otherwise x_lattice = 30.0 y_lattice = 0.0 z_lattice = 0.0 # list to store the lattice points where the periodic # copies will be placed lattice_points = [] for xi in range(-1, 2): lattice_points.append([xi * x_lattice, 0.0 * y_lattice, 0.0 * z_lattice]) # copies of the system along the x-axis pbc = nmag.SetLatticePoints(vectorlist=lattice_points, scalefactor=SI(1e-9, 'm')) #create simulation object sim = nmag.Simulation(periodic_bc=pbc.structure)
import nmag, sys from nmag import SI try: meshfile = sys.argv[1] datafile = sys.argv[2] except IndexError: print 'Usage: nmsim %s meshfile outputdatafile' % sys.argv[0] sys.exit(1) #create simulation object sim = nmag.Simulation() # define magnetic material Py = nmag.MagMaterial(name='Py', Ms=SI(1.0, 'A/m'), exchange_coupling=SI(13.0e-12, 'J/m')) # load mesh sim.load_mesh(meshfile, [('sphere', Py)], unit_length=SI(1e-9, 'm')) # set initial magnetisation sim.set_m([1, 0, 0]) # set external field sim.set_H_ext([0, 0, 0], SI('A/m')) # Save and display data in a variety of ways sim.save_data(fields='all') # save all fields spatially resolved # together with average data
##magnetisation vs time py doc import nmag from nmag import SI, at #create a simulation object sim = nmag.Simulation() #define magnetic material matd_Py = nmag.MagMaterial(name="Py", Ms=SI(0.86e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m"), llg_damping=0.5) #load mesh: the mesh dimensions are scaled by 100nm sim.load_mesh("bar30_30_100.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9, "m")) #set initial magnetisation sim.set_m([1,0,1]) #dynamic process, compute the time development over certain amount of time. dt = SI(5e-12, "s") #for loop in which "i" will take values for subsequent iterations. #compute time development for i in range(0,61): sim.advance_time(dt*i) #every 10 loop iterations, save avg and all if i % 10 == 0: sim.save_data(fields="all") #otherwise save avg. else:
# One dimensional magnetic system studied using nsim import numpy as np import nmag from nmag import SI import nmeshlib.unidmesher as unidmesher # Details about the layers and the mesh and the material length = 20.0 # in nanometers mesh_unit = SI(1e-9, "m") # mesh unit (1 nm) layers = [(0.0, length)] # the mesh discretization = 2.0 # discretization # Initial magnetization xfactor = float(SI("m") / (length * mesh_unit)) def m0(r): x = max(0.0, min(1.0, r[0] * xfactor)) mx = 2.0 * x - 1.0 my = (1.0 - mx * mx)**0.5 return [mx, my, 0.0] dx = 0.5 * float(discretization * mesh_unit / SI("m")) xmin = dx xmax = float(length * mesh_unit / SI("m")) - dx def pin(r): p = (1.0 if xmin <= r[0] <= xmax else 0.0) return p
import nmag from nmag import SI mat_Py = nmag.MagMaterial(name="Py", Ms=SI(0.86e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m"), llg_damping=0.5) sim = nmag.Simulation("bar") sim.load_mesh("coarse_bar.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9, "m")) #sim.load_mesh("bar.nmesh.h5", # [("Py", mat_Py)], # unit_length=SI(1e-9,"m")) sim.set_m([1, 0, 1]) dt = SI(5e-12, "s") ###### # After ten time steps, plot the energy density # from z=0nm to z=100nm through the center of the body. ###### sim.advance_time(dt * 10) f = open("nmag_exch_Edensity.txt", "w") f2 = open("nmag_demag_Edensity.txt", "w") for i in range(100): f.write("%g " %
def print_time(sim): sim_time = float(sim.time / SI(1e-12, 's')) print('----SIM Time %f ps----' % sim_time)
import nmag from nmag import SI, every # This basic simulation gives us an idea about the relaxation properties # of the system. # We find that it takes about 200 frames to do one full oscillation, # which corresponds to a frequency of about f=1 GHz. #create simulation object sim = nmag.Simulation() # define magnetic material Py = nmag.MagMaterial(name='Py', Ms=SI(1e6, 'A/m'), llg_damping=0.02, exchange_coupling=SI(13.0e-12, 'J/m')) # load mesh sim.load_mesh('rod.nmesh.h5', [('rod', Py)], unit_length=SI(1e-9, 'm')) # set initial magnetisation sim.set_m([1, 0, 0.1]) # set external field sim.set_H_ext([0, 0, 0], SI('A/m')) sim.relax(save=[('fields', every('time', SI(5e-12, "s")))])
import nmag from nmag import SI, at #create simulation object sim = nmag.Simulation() # define magnetic material Py = nmag.MagMaterial(name="Py", Ms=SI(1e6,"A/m"), exchange_coupling=SI(13.0e-12, "J/m")) # load mesh: the mesh dimensions are scaled by 0.5 nm sim.load_mesh("ellipsoid.nmesh.h5", [("ellipsoid", Py)], unit_length=SI(1e-9,"m")) # set initial magnetisation sim.set_m([1.,0.,0.]) Hs = nmag.vector_set(direction=[1.,0.01,0], norm_list=[ 1.00, 0.95, [], -1.00, -0.95, -0.90, [], 1.00], units=1e6*SI('A/m')) # loop over the applied fields Hs sim.hysteresis(Hs, save=[('restart','fields', at('convergence'))])
import time #need this to measure execution time import nmag from nmag import SI, every, at mat_Py = nmag.MagMaterial(name="Py", Ms=SI(0.86e6,"A/m"), exchange_coupling=SI(13.0e-12, "J/m"), llg_damping=SI(0.5,"")) sim = nmag.Simulation() sim.load_mesh("bar30_30_100.nmesh.h5", [("Py", mat_Py)], unit_length=SI(1e-9,"m")) sim.set_m([1,0,1]) #Need to call advance time to create timestepper ps = SI(1e-12, "s") sim.advance_time(0*ps) sim.get_timestepper().set_params(rel_tolerance=1e-8,abs_tolerance=1e-8) starttime = time.time()
import nmag import time from nmag import SI sim = nmag.Simulation() # Specify magnetic material, parameters chosen as in example 1 Py = nmag.MagMaterial(name="Py", Ms=SI(1e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m")) # Load the mesh sim.load_mesh('sphere.nmesh.h5', [('sphere', Py)], unit_length=SI(1e-9, 'm')) # Set the initial magnetisation sim.set_m([1, 0, 0]) # Save the demagnetisation field sim.save_data(fields=['H_demag']) # Probe the demagnetisation field at ten points within the sphere for i in range(-5, 6): x = i * 1e-9 Hdemag = sim.probe_subfield_siv('H_demag', [x, 0, 0]) print "x=", x, ": H_demag = ", Hdemag
# One dimensional magnetic system studied using nsim import numpy as np import nmag from nmag import SI import nmeshlib.unidmesher as unidmesher # Details about the layers and the mesh and the material length = 100.0 # in nanometers mesh_unit = SI(1e-9, "m") # mesh unit (1 nm) layers = [(0.0, length)] # the mesh discretization = 2.0 # discretization # Initial magnetization xfactor = float(SI("m") / (length * mesh_unit)) def m0(r): x = max(0.0, min(1.0, r[0] * xfactor)) mx = x mz = 0.1 my = (1.0 - (mx * mx * 0.99 + mz * mz)) ** 0.5 return [mx, my, mz] # Create the material mat_Py = nmag.MagMaterial(name="Py", Ms=SI(0.86e6, "A/m"), exchange_coupling=SI(0, "J/m"), # disables exchange? anisotropy=nmag.uniaxial_anisotropy( axis=[0, 0, 1], K1=SI(520e3, "J/m^3")), llg_gamma_G=SI(0.2211e6, "m/A s"), llg_damping=SI(0.2),
import math import time import nmag from nmag.common import * from nmag import SI, every, at mesh_file = 'cubes.nmesh.h5' sim = nmag.Simulation() # height hard_h = 6.0 soft_h = 4.0 # Saturation Magnetization -- M M_hard = SI(0.5e6, 'A/m') M_soft = SI(1.2e6, 'A/m') # exchange coupling strength -- A A_hard = SI(1.2e-11, "J/m") A_soft = SI(2.8e-11, "J/m") # Anisotropy -- K K_hard = SI((55 * 1.38e-23 * 350 / 25e-27 - 100 * soft_h) / hard_h, "J/m^3") K_soft = SI(100.0, "J/m^3") Mat_Hard = nmag.MagMaterial(name='Mat_Hard', Ms=M_hard, exchange_coupling=A_hard, anisotropy=nmag.uniaxial_anisotropy( axis=[0, 0, -1.0], K1=K_hard), llg_damping=1.0) Mat_Soft = nmag.MagMaterial(name='Mat_Soft', Ms=M_soft,
import nmag from nmag import SI, mesh import nmesh import os, sys H_x = SI(0.0e6, "A/m") H_y = SI(0.0e6, "A/m") H_z = SI(0.0e6, "A/m") intensive_param_by_name = {"H_x": H_x, "H_y": H_y, "H_z": H_z} mat_Py = nmag.MagMaterial(name="Py", Ms=SI(1e6, "A/m"), exchange_coupling=SI(13.0e-12, "J/m")) sim = nmag.Simulation("sphere", fem_only=True) unit_length = SI(1e-9, "m") meshfile = "sphere-test-rho-phi2.nmesh" sim.load_mesh(meshfile, [("void", []), ("Py", mat_Py)], unit_length=unit_length) def initial_magnetization((x, y, z), mag_type): return [1, 0, 0] sim.set_magnetization(initial_magnetization) sim.compute_H_fields() sim.fun_update_energies([])
import math import time import nmag from nmag.common import * from nmag import SI, every, at mesh_file = 'cubes.nmesh.h5' sim = nmag.Simulation() # height hard_h = 4.0 soft_h = 6.0 # Saturation Magnetization -- M ms_hard = 0.5e6 M_hard = SI(ms_hard, 'A/m') M_soft = SI(1.2e6, 'A/m') # Exchange coupling strength -- A A_hard = SI(1.2e-11, "J/m") A_soft = SI(2.8e-11, "J/m") # Anisotropy -- K Stability_constant = 55 * 1.38e-23 * 350 # Stability Constant Area_constant = 25e-27 # Area Constant = area * 1e-9 ku_soft = 100.0 ku_hard = (Stability_constant / Area_constant - ku_soft * soft_h) / hard_h print('ku_hard %f' % ku_hard) K_hard = SI(ku_hard, "J/m^3") K_soft = SI(ku_soft, "J/m^3") # Max Apply Field H_max = 2 * ku_hard * 1e4 / ms_hard H_max = H_max * 1e3 / (4 * math.pi) # koe to A/m print('H_max %f' % H_max)