def spawn_children(self, p_state):
        """If intermediate minima are present, relaxes them and creates child nodes"""

        from spirit import chain, simulation

        if not self.allow_split:
            return

        if len(self.intermediate_minima) == 0:
            return

        if self._converged:
            return

        self.log("Spawning children - splitting chain")

        self.log("Relaxing intermediate minima")
        for idx_minimum in self.intermediate_minima:
            simulation.start(p_state,
                             simulation.METHOD_LLG,
                             self.solver_llg,
                             idx_image=idx_minimum)

        # Instantiate the GNEB nodes
        noi = chain.get_noi(p_state)
        # Creates a list of all indices that would be start/end points of new chains
        idx_list = [0, *self.intermediate_minima, noi - 1]
        # From the previous list, creates a list of pairs of start/end points
        idx_pairs = [(idx_list[i], idx_list[i + 1])
                     for i in range(len(idx_list) - 1)]

        # First create all the instances of GNEB nodes
        for i1, i2 in idx_pairs:
            self.add_child(i1, i2, p_state)
Exemple #2
0
def run(enable_output = True):
    passed = True
    field_center = []
    E = []

    for size in system_sizes:
        with state.State("") as p_state:
            parameters.llg.set_output_general(p_state, any=False)
            
            #turn ddi on
            hamiltonian.set_ddi(p_state, 1)

            #turn everything else off
            hamiltonian.set_exchange(p_state, 0, [])
            hamiltonian.set_dmi(p_state, 0, [])
            hamiltonian.set_anisotropy(p_state, 0, [0,0,1])
            hamiltonian.set_boundary_conditions(p_state, [0,0,0])
            hamiltonian.set_field(p_state, 0, [0,0,1])

            geometry.set_n_cells(p_state, [size, size, 1])
            
            configuration.plus_z(p_state)
            nos = system.get_nos(p_state)
            simulation.start(p_state, simulation.METHOD_LLG, simulation.SOLVER_VP, n_iterations = 1)
            Gradient_Spirit = np.array(system.get_effective_field(p_state)).reshape(nos, 3)
            E_Spirit = system.get_energy(p_state)
            field_center.append(Gradient_Spirit[int(size/2 + size/2 * size)])
            E.append(E_Spirit)
            
        if enable_output:
            with open(outputfile, 'w') as out:
                out.write("#system_size, field_center_z, energy\n")
                for i in range(len(E)):
                    out.write("{0}, {1}, {2}\n".format(system_sizes[i], field_center[i][2], E[i]))
    def run(self):
        passed = True

        with state.State(self.inputfile, quiet=True) as p_state:

            configuration.plus_z(p_state)
            # simulation.start(p_state, simulation.METHOD_LLG, simulation.SOLVER_SIB, n_iterations=1)
            system.update_data(p_state)

            E_Bf, E_Spirit = self.test_energy(p_state)

            Gradient_Bf, Gradient_Spirit = self.test_gradient(p_state)

            passed = True
            print('>>> Result 1: plus_z')
            print('E (Brute Force) = ', E_Bf)
            print('E (Spirit)      = ', E_Spirit)
            print('Avg. Grad (Brute Force) = ', np.mean(Gradient_Bf, axis=0))
            print('Avg. Grad (Spirit)      = ', np.mean(Gradient_Spirit,
                                                        axis=0))
            if np.abs(E_Bf - E_Spirit) > 1e-4:
                passed = False

            configuration.random(p_state)
            simulation.start(p_state,
                             simulation.METHOD_LLG,
                             simulation.SOLVER_SIB,
                             n_iterations=1)
            system.update_data(p_state)
            E_Bf, E_Spirit = self.test_energy(p_state)
            Gradient_Bf, Gradient_Spirit = self.test_gradient(p_state)
            passed = True
            print('\n>>> Result 2: random')
            print('E (Brute Force) = ', E_Bf)
            print('E (Spirit)      = ', E_Spirit)
            print('Avg. Grad (Brute Force) = ', np.mean(Gradient_Bf, axis=0))
            print('Avg. Grad (Spirit)      = ', np.mean(Gradient_Spirit,
                                                        axis=0))
            if np.abs(E_Bf - E_Spirit) > 1e-4:
                passed = False

            configuration.hopfion(p_state, 4)
            simulation.start(p_state,
                             simulation.METHOD_LLG,
                             simulation.SOLVER_SIB,
                             n_iterations=1)
            system.update_data(p_state)
            E_Bf, E_Spirit = self.test_energy(p_state)
            Gradient_Bf, Gradient_Spirit = self.test_gradient(p_state)
            passed = True
            print('\n>>> Result 3: hopfion')
            print('E (Brute Force) = ', E_Bf)
            print('E (Spirit)      = ', E_Spirit)
            print('Avg. Grad (Brute Force) = ', np.mean(Gradient_Bf, axis=0))
            print('Avg. Grad (Spirit)      = ', np.mean(Gradient_Spirit,
                                                        axis=0))
            if np.abs(E_Bf - E_Spirit) > 1e-4:
                passed = False

            return passed
