def test_script_missing_terms(self): # Missing Gilbert damping alpha self.system.dynamics = oc.Precession(gamma=2.2) td = oc.TimeDriver() script = td.script(self.system, t=1e-9, n=20) assert "alpha 0" in script assert "gamma_G 2.2" in script # Missing gamma self.system.dynamics = oc.Damping(alpha=5) td = oc.TimeDriver() script = td.script(self.system, t=1e-9, n=20) assert "alpha 5" in script assert "gamma_G 221100" in script
def overhead(): """Run a macrospin example for 1 ps through oommfc and directly and return the difference in run times. Returns ------- overhead : float The time difference (overhead) between running OOMMF though oommfc and directly """ # Running OOMMF through oommfc. system = oc.examples.macrospin() td = oc.TimeDriver() oommfc_start = time.time() td.drive(system, t=1e-12, n=1) oommfc_stop = time.time() oommfc_time = oommfc_stop - oommfc_start # Running OOMMF directly. oommf_runner = get_oommf_runner() mifpath = os.path.realpath('example-macrospin/example-macrospin.mif') oommf_start = time.time() oommf_runner.call(mifpath) oommf_stop = time.time() oommf_time = oommf_stop - oommf_start return oommfc_time - oommf_time
def status(): """Run a macrospin example for 1 ps through oommfc and print the OOMMF status. Returns ------- int If ``0``, the OOMMF is found and running. Otherwise, ``1`` is returned. Examples -------- 1. Checking the OOMMF status. >>> import oommfc as oc ... >>> oc.oommf.status() Running OOMMF... OOMMF found and running. 0 """ system = mm.examples.macrospin() try: td = oc.TimeDriver() td.drive(system, t=1e-12, n=1) print('OOMMF found and running.') return 0 except (EnvironmentError, RuntimeError): print('Cannot find OOMMF.') return 1
def test_script(self): driver = oc.TimeDriver() t = 1e-9 n = 120 script = driver.script(self.system, t=t, n=n) assert script[0] == "#" assert script[-1] == "1" assert script.count("#") == 3 assert script.count("Specify") == 2 assert script.count("Destination") == 2 assert script.count("Schedule") == 2 assert script.count("mmArchive") == 2 assert script.count("Stage") == 2 assert "Oxs_RungeKuttaEvolve" in script assert "Oxs_TimeDriver" in script assert "Oxs_FileVectorField" in script lines = script.split("\n") alpha = self.system.dynamics.damping.alpha assert lines[2] == " alpha {}".format(alpha) gamma = self.system.dynamics.precession.gamma assert lines[3] == " gamma_G {}".format(gamma) assert lines[9] == " stopping_time {}".format(t / n) assert lines[11] == " stage_count {}".format(n) assert lines[12] == " Ms {}".format(8e5) assert lines[17] == " file m0.omf" assert lines[20] == " basename tds"
def status(): """Run a macrospin example for 1 ps through oommfc and print the OOMMF status. """ try: system = oc.examples.macrospin() td = oc.TimeDriver() td.drive(system, t=1e-12, n=1) print('OOMMF found and running.') return 0 except (EnvironmentError, RuntimeError): print("Cannot find OOMMF.") return 1
def test_stdprob5(): name = "stdprob5" # Remove any previous simulation directories. if os.path.exists(name): shutil.rmtree(name) # Geometry lx = 100e-9 # x dimension of the sample(m) ly = 100e-9 # y dimension of the sample (m) lz = 10e-9 # sample thickness (m) # Material (permalloy) parameters Ms = 8e5 # saturation magnetisation (A/m) A = 1.3e-11 # exchange energy constant (J/m) # Dynamics (LLG + STT equation) parameters gamma = 2.211e5 # gyromagnetic ratio (m/As) alpha = 0.1 # Gilbert damping ux = -72.35 # velocity in x direction beta = 0.05 # non-adiabatic STT parameter system = oc.System(name=name) mesh = oc.Mesh(p1=(0, 0, 0), p2=(100e-9, 100e-9, 10e-9), cell=(5e-9, 5e-9, 5e-9)) system.mesh = mesh system.hamiltonian = oc.Exchange(A) + oc.Demag() def m_vortex(pos): x, y, z = pos[0] / 1e-9 - 50, pos[1] / 1e-9 - 50, pos[2] / 1e-9 return (-y, x, 10) system.m = df.Field(mesh, value=m_vortex, normalisedto=Ms) md = oc.MinDriver() md.drive(system) system.dynamics += oc.Precession(gamma) + oc.Damping(alpha) + \ oc.STT(u=(ux, 0, 0), beta=beta) td = oc.TimeDriver() td.drive(system, t=8e-9, n=100) mx = system.dt["mx"].as_matrix() assert -0.03 < mx.max() < 0 assert -0.35 < mx.min() < -0.30 shutil.rmtree(name)
def test_save_mif(self): driver = oc.TimeDriver() t = 1e-9 n = 120 driver._makedir(self.system) driver._save_mif(self.system, t=t, n=n) miffilename = os.path.join("tds", "tds.mif") assert os.path.isfile(miffilename) lines = open(miffilename, "r").readlines() assert lines[0] == "# MIF 2.1\n" assert lines[-1][-1] == "1" shutil.rmtree("tds")
def effective_field(self): _dict = { "Demag": "Oxs_Demag::Field", "Exchange": "Oxs_UniformExchange::Field", "UniaxialAnisotropy": "Oxs_UniaxialAnisotropy::Field", "Zeeman": "Oxs_FixedZeeman::Field", "Hamiltonian": "Oxs_RungeKuttaEvolve:evolver:Total field" } td = oc.TimeDriver() td.drive(self.system, derive=_dict[self.cls]) dirname = os.path.join(self.system.name, "") ohf_file = max(glob.iglob("{}*.ohf".format(dirname)), key=os.path.getctime) return df.read(ohf_file)
def energy(self): _dict = { "Demag": "Demag::Energy", "Exchange": "UniformExchange::Energy", "UniaxialAnisotropy": "UniaxialAnisotropy::Energy", "Zeeman": "FixedZeeman::Energy", "Hamiltonian": "RungeKuttaEvolve:evolver:Totalenergy" } td = oc.TimeDriver() td.drive(self.system, derive="energy") dirname = os.path.join(self.system.name, "") odt_file = max(glob.iglob("{}*.odt".format(dirname)), key=os.path.getctime) dt = oommfodt.read(odt_file, replace_columns=False) return dt[_dict[self.cls]][0]
def test_stdprobfmr(): name = "stdprobfmr" # Remove any previous simulation directories. if os.path.exists(name): shutil.rmtree(name) lx = ly = 120e-9 # x and y dimensions of the sample(m) lz = 10e-9 # sample thickness (m) dx = dy = dz = 10e-9 # discretisation in x, y, and z directions (m) Ms = 8e5 # saturation magnetisation (A/m) A = 1.3e-11 # exchange energy constant (J/m) H = 8e4 * np.array([0.81345856316858023, 0.58162287266553481, 0.0]) alpha = 0.008 # Gilbert damping gamma = 2.211e5 mesh = oc.Mesh(p1=(0, 0, 0), p2=(lx, ly, lz), cell=(dx, dy, dz)) system = oc.System(name="stdprobfmr") system.hamiltonian = oc.Exchange(A) + oc.Demag() + oc.Zeeman(H) system.dynamics = oc.Precession(gamma) + oc.Damping(alpha) system.m = df.Field(mesh, value=(0, 0, 1), norm=Ms) md = oc.MinDriver() md.drive(system) H = 8e4 * np.array([0.81923192051904048, 0.57346234436332832, 0.0]) system.hamiltonian.zeeman.H = H T = 20e-9 n = 4000 td = oc.TimeDriver() td.drive(system, t=T, n=n) t = system.dt['t'].as_matrix() my = system.dt['mx'].as_matrix() psd = np.log10(np.abs(scipy.fftpack.fft(my))**2) f_axis = scipy.fftpack.fftfreq(4000, d=20e-9/4000) shutil.rmtree(name)
def test_drive(self): md = oc.TimeDriver() md.drive(self.system, t=0.1e-9, n=10) assert os.path.exists("tds") miffilename = os.path.join("tds", "tds.mif") assert os.path.isfile(miffilename) omf_files = list(glob.iglob("tds/*.omf")) odt_files = list(glob.iglob("tds/*.odt")) assert len(omf_files) == 11 omffilename = os.path.join("tds", "m0.omf") assert omffilename in omf_files assert len(odt_files) == 1 shutil.rmtree("tds")
def energy_density(self): _dict = { "Demag": "Oxs_Demag::Energy density", "Exchange": "Oxs_UniformExchange::Energy density", "UniaxialAnisotropy": ("Oxs_UniaxialAnisotropy::" "Energy density"), "Zeeman": "Oxs_FixedZeeman::Energy density", "Hamiltonian": ("Oxs_RungeKuttaEvolve:evolver:" "Total energy density") } td = oc.TimeDriver() td.drive(self.system, derive=_dict[self.cls]) dirname = os.path.join(self.system.name, "") oef_file = max(glob.iglob("{}*.oef".format(dirname)), key=os.path.getctime) return df.read(oef_file)
def overhead(): """Run a macrospin example for 1 ps through ``oommfc`` and directly and return the difference in run times. Returns ------- float The time difference (overhead) between running OOMMF though ``oommfc`` and directly. Examples -------- 1. Getting the overhead time. >>> import oommfc as oc ... >>> isinstance(oc.oommf.overhead(), float) Running OOMMF... True """ # Running OOMMF through oommfc. system = mm.examples.macrospin() td = oc.TimeDriver() oommfc_start = time.time() td.drive(system, t=1e-12, n=1, save=True, overwrite=True) oommfc_stop = time.time() oommfc_time = oommfc_stop - oommfc_start # Running OOMMF directly. oommf_runner = get_oommf_runner() mifpath = os.path.realpath( os.path.join(system.name, 'drive-0', 'macrospin.mif')) oommf_start = time.time() oommf_runner.call(mifpath) oommf_stop = time.time() oommf_time = oommf_stop - oommf_start oc.delete(system) return oommfc_time - oommf_time
def overhead(): """Run a macrospin example for 1 ps through ``oommfc`` and directly and return the difference in run times. Returns ------- float The time difference (overhead) between running OOMMF though ``oommfc`` and directly. Examples -------- 1. Getting the overhead time. >>> import oommfc as oc ... >>> isinstance(oc.oommf.overhead(), float) Running OOMMF... True """ with tempfile.TemporaryDirectory() as workingdir: with uu.changedir(workingdir): # Running OOMMF through oommfc. system = mm.examples.macrospin() td = oc.TimeDriver() oommfc_start = time.time() td.drive(system, t=1e-12, n=1) oommfc_stop = time.time() oommfc_time = oommfc_stop - oommfc_start # Running OOMMF directly. oommf_runner = oc.runner.runner mifpath = pathlib.Path(f"{system.name}/drive-0/macrospin.mif").resolve() oommf_start = time.time() oommf_runner.call(str(mifpath)) oommf_stop = time.time() oommf_time = oommf_stop - oommf_start return oommfc_time - oommf_time
def test_silent(capsys): md = oc.MinDriver() md.drive(mm.examples.macrospin()) captured = capsys.readouterr() assert "Running OOMMF" in captured.out assert captured.err == "" md.drive(mm.examples.macrospin(), verbose=2) captured = capsys.readouterr() assert "Running OOMMF" in captured.out assert captured.err == "" td = oc.TimeDriver() td.drive(mm.examples.macrospin(), t=1e-10, n=10, verbose=2) captured = capsys.readouterr() assert captured.out == "" assert "files written" in captured.err # tqdm output on stderr md.drive(mm.examples.macrospin(), verbose=0) captured = capsys.readouterr() assert captured.out == "" assert captured.err == ""
def compute(func, system): """Computes a particular value of an energy term or energy container (``energy``, ``density``, or ``effective_field``). Parameters ---------- func : callable A property of an energy term or an energy container. system : micromagneticmodel.System Micromagnetic system for which the property is calculated. Returns ------- numbers.Real, discretisedfield.Field Resulting value. Examples -------- 1. Computing values of energy terms. >>> import micromagneticmodel as mm >>> import oommfc as oc ... >>> system = mm.examples.macrospin() >>> oc.compute(system.energy.zeeman.energy, system) Running OOMMF... -8.8...e-22 >>> oc.compute(system.energy.effective_field, system) Running OOMMF... Field(...) >>> oc.compute(system.energy.density, system) Running OOMMF... Field(...) """ td = oc.TimeDriver(total_iteration_limit=1) td.drive(system, t=1e-25, n=1, append=True, compute=schedule_script(func, system)) if func.__name__ == 'energy': extension = '*.odt' elif func.__name__ == 'effective_field': extension = '*.ohf' elif func.__name__ == 'density': extension = '*.oef' dirname = os.path.join(system.name, f'compute-{system.compute_number-1}') output_file = max(glob.iglob(os.path.join(dirname, extension)), key=os.path.getctime) if func.__name__ == 'energy': table = ut.Table.fromfile(output_file, rename=False) if isinstance(func.__self__, mm.Energy): output = table.data['RungeKuttaEvolve:evolver:Total energy'][0] else: output = table.data[(f'{oxs_class(func.__self__, system)}:' f'{func.__self__.name}:Energy')][0] else: output = df.Field.fromfile(output_file) return output
def test_drive_exception(self): md = oc.TimeDriver() with pytest.raises(ValueError): md.drive(self.system, t=-0.1e-9, n=10) with pytest.raises(ValueError): md.drive(self.system, t=0.1e-9, n=-10)
def test_stdprob4(): name = "stdprob4" # Remove any previous simulation directories. if os.path.exists(name): shutil.rmtree(name) L, d, th = 500e-9, 125e-9, 3e-9 # (m) cellsize = (5e-9, 5e-9, 3e-9) # (m) mesh = oc.Mesh((0, 0, 0), (L, d, th), cellsize) system = oc.System(name=name) A = 1.3e-11 # (J/m) system.hamiltonian = oc.Exchange(A) + oc.Demag() gamma = 2.211e5 # (m/As) alpha = 0.02 system.dynamics = oc.Precession(gamma) + oc.Damping(alpha) Ms = 8e5 # (A/m) system.m = df.Field(mesh, value=(1, 0.25, 0.1), norm=Ms) md = oc.MinDriver() md.drive(system) # updates system.m in-place dirname = os.path.join(name, "") miffilename = os.path.join(name, "{}.mif".format(name)) assert os.path.exists(dirname) assert os.path.isfile(miffilename) omf_files = list(glob.iglob("{}/*.omf".format(name))) odt_files = list(glob.iglob("{}/*.odt".format(name))) assert len(omf_files) == 2 omffilename = os.path.join(name, "m0.omf") assert omffilename in omf_files assert len(odt_files) == 1 shutil.rmtree(name) H = (-24.6e-3/oc.mu0, 4.3e-3/oc.mu0, 0) system.hamiltonian += oc.Zeeman(H) td = oc.TimeDriver() td.drive(system, t=1e-9, n=200) dirname = os.path.join(name, "") miffilename = os.path.join(name, "{}.mif".format(name)) assert os.path.exists(dirname) assert os.path.isfile(miffilename) omf_files = list(glob.iglob("{}/*.omf".format(name))) odt_files = list(glob.iglob("{}/*.odt".format(name))) assert len(omf_files) == 201 omffilename = os.path.join(name, "m0.omf") assert omffilename in omf_files assert len(odt_files) == 1 myplot = system.dt.plot("t", "my") figfilename = os.path.join(name, "stdprob4-t-my.pdf") myplot.figure.savefig(figfilename) assert os.path.isfile(figfilename) t = system.dt["t"].as_matrix() my = system.dt["my"].as_matrix() assert abs(min(t) - 5e-12) < 1e-20 assert abs(max(t) - 1e-9) < 1e-20 # Eye-norm test. assert 0.7 < max(my) < 0.8 assert -0.5 < min(my) < -0.4 shutil.rmtree(name)
>>> oc.compute(system.energy.zeeman.energy, system) Running OOMMF... -8.8...e-22 >>> oc.compute(system.energy.effective_field, system) Running OOMMF... Field(...) >>> oc.compute(system.energy.density, system) Running OOMMF... Field(...) """ if system.T > 0: raise RuntimeError("`oc.compute` does not support finite temperature." f" (Temperature is specified as {system.T=})") td = oc.TimeDriver(total_iteration_limit=1) workingdir = td._setup_working_directory(system=system, dirname=dirname, mode="compute", append=append) with uu.changedir(workingdir): td.write_mif( system=system, t=1e-25, n=1, ovf_format=ovf_format, compute=schedule_script(func, system), ) td._call(system=system, runner=runner, n_threads=n_threads,
shutil.rmtree(name) L = 30e-9 # (m) cellsize = (10e-9, 15e-9, 5e-9) # (m) mesh = oc.Mesh((0, 0, 0), (L, L, L), cellsize) system = oc.System(name=name) A = 1.3e-11 # (J/m) H = (1e6, 0.0, 2e5) system.hamiltonian = oc.Exchange(A=A) + oc.Zeeman(H=H) gamma = 2.211e5 # (m/As) alpha = 0.02 system.dynamics = oc.Precession(gamma) + oc.Damping(alpha) Ms = 8e5 # (A/m) system.m = df.Field(mesh, value=(0.0, 0.25, 0.1), norm=Ms) td = oc.TimeDriver() td.drive(system, t=25e-12, n=25) # updates system.m in-place td.drive(system, t=15e-12, n=15) td.drive(system, t=5e-12, n=10) md = oc.MinDriver() md.drive(system) system.hamiltonian.zeeman.H = (0.0, 0.0, 1.0e6) td.drive(system, t=5e-12, n=5) md.drive(system)
import oommfc as mc # import mumaxc as mc import discretisedfield as df L = 10e-9 d = 1e-9 Ms = 8e6 # saturation magnetisation (A/m) A = 1e-12 # exchange energy constant (J/m) H = (5e6, 0, 0) # external magnetic field in the x-direction (A/m) gamma = 2.211e5 # gamma parameter (m/As) alpha = 0.2 # Gilbert damping mesh = mc.Mesh(p1=(0, 0, 0), p2=(L, L, L), cell=(d, d, d)) system = mc.System(name='example2') system.hamiltonian = mc.Exchange(A=A) + mc.Demag() + mc.Zeeman(H=H) system.dynamics = mc.Precession(gamma=gamma) + mc.Damping(alpha=alpha) system.m = df.Field(mesh, value=(0, 0, 1), norm=Ms) td = mc.TimeDriver() td.drive(system, t=1e-9, n=10, overwrite=True) mx, my, mz = system.m.average assert mx > my assert mx > mz print(system.m.average)