Exemple #4
0
 def test_singleshot(self):
     configuration.plus_z(self.p_state)
     simulation.start(self.p_state,
                      LLG,
                      SIB,
                      n_iterations=1,
                      single_shot=True)
     simulation.single_shot(self.p_state)
     simulation.start(self.p_state, LLG, SIB, single_shot=True)
     simulation.single_shot(self.p_state)
     simulation.stop(self.p_state)
 def before_gneb_cb(gnw, p_state):
     # gneb.set_image_type_automatically(p_state)
     simulation.start(p_state,
                      simulation.METHOD_GNEB,
                      self.solver_gneb,
                      n_iterations=1)
     gnw.current_energy_path = data.energy_path_from_p_state(p_state)
     plotting.plot_energy_path(gnw.current_energy_path, plt.gca())
     mark_climbing_image(p_state, gnw, plt.gca())
     plt.savefig(gnw.output_folder +
                 "/path_{}_initial.png".format(gnw.total_iterations))
     plt.close()
Exemple #6
0
    def test_write(self):
        configuration.plus_z(self.p_state)
        configuration.skyrmion(self.p_state, radius=5, phase=-90)
        simulation.start(self.p_state, "LLG", "VP")
        system.update_eigenmodes(self.p_state)
        io.eigenmodes_write(self.p_state, io_image_test,
                            io.FILEFORMAT_OVF_TEXT)

        io.image_append(self.p_state, io_image_test, io.FILEFORMAT_OVF_TEXT,
                        "python io test")
        io.image_append(self.p_state, io_image_test, io.FILEFORMAT_OVF_TEXT,
                        "python io test")
Exemple #7
0
    def run(self):
        passed = True
        l_cube = 100
        radius = l_cube / 4

        with state.State(self.inputfile, quiet=True) as p_state:
            configuration.plus_z(p_state)
            simulation.start(p_state,
                             simulation.METHOD_LLG,
                             simulation.SOLVER_SIB,
                             n_iterations=1)
            system.update_data(p_state)

            #query some quantities
            nos = system.get_nos(p_state)
            field = np.array(system.get_effective_field(p_state)).reshape(
                nos, 3)
            pos = np.array(geometry.get_positions(p_state)).reshape(nos, 3)
            spins = np.array(system.get_spin_directions(p_state)).reshape(
                nos, 3)

            #get quantitities in sphere
            center = np.array([l_cube / 2, l_cube / 2, l_cube / 2], dtype=int)
            idx_in_sphere = np.linalg.norm(pos - center, axis=1) <= radius
            mu_s = np.array([1 if idx_in_sphere[i] else 0 for i in range(nos)])

            # field_bf = self.Gradient_DDI_BF(pos, spins, mu_s)
            # field_bf_in_sphere = field_bf[idx_in_sphere]

            field_in_sphere = field[idx_in_sphere]

            # deviation_sphere = np.std(field_in_sphere - mean_grad_sphere, axis=0)

            theory = np.array(
                [0, 0, 1]) * 2 / 3 * self.mu_0 * self.mu_B * self.mu_B * 1e30

            print("Mean field                  = ",
                  np.mean(field / self.mu_B, axis=0))
            # print("Mean field (BF)             = ", np.mean(field_bf/self.mu_B, axis=0))
            print("Mean field in sphere        = ",
                  np.mean(field_in_sphere / self.mu_B, axis=0))
            # print("Mean field in sphere (BF)   = ", np.mean(field_bf_in_sphere/self.mu_B, axis=0))
            print("Theory                      = ", theory)

        return passed
Exemple #8
0
def test_gradient(p_state, mu = None):
    
    nos = system.get_nos(p_state)
    pos = np.array(geometry.get_positions(p_state)).reshape(nos, 3)
    spins = np.array(system.get_spin_directions(p_state)).reshape(nos, 3)

    simulation.start(p_state, simulation.METHOD_LLG, simulation.SOLVER_SIB, n_iterations=1)
    system.update_data(p_state)
    
    if type(mu) == type(None):
        mu_s = np.ones(len(pos))
    else:
        mu_s = mu

    Gradient_BF = Gradient_DDI_BF(pos, spins, mu_s)
    Gradient_Spirit = np.array(system.get_effective_field(p_state)).reshape(nos, 3)

    return Gradient_BF, Gradient_Spirit
 def update_energy_path(self, p_state=None):
     """Updates the current energy path. If p_state is given we just use that, otherwise we have to construct it first"""
     self._log = False
     if p_state:
         self.current_energy_path = energy_path_from_p_state(p_state)
         self.noi = self.current_energy_path.noi()
     else:
         from spirit import state, chain, simulation
         with state.State(self.input_file) as p_state:
             chain.update_data(p_state)
             self._prepare_state(p_state)
             simulation.start(
                 p_state,
                 simulation.METHOD_GNEB,
                 self.solver_gneb,
                 n_iterations=1
             )  # One iteration of GNEB to get interpolated quantities
             self.update_energy_path(p_state)
     self._log = True
Exemple #10
0
    def run(self, enable_output=True):
        passed = True
        self.inputfile = "test_cases/input/input_saturated_film.cfg"

        theory = 0.5
        N_ITERATIONS = 1
        system_sizes = [10 * (i + 1) for i in range(5)]
        field_center = []
        E = []

        for size in system_sizes:
            with state.State(self.inputfile) as p_state:
                parameters.llg.set_output_general(p_state, any=False)
                geometry.set_n_cells(p_state, [size, size, 1])
                configuration.plus_z(p_state)
                nos = system.get_nos(p_state)

                simulation.start(p_state,
                                 simulation.METHOD_LLG,
                                 simulation.SOLVER_VP,
                                 n_iterations=1)

                Gradient_Spirit = np.array(
                    system.get_effective_field(p_state)).reshape(nos, 3)
                E_Spirit = system.get_energy(p_state)

                field_center.append(Gradient_Spirit[int(size / 2 +
                                                        size / 2 * size)])
                E.append(E_Spirit)

        if enable_output:
            with open('output_' + self.name + '.txt', 'w') as out:
                out.write("#system_size, field_center_z, energy\n")
                for i in range(len(E)):
                    out.write("{0}, {1}, {2}\n".format(system_sizes[i],
                                                       field_center[i][2],
                                                       E[i]))
Exemple #11
0
def run():
    with state.State("input/input_brute_force.cfg", quiet = True) as p_state:
        #turn ddi on
        hamiltonian.set_ddi(p_state, hamiltonian.DDI_METHOD_FFT, [4,4,4], 20)

        #turn everything else off
        hamiltonian.set_exchange(p_state, 0, [])
        hamiltonian.set_dmi(p_state, 0, [])
        hamiltonian.set_anisotropy(p_state, 0, [0,0,1])
        hamiltonian.set_boundary_conditions(p_state, [0,0,0])
        hamiltonian.set_field(p_state, 0, [0,0,1])

        #set a reasonable amount of basis cells
        geometry.set_n_cells(p_state, [5,5,5])

        configuration.plus_z(p_state)
        simulation.start(p_state, simulation.METHOD_LLG, simulation.SOLVER_SIB, n_iterations=1)
        E_Bf, E_Spirit = test_energy(p_state)
        Gradient_Bf, Gradient_Spirit = test_gradient(p_state)

        passed = True
        print('>>> Result 1: plus_z')
        print('E (Brute Force) = ', E_Bf)
        print('E (Spirit)      = ', E_Spirit)
        print('Avg. Grad (Brute Force) = ', np.mean(Gradient_Bf, axis = 0))
        print('Avg. Grad (Spirit)      = ', np.mean(Gradient_Spirit, axis = 0))
        if np.abs(E_Bf - E_Spirit) > tolerance:
            passed = False

        configuration.random(p_state)
        simulation.start(p_state, simulation.METHOD_LLG, simulation.SOLVER_SIB, n_iterations=1)
        E_Bf, E_Spirit = test_energy(p_state)
        Gradient_Bf, Gradient_Spirit = test_gradient(p_state)
        passed = True
        print('\n>>> Result 2: random')
        print('E (Brute Force) = ', E_Bf)
        print('E (Spirit)      = ', E_Spirit)
        print('Avg. Grad (Brute Force) = ', np.mean(Gradient_Bf, axis = 0))
        print('Avg. Grad (Spirit)      = ', np.mean(Gradient_Spirit, axis = 0))
        if np.abs(E_Bf - E_Spirit) > tolerance:
            passed = False

        configuration.hopfion(p_state, 4)
        simulation.start(p_state, simulation.METHOD_LLG, simulation.SOLVER_SIB, n_iterations=1)
        E_Bf, E_Spirit = test_energy(p_state)
        Gradient_Bf, Gradient_Spirit = test_gradient(p_state)
        passed = True
        print('\n>>> Result 3: hopfion')
        print('E (Brute Force) = ', E_Bf)
        print('E (Spirit)      = ', E_Spirit)
        print('Avg. Grad (Brute Force) = ', np.mean(Gradient_Bf, axis = 0))
        print('Avg. Grad (Spirit)      = ', np.mean(Gradient_Spirit, axis = 0))
        if np.abs(E_Bf - E_Spirit) > tolerance:
            passed = False
        return passed
def estimate_mc_runtime(p_state, total_iterations, n_iterations_test=500):
    """Estimates the total run time of 'total iterations' monte carlo steps by measuring `n_iterations_test` monte carlo steps"""
    from spirit import simulation
    from spirit import parameters

    parameters.mc.set_iterations(p_state, n_iterations_test, n_iterations_test) # We want n_iterations iterations and only a single log message
    info = simulation.start(p_state, simulation.METHOD_MC) # Start a MC simulation

    # total_iterations = len(sample_temperatures) * (n_samples*n_decorrelation + n_thermalisation)
    runtime_seconds = total_iterations / info.total_ips

    hours   = int( (runtime_seconds / (60**2)) )
    minutes = int( (runtime_seconds - hours * 60**2) / 60 )
    seconds = int( (runtime_seconds - hours * 60**2 - minutes*60) )

    print("Estimated runtime = {:.0f}h:{:.0f}m:{:.0f}s".format( hours, minutes, seconds ) )
    print("Total iterations  = {:.0f}".format( total_iterations ) )
    print("IPS               = {:.0f}".format( info.total_ips ) )

    return runtime_seconds
Exemple #13
0
 def test_playpause(self):
     configuration.plus_z(self.p_state)
     configuration.skyrmion(p_state, 5)
     simulation.start(self.p_state, LLG, SIB)
Exemple #14
0
    # Loop over temperatures
    for iT, T in enumerate(sample_temperatures):
        parameters.mc.set_temperature(p_state, T)

        # Cumulative average variables
        E = 0
        E2 = 0
        M = 0
        M2 = 0
        M4 = 0

        # Thermalisation
        parameters.mc.set_iterations(
            p_state, n_thermalisation, n_thermalisation
        )  # We want n_thermalisation iterations and only a single log message
        simulation.start(p_state, MC)  # Start a MC simulation

        # Sampling at given temperature
        parameters.mc.set_iterations(
            p_state, n_decorrelation * n_samples, n_decorrelation * n_samples
        )  # We want n_decorrelation iterations and only a single log message
        simulation.start(p_state, MC,
                         single_shot=True)  # Start a single-shot MC simulation
        for n in range(n_samples):
            # Run decorrelation
            for i_decorr in range(n_decorrelation):
                simulation.single_shot(p_state)  # one MC iteration
            # Get energy
            E_local = system.get_energy(p_state) / NOS
            # Get magnetization
            M_local = np.array(quantities.get_magnetization(p_state))
    def run(self):
        """Run GNEB with checks after a certain number of iterations"""
        if (len(self.children) !=
                0):  # If not a leaf node call recursively on children
            self.run_children()
            return

        try:
            self.log("Running")

            from spirit import state, simulation, io
            self._converged = False
            self.increase_noi()

            with state.State(self.input_file) as p_state:
                self._prepare_state(p_state)
                self.update_energy_path(p_state)

                # Another callback at which the chain actually exists now, theoretically one could set image types here
                if self.before_gneb_callback:
                    self.before_gneb_callback(self, p_state)

                try:
                    self.log("Starting GNEB iterations")
                    n_checks = 0
                    while (self.check_run_condition()):

                        info = simulation.start(
                            p_state,
                            simulation.METHOD_GNEB,
                            self.solver_gneb,
                            n_iterations=self.n_iterations_check)
                        self.update_energy_path(p_state)
                        self.check_for_minima(
                        )  # Writes the intermediate minima list
                        n_checks += 1
                        self.total_iterations += info.total_iterations

                        # Log some information
                        self.log("Total iterations = {}".format(
                            self.total_iterations))
                        self.log("      max.torque = {}".format(
                            info.max_torque))
                        self.log("      ips        = {}".format(
                            info.total_ips))
                        self.log("      Delta E    = {}".format(
                            self.current_energy_path.barrier()))

                        self._converged = info.max_torque < self.convergence

                        self.history.append(
                            [self.total_iterations, info.max_torque])

                        # Step callback to e.g plot chains
                        if (self.gneb_step_callback):
                            self.gneb_step_callback(self, p_state)

                        # Save the chain periodically
                        if (n_checks % self.n_checks_save == 0):
                            self.save_chain(p_state)

                        # Rebalancing
                        # self.chain_rebalance(p_state)

                except KeyboardInterrupt as e:
                    self.log("Interrupt during run loop")
                    self.save_chain(p_state)
                    if (self.exit_callback):
                        self.exit_callback(self, p_state)
                    raise e

                if self.before_llg_callback:
                    self.before_llg_callback(self, p_state)

                self.update_energy_path(p_state)

                self.spawn_children(p_state)

                self.save_chain(p_state)

                if (self.exit_callback):
                    self.exit_callback(self, p_state)

                # p_state gets deleted here, it does not have to persist to run the child nodes
            self.run_children()
            self.log("Finished!")

        except Exception as e:
            self.log("Exception during 'run': {}".format(
                str(e)))  # Log the exception and re-raise
            self.log(traceback.format_exc())
            raise e
Exemple #16
0
def run_simulation(i_state, Mtd, Slvr, convThr, tS, K, Kdir, Exchange, DMI,
                   Dij, alphaD, x_size, y_size, read_config, lc):
    Skyrmion_size = 0
    calc_ittr = 0
    js = 0  # current value
    STTdir = [0, 0, 0]  # polarization direction
    hdir = [0.0, 0.0, 1.0]  # magnetic Field direction
    hval = 0
    sim_count = 0
    load_fname = 'start.ovf'
    startup = True

    while True:
        clear_screen()
        if startup:  # load initial state or set up new state
            #initialize ddi
            usr_in = collect_input(int, 'Load state from file (0/1)?: ')
            if usr_in == 1:
                load_fname = collect_input(str, 'Enter filename to load: ')
                print('\nLoading {:s}...\n'.format(load_fname))
                io.chain_read(i_state, load_fname)
                print('Done!\n')
            startup = False
            continue
        #end if startup block

        usr_in = collect_input(
            str,
            'Enter command:\nl to load\nm to minimize\nr to run simulation\np to plot\nmtd for set method\nq to quit\n'
        )
        print('\n')

        if usr_in == 'l':
            clear_screen()

            usr_in = collect_input(
                int,
                'Create or ammend to state, Load state from file, or exit (0/1/-1)?: '
            )
            if usr_in == 1:
                load_fname = collect_input(str, 'Enter filename to load: ')
                print('\nLoading {:s}...\n'.format(load_fname))
                io.chain_read(i_state, load_fname)
                print('Done!\n')
            elif usr_in == 0:
                usr_in = collect_input(
                    int,
                    'Set state None, Random, skyrmion, plus-z, minus-z, other settings (0/1/2/3/4/5): '
                )

                #initialize initial conditions of simulation
                print('Setting up initial state...\n')
                if not read_config:  #if config file was set, dont set custom lattice size or BC
                    hamiltonian.set_dmi(i_state, 1, [DMI], 1)
                    geometry.set_n_cells(i_state, [x_size, y_size, 1])
                    hamiltonian.set_boundary_conditions(i_state, [1, 1, 0])
                parameters.llg.set_temperature(i_state, 0.0)
                parameters.llg.set_damping(i_state, alphaD)
                parameters.llg.set_convergence(i_state, convThr)
                parameters.llg.set_output_configuration(i_state, True, True, 4)
                hamiltonian.set_field(i_state, hval, hdir)
                parameters.llg.set_stt(i_state, True, 0, STTdir)
                parameters.llg.set_timestep(i_state, tS)
                parameters.llg.set_iterations(i_state, 1, 1)
                #hamiltonian.set_dmi(i_state,1,[40],chirality=2)
                if usr_in == 1:
                    print('Initilizing random state...\n')
                    configuration.random(i_state)  #initialize random
                    pass
                elif usr_in == 2:
                    Skyrmion_size = collect_input(int, "Enter Skyrmion size: ")
                    phase = collect_input(float, 'Enter Skyrmion phase: ')
                    anti = collect_input(int,
                                         'Antiskyrmion or skyrmion (0/1)?: ')
                    pos = [0, 0, 0]
                    for i in range(len(pos)):
                        pos[i] = collect_input(
                            int,
                            'Enter position {:d} for skyrmion (keep z = 0): '.
                            format(i + 1))
                    print('Initilizing Skyrmion...\n')
                    configuration.skyrmion(i_state, Skyrmion_size, 1, phase,
                                           False, anti,
                                           pos)  #initialize skyrmion
                    if os.path.isfile("start.ovf"):
                        os.remove("start.ovf")
                        pass
                    pass
                elif usr_in == 3:
                    print('Setting all spins to +z...\n')
                    configuration.plus_z(i_state)
                    pass
                elif usr_in == 4:
                    print('Setting all spins to -z...\n')
                    configuration.minus_z(i_state)
                elif usr_in == 5:
                    convThr = collect_input(
                        float,
                        'enter Value for convergance threshold (default is 1e-12): '
                    )
        #end load block
        elif usr_in == 'p':
            usr_in = 1
            while usr_in == 1:
                usr_in = collect_input(int, '-1 to exit, 1 to plot.')
                if usr_in == 1:
                    usr_in = input("enter file name to plot: ")
                    xs = collect_input(int, 'x = ')
                    ys = collect_input(int, 'y = ')
                    plot_out.Plot_Lattice(usr_in, xs, ys)
                    usr_in = 1
        #end plotting block
        elif usr_in == 'm':
            clear_screen()
            sim_count = 0
            usr_in = 0

            while usr_in != -1:
                usr_in = collect_input(int, 'preform minimization?(-1/1): ')
                if usr_in == 1:
                    sim_time = collect_input(float,
                                             'set minimize time in fs: ')
                    calc_ittr = int(sim_time * 0.001 / tS)  #n_fs * fs/(dt*ps)
                    hval = collect_input(
                        float,
                        'enter H field strength: ')  # magnetic Field direction
                    js = 0
                    hval = convert_from_dimcord_j(DMI, Exchange, js, hval,
                                                  x_size, y_size, lc)[1]

                    print('H = {:f}T'.format(hval))
                    parameters.llg.set_temperature(i_state, 0.0)
                    parameters.llg.set_damping(i_state, alphaD)
                    parameters.llg.set_convergence(i_state, convThr)
                    parameters.llg.set_timestep(i_state, tS)
                    hamiltonian.set_field(i_state, hval, hdir)
                    parameters.llg.set_stt(i_state, True, 0, [0, 0, 0])
                    #minimize
                    print('Minimizing\n')
                    parameters.llg.set_iterations(i_state, calc_ittr,
                                                  calc_ittr)
                    simulation.start(i_state, simulation.METHOD_LLG,
                                     simulation.SOLVER_VP)
                    cur_fname = 'min_{:d}.ovf'.format(sim_count)
                    if os.path.isfile(cur_fname):
                        os.remove(cur_fname)
                        pass
                    io.chain_write(i_state, cur_fname)
                    simulation.stop_all(i_state)
                    plot_out.Plot_Lattice(cur_fname, x_size, y_size)
                    print('Done!\n')
                    sim_count += 1
                continue
        #end minimize block
        elif usr_in == 'mtd':
            clear_screen()
            #set values
            divider = 2
            current_time = collect_input(float,
                                         "amount of time to apply current: ")
            relax_time = collect_input(float, "amount of time to relax: ")
            begin = collect_input(float, 'enter begining: ')
            end = collect_input(float, 'enter end: ')
            count = collect_input(float, 'enter step size: ')
            current_time = int(current_time * 0.001 / tS)
            relax_time = int(relax_time * 0.001 / tS)
            for i, sim_num in enumerate(
                    np.linspace(begin,
                                end, (end - begin) / count,
                                endpoint=True)):
                configuration.plus_z(i_state)
                hval = sim_num
                temp = convert_from_dimcord_j(DMI, Exchange, 0.883, hval,
                                              x_size, y_size, lc)
                hval = temp[1]
                current = temp[0]
                print('running set method...\n')
                #set per-run parameters
                parameters.llg.set_temperature(i_state, 0)
                parameters.llg.set_damping(i_state, alphaD)
                parameters.llg.set_convergence(i_state, convThr)
                parameters.llg.set_timestep(i_state, tS)

                #apply current block
                parameters.llg.set_stt(i_state, True, current, [0, -1, 0])
                hamiltonian.set_field(i_state, hval, [0, 0, 1])
                calc_ittr = int(6000 * 0.001 / tS)
                parameters.llg.set_iterations(i_state, calc_ittr / divider, 0)

                start = time.time()
                for i in range(1, divider + 1):
                    simulation.start(i_state, Mtd, Slvr)
                    io.chain_write(
                        i_state, '{:d}of{:d}_current_{:4.2f}.ovf'.format(
                            i, divider, hval))
                    simulation.stop_all(i_state)
                end = time.time()
                print(end - start)
                #turn off current and relax
                parameters.llg.set_stt(i_state, True, 0, [0, 0, 0])
                hamiltonian.set_field(i_state, 16, [0, 0, 1])
                calc_ittr = int(6000 * 0.001 / tS)
                parameters.llg.set_iterations(i_state, relax_time, 0)
                simulation.start(i_state, Mtd, Slvr)
                simulation.stop_all(i_state)
                io.chain_write(i_state, 'current_off_{:4.2f}.ovf'.format(hval))
            #end set method

        elif usr_in == 'r':
            clear_screen()
            sim_count = 0
            sim_time = 0
            prev_ittr = 0
            prev_sim_time = 0
            calc_ittr = 0
            #set per-run parameters
            parameters.llg.set_temperature(i_state, 0)
            parameters.llg.set_damping(i_state, alphaD)
            parameters.llg.set_convergence(i_state, convThr)
            parameters.llg.set_timestep(i_state, tS)
            while True:
                sim_time = collect_input(
                    float,
                    'set time to run in fs, 0 to use last used values, -1 to exit simulation mode: '
                )
                if isclose(sim_time, -1, 1e-8):
                    break
                elif isclose(sim_time, 0, 1e-8):
                    if sim_count == 0:
                        print('Run one simulation first!\n')
                        continue
                    calc_ittr = prev_ittr
                    print(
                        'H = {:f}T\nJ = {:f}microAmps\nP = ({:f},{:f},{:f})\nItterations = {:d} = {:f}fs'
                        .format(hval, 1e+6 * js, STTdir[0], STTdir[1],
                                STTdir[2], int(prev_ittr), prev_sim_time))
                elif (sim_time <
                      (tS / 0.001)) and (not isclose(sim_time, (tS / 0.001),
                                                     (tS / 0.001) / 10.0)):
                    print('Enter a larger value!\n')
                    continue
                else:
                    calc_ittr = int(float(sim_time) * 0.001 /
                                    tS)  #n_fs * fs/(dt*ps)
                    prev_ittr = calc_ittr
                    prev_sim_time = sim_time
                    hval = collect_input(
                        float,
                        'enter H field strength: ')  # magnetic Field direction
                    js = collect_input(
                        float, 'enter current val: '
                    )  # Spin Torque magnitude EDIT SET TO 0 norm 3e-04
                    temp = convert_from_dimcord_j(DMI, Exchange, js, hval,
                                                  x_size, y_size, lc)
                    if isclose(0, js, 1e-7):
                        js = 0.0
                    else:
                        js = temp[0]
                    hval = temp[1]
                    for i in range(len(STTdir)):
                        STTdir[i] = collect_input(
                            float,
                            'input Polerization element {:d}: '.format(i + 1))
                    print(
                        'H = {:f}T\nJ = {:f}microAmps\nP = ({:f},{:f},{:f})\nItterations = {:d} = {:f}fs'
                        .format(hval, 1e+6 * js, STTdir[0], STTdir[1],
                                STTdir[2], int(prev_ittr), sim_time))
                #end quit/re-run/new-sim block

                print('Running simulation...\n')

                cur_fname = 'r_{:d}.ovf'.format(sim_count)
                if os.path.isfile(cur_fname):
                    #if current filename already exists within directory
                    #remove it
                    os.remove(cur_fname)

                parameters.llg.set_stt(i_state, True, js, STTdir)
                hamiltonian.set_field(i_state, hval, hdir)
                parameters.llg.set_iterations(i_state, calc_ittr, 0)

                start = time.time()
                simulation.start(i_state, Mtd, Slvr)
                end = time.time()
                io.chain_write(i_state, cur_fname)
                simulation.stop_all(i_state)

                print('Done! Elapsed time: {:f}\n'.format(end - start))
                plot_out.Plot_Lattice(cur_fname, x_size, y_size)
                sim_count += 1
                continue
            #while not (sim_time == -1):
        #end run simulation block
        elif usr_in == 'q':
            #break and exit loop to quit program
            break
    clear_screen()
    return (0)  #run_simulation
Exemple #17
0
from spirit import state
from spirit import configuration
from spirit import simulation
from spirit import hamiltonian
from spirit import io

cfgfile = "../input/input.cfg"
quiet = False

with state.State(cfgfile, quiet) as p_state:
    ### Read Image from file
    # spinsfile = "input/spins.ovf"
    # io.image_from_file(state.get(), spinsfile, idx_image=0);

    ### First image is homogeneous with a skyrmion in the center
    configuration.plus_z(p_state, idx_image=0)
    configuration.skyrmion(p_state, 200.0, phase=0.0, idx_image=0)
    configuration.set_region(p_state,
                             region_id=1,
                             pos=[0, 0, 0],
                             border_rectangular=[100, 100, 1],
                             idx_image=0)
    hamiltonian.set_field_m(p_state, 200, [0, 0, 1], 0)
    hamiltonian.set_field_m(p_state, 200, [0, 0, -1], 1)
    ### LLG dynamics simulation
    LLG = simulation.METHOD_LLG
    LBFGS_OSO = simulation.SOLVER_LBFGS_OSO  # Velocity projection minimiser

    simulation.start(p_state, LLG, LBFGS_OSO)
    io.image_write(p_state, "out.ovf")
Exemple #18
0
import sys

### Make sure to find the Spirit modules
### This is only needed if you did not install the package
spirit_py_dir = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "../core/python"))
sys.path.insert(0, spirit_py_dir)

### Import Spirit modules
from spirit import state
from spirit import configuration
from spirit import simulation
from spirit import io

cfgfile = "input/input.cfg"
quiet = False

with state.State(cfgfile, quiet) as p_state:
    ### Read Image from file
    # spinsfile = "input/spins.ovf"
    # io.image_from_file(state.get(), spinsfile, idx_image=0);

    ### First image is homogeneous with a skyrmion in the center
    configuration.plus_z(p_state, idx_image=0)
    configuration.skyrmion(p_state, 5.0, phase=-90.0, idx_image=0)

    ### LLG dynamics simulation
    LLG = simulation.METHOD_LLG
    DEPONDT = simulation.SOLVER_DEPONDT  # Velocity projection minimiser
    simulation.start(p_state, LLG, DEPONDT)
Exemple #19
0
    # io.image_from_file(state.get(), spinsfile, idx_image=0);
    ### Read Chain from file
    # io.chain_from_file(state.get(), chainfile);

    ### First image is homogeneous with a skyrmion in the center
    configuration.plus_z(p_state, idx_image=0)
    configuration.skyrmion(p_state, 5.0, phase=-90.0, idx_image=0)
    ### Last image is homogeneous
    configuration.plus_z(p_state, idx_image=noi - 1)

    ### Initial guess: homogeneous transition between first and last image
    transition.homogeneous(p_state, 0, noi - 1)

    ### Energy minimisation of first and last image
    LLG = simulation.METHOD_LLG
    GNEB = simulation.METHOD_GNEB
    VP = simulation.SOLVER_VP  # Velocity projection minimiser
    simulation.start(p_state, LLG, VP, idx_image=0)
    simulation.start(p_state, LLG, VP, idx_image=noi - 1)

    ### Initial relaxation of transition path
    simulation.start(p_state, GNEB, VP, n_iterations=10000)
    ### Full relaxation with climbing image
    parameters.gneb.set_image_type_automatically(p_state)
    simulation.start(p_state, GNEB, VP)

    ### Calculate the energy barrier of the transition
    E = chain.get_energy(p_state)
    delta = max(E) - E[0]
    log.send(p_state, log.LEVEL_ALL, log.SENDER_ALL,
             "Energy barrier: {} meV".format(delta))