def test():

    INPUT_FILE = os.path.join(SCRIPT_DIR, "inputs/test_plotting.cfg")

    from spirit import state, configuration

    with state.State(INPUT_FILE) as p_state:
        configuration.plus_z(p_state)
        configuration.hopfion(p_state, 7)
        # configuration.skyrmion(p_state, 7)

        system = data.spin_system_from_p_state(p_state)

        plotter = pyvista_plotting.Spin_Plotter(system)
        plotter.camera_position = 'yz'
        plotter.camera_azimuth = 45
        plotter.camera_elevation = 50

        # plotter.compute_delaunay()
        # plotter.save_delaunay("delaunay.vtk")
        plotter.load_delaunay("delaunay.vtk")

        # plotter.add_preimage([1,0,0], tol=0.02)
        plotter.isosurface(0, "spins_z")
        # plotter.show()
        plotter.render_to_png("test")
    def prepare_moving_endpoints(self, idx_mid=-1):
        from spirit import chain, io, state, parameters

        self.log("Preparing for moving endpoints")

        self.target_noi = 3
        self.moving_endpoints = True
        self.image_types = [[1, parameters.gneb.IMAGE_CLIMBING]]

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

            noi = chain.get_noi(p_state)

            if idx_mid < 0:
                E = chain.get_energy(p_state)
                idx_mid = np.argmax(E)

            self.log("idx_mid = {}".format(idx_mid))

            if (idx_mid >= 1 and idx_mid < noi - 1):
                for i in range(idx_mid - 1):
                    chain.delete_image(p_state, idx_image=0)
                for i in range(noi - idx_mid - 2):
                    chain.pop_back(p_state)

            self.update_energy_path(p_state)
            self.save_chain(p_state)
Exemplo n.º 3
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
def test_write_split_at():
    with state.State(INPUT_FILE, QUIET) as p_state:
        configuration.plus_z(p_state)
        chain.image_to_clipboard(p_state)

        noi = 10
        chain.set_length(p_state, noi)
        for idx_image in range(noi):
            configuration.skyrmion(p_state, radius=2*idx_image, idx_image=idx_image)

        # Test write split_at
        filenames = [ os.path.join(SCRIPT_DIR, n) for n in  ["output_1.ovf", "output_2.ovf"] ]
        idx_list  = [2,3,9]
        idx_pairs = [[2,3], [3,9]]

        old_spin_directions = []
        for p in idx_pairs:
            old_spin_directions.append([])
            for idx in range(p[0], p[1]+1):
                old_spin_directions[-1].append( np.array(system.get_spin_directions(p_state, idx_image=idx)) )

        chain_io.chain_write_split_at(p_state, idx_list=idx_list, filename_list=filenames)

        for j,(f,p) in enumerate(zip(filenames, idx_pairs)):
            chain.set_length(p_state, 1)
            io.chain_read(p_state, f)
            idx_1 = p[0]
            idx_2 = p[1]
            for i, idx in enumerate(range(idx_1, idx_2 + 1)):
                new_spin_directions = np.array( np.array(system.get_spin_directions(p_state, idx_image=i)) )
                print( "Testing image {}, original idx {}".format(i, idx) )
                res = np.max( np.ravel(old_spin_directions[j][i] ) - np.ravel(new_spin_directions ) )
                print( res )
                assert( res < 1e-10 )
def test_write_between():
    OUTPUT_FILE = os.path.join(SCRIPT_DIR, "output_test_chain_io.ovf")
    with state.State(INPUT_FILE, QUIET) as p_state:
        configuration.plus_z(p_state)
        chain.image_to_clipboard(p_state)

        noi = 10
        chain.set_length(p_state, noi)
        for idx_image in range(noi):
            configuration.skyrmion(p_state, radius=2*idx_image, idx_image=idx_image)

        # Test write between
        idx_1 = 2
        idx_2 = 5

        old_spin_directions = []
        for idx in range(idx_1, idx_2+1):
            old_spin_directions.append( np.array(system.get_spin_directions(p_state, idx_image=idx)) )

        chain_io.chain_write_between(p_state, OUTPUT_FILE, idx_1, idx_2)
        chain.set_length(p_state, 1)
        io.chain_read(p_state, OUTPUT_FILE)

        for i, idx in enumerate(range(idx_1, idx_2 + 1)):
            new_spin_directions = np.array( np.array(system.get_spin_directions(p_state, idx_image=i)) )
            print( "Testing image {}, original idx {}".format(i, idx) )
            res = np.max( np.ravel(old_spin_directions[i] ) - np.ravel(new_spin_directions ) )
            print( res )
            assert( res < 1e-10 )
 def backup_chain(self, path):
     """Saves the chain to a file"""
     from spirit import state, io
     with state.State(self.input_file) as p_state:
         self._prepare_state(p_state)
         self.log("Writing chain to {}".format(path))
         io.chain_write(p_state,
                        path,
                        fileformat=self.chain_write_fileformat)
Exemplo n.º 8
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 run(self):
        passed = True

        with state.State(self.inputfile1, quiet=True) as p_state:
            configuration.plus_z(p_state)
            system.update_data(p_state)
            E_1 = system.get_energy(p_state)
            print('>>> Result 1: mu_s = 1')
            print('E_DDI = ', E_1)

        with state.State(self.inputfile2, quiet=True) as p_state:
            configuration.plus_z(p_state)
            system.update_data(p_state)
            E_2 = system.get_energy(p_state)
            print('\n>>> Result 2: mu_s = 2')
            print('E_DDI = ', E_2)

        if np.abs(E_1 * 2**2 - E_2) > 1e-1:
            passed = False

        return passed
    def add_child(self, i1, i2, p_state=None):
        def _helper(p_state):
            self.log("Adding child with indices {} and {}".format(i1, i2))
            # Attributes that change due to tree structure
            child_name = self.name + "_{}".format(len(self.children))
            child_input_file = self.input_file
            child_output_folder = self.output_folder + "/{}".format(
                len(self.children))
            self.children += (GNEB_Node(
                name=child_name,
                input_file=child_input_file,
                output_folder=child_output_folder,
                gneb_workflow_log_file=self.gneb_workflow_log_file,
                parent=self), )
            self.children[
                -1].current_energy_path = self.current_energy_path.split(
                    i1, i2 + 1)
            # Copy the other attributes
            self.children[-1].target_noi = self.target_noi
            self.children[-1].convergence = self.convergence
            self.children[
                -1].path_shortening_constant = self.path_shortening_constant
            self.children[-1].max_total_iterations = self.max_total_iterations
            self.children[
                -1].state_prepare_callback = self.state_prepare_callback
            self.children[-1].gneb_step_callback = self.gneb_step_callback
            self.children[-1].exit_callback = self.exit_callback
            self.children[-1].before_gneb_callback = self.before_gneb_callback
            self.children[-1].before_llg_callback = self.before_llg_callback
            self.children[-1].n_iterations_check = self.n_iterations_check
            self.children[-1].n_checks_save = self.n_checks_save
            self.children[-1].allow_split = self.allow_split
            self.children[
                -1].chain_write_fileformat = self.chain_write_fileformat

            self.child_indices.append([i1, i2])
            # Write the chain file
            chain_write_between(p_state,
                                self.children[-1].chain_file,
                                i1,
                                i2,
                                fileformat=self.chain_write_fileformat)

        if p_state:
            _helper(p_state)
        else:
            from spirit import state
            with state.State(self.input_file) as p_state:
                self._prepare_state(p_state)
                _helper(p_state)

        return self.children[
            -1]  # Return a reference to the child that has just been added
Exemplo n.º 11
0
 def test(self):
     with state.State(cfgfile) as p_state:
         # Noise
         configuration.Random(p_state)
         configuration.Add_Noise_Temperature(p_state, 5)
         # Homogeneous
         configuration.PlusZ(p_state)
         configuration.MinusZ(p_state)
         configuration.Domain(p_state, [1,1,1])
         # Skyrmion
         configuration.Skyrmion(p_state, 5)
         # Hopfion
         configuration.Hopfion(p_state, 5)
         # Spin Spiral
         configuration.SpinSpiral(p_state, "Real Lattice", [0,0,0.1], [0,0,1], 30)
Exemplo n.º 12
0
 def test(self):
     with state.State(cfgfile) as p_state:
         # Noise
         configuration.random(p_state)
         configuration.add_noise(p_state, 5)
         # Homogeneous
         configuration.plus_z(p_state)
         configuration.minus_z(p_state)
         configuration.domain(p_state, [1, 1, 1])
         # Skyrmion
         configuration.skyrmion(p_state, 5)
         # Hopfion
         configuration.hopfion(p_state, 5)
         # Spin Spiral
         configuration.spin_spiral(p_state, "Real Lattice", [0, 0, 0.1],
                                   [0, 0, 1], 30)
def test_append_to_file_from_file():
    FILE_IN = os.path.join(SCRIPT_DIR, "in.ovf")
    FILE_OUT = os.path.join(SCRIPT_DIR, "out.ovf")
    
    if os.path.exists(FILE_OUT):
        os.remove(FILE_OUT)

    with state.State(INPUT_FILE, QUIET) as p_state:
        configuration.plus_z(p_state)
        chain.image_to_clipboard(p_state)

        noi = 2
        chain.set_length(p_state, noi)
        for idx_image in range(noi):
            configuration.skyrmion(p_state, radius=2*idx_image, idx_image=idx_image)

        old_spin_directions = []
        for idx in range(noi):
            old_spin_directions.append( np.array(system.get_spin_directions(p_state, idx_image=idx)) )

        io.chain_write(p_state, FILE_IN)

        chain.set_length(p_state, 1)
        configuration.random(p_state)

        chain_io.chain_append_to_file_from_file(p_state, FILE_OUT, FILE_IN)
        chain_io.chain_append_to_file_from_file(p_state, FILE_OUT, FILE_IN)
        chain_io.chain_append_to_file_from_file(p_state, FILE_OUT, FILE_IN)
        chain_io.chain_append_to_file_from_file(p_state, FILE_OUT, FILE_IN)

        chain.set_length(p_state, 1)
        io.chain_read(p_state, FILE_OUT)

        for i in range(4):
            print( "Testing image {}, original idx {}".format(i, idx) )

            new_spin_directions = np.array( np.array(system.get_spin_directions(p_state, idx_image=2*i)) )
            res = np.max( np.ravel(old_spin_directions[0] ) - np.ravel(new_spin_directions ) )
            print( res )
            assert( res < 1e-10 )

            new_spin_directions = np.array( np.array(system.get_spin_directions(p_state, idx_image=2*i+1)) )
            res = np.max( np.ravel(old_spin_directions[1] ) - np.ravel(new_spin_directions ) )
            print( res )
            assert( res < 1e-10 )
Exemplo n.º 14
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
    def collect_chain(self, output_file):
        from spirit import state, io, chain
        self.log("Collecting chain in file {}".format(output_file))

        if os.path.exists(output_file):
            os.remove(output_file)

        def helper(p_state, node):
            node.log("    collecting...")
            # Make sure the number of images matches our current simulation state
            chain.image_to_clipboard(p_state)
            noi = io.n_images_in_file(p_state, node.chain_file)
            chain.set_length(p_state, noi)
            io.chain_read(p_state, node.chain_file)
            noi = chain.get_noi(p_state)

            i = 0
            while i < noi:
                # First we check if this images is within any of the ranges covered by the children
                is_child = False
                for idx_c, (i1, i2) in enumerate(node.child_indices):
                    if i >= i1 and i <= i2:
                        is_child = True
                        idx_child = idx_c
                        break

                # If the current idx is covered by a child node, we open up another level of recursion, else we append the image
                if is_child:
                    helper(p_state, node.children[idx_child])
                    # After collecting the child we advance the current iteration idx, so that we continue one past the last child index
                    i = node.child_indices[idx_child][1] + 1
                    # We also need to read the chain file again to return to our previous state
                    chain.image_to_clipboard(p_state)
                    chain.set_length(p_state, noi)
                    io.chain_read(p_state, node.chain_file)
                else:
                    io.image_append(p_state, output_file, idx_image=i)
                    i += 1

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

        self.log("Done collecting chain in file")
 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
    def increase_noi(self, p_state=None):
        """Increases the noi by (roughly) a factor of two until the number of images is at least as large as target_noi"""
        from spirit import state, chain, transition, io

        with state.State(self.input_file) as p_state:
            self._prepare_state(p_state)
            self.noi = chain.get_noi(p_state)

            if (self.noi < self.target_noi):
                self.log(
                    "Too few images ({}). Inserting additional interpolated images"
                    .format(self.noi))

            while (self.noi < self.target_noi):
                transition.homogeneous_insert_interpolated(p_state, 1)
                self.noi = chain.get_noi(p_state)

            self.log("Number of images = {}".format(self.noi))
            self.save_chain(p_state)
Exemplo n.º 18
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]))
    def prepare_dimer(self, idx_left, idx_right=None):
        from spirit import chain, io, state, parameters

        if idx_right is None:
            idx_right = idx_left + 1

        self.log("Preparing for dimer endpoints")

        self.target_noi = 2
        self.moving_endpoints = True
        self.translating_endpoints = True
        self.image_types = []

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

            noi = chain.get_noi(p_state)

            self.log("idx_left = {}, idx_right = {}".format(
                idx_left, idx_right))

            # Delete all images to the right of idx right
            for i in range(noi - idx_right - 1):
                chain.pop_back(p_state)

            # Delete all images to the left of idx_left
            for i in range(idx_left):
                chain.delete_image(p_state, idx_image=0)

            # Delete images between idx_left and idx_right
            for i in range(idx_right - idx_left - 1):
                chain.delete_image(p_state, idx_image=1)

            self.update_energy_path(p_state)
            self.save_chain(p_state)
Exemplo n.º 20
0
    sample_temperatures,
    np.linspace(Ta + 0.5 * T_step,
                Tb - 0.5 * T_step,
                num=int(n_temperatures - (n_temperatures / 4) * 2)))
sample_temperatures = np.append(
    sample_temperatures,
    np.linspace(Tb + 0.5 * T_step, T_end, num=int(n_temperatures / 4)))

energy_samples = []
magnetization_samples = []
susceptibility_samples = []
specific_heat_samples = []
binder_cumulant_samples = []

cfgfile = "ui-python/input.cfg"  # Input File
with state.State(cfgfile) as p_state:  # State setup
    # Set parameters
    hamiltonian.set_field(p_state, 0.0, [0, 0, 1])
    hamiltonian.set_exchange(p_state, Jij, [1.0])
    hamiltonian.set_dmi(p_state, 0, [])

    parameters.mc.set_output_general(p_state, any=False)  # Disallow any output

    geometry.set_mu_s(p_state, 1.0)
    geometry.set_n_cells(p_state, [system_size, system_size, system_size])

    NOS = system.get_nos(p_state)

    # Ferromagnet in z-direction
    configuration.plus_z(p_state)
    # configuration.Random(p_state)
    def clamp_and_refine(self,
                         convergence=None,
                         max_total_iterations=None,
                         idx_max_list=None,
                         apply_ci=True,
                         target_noi=5):
        """One step of clamp and refine algorithm"""

        if target_noi % 2 == 0:
            raise Exception("target_noi must be uneven!")

        if not convergence:
            convergence = self.convergence

        if not max_total_iterations:
            max_total_iterations = self.max_total_iterations

        try:
            from spirit import state
            if (len(self.children) !=
                    0):  # If not a leaf node call recursively on children
                for c in self.children:
                    c.clamp_and_refine(convergence, max_total_iterations,
                                       idx_max_list, apply_ci, target_noi)
                return

            self.update_energy_path()

            # To get a list of the "interesting" images we compute the second derivative of the energy wrt to Rx
            # We initialize these lists with a dummy element so the idx counting is not offset by one
            second_deriv = [0]  # second derivative
            first_deriv_fw = [0]  # first derivative forward
            first_deriv_bw = [0]  # first derivative backward

            E = self.current_energy_path.total_energy
            Rx = self.current_energy_path.reaction_coordinate

            for idx in range(1,
                             self.current_energy_path.noi() -
                             1):  # idx=0 and idx=noi-1 excluded!
                grad_forward = (E[idx + 1] - E[idx]) / (Rx[idx + 1] - Rx[idx])
                grad_backward = (E[idx] - E[idx - 1]) / (Rx[idx] - Rx[idx - 1])
                second = 2 * (grad_forward - grad_backward) / (Rx[idx + 1] -
                                                               Rx[idx - 1])
                first_deriv_fw.append(grad_forward)
                first_deriv_bw.append(grad_backward)
                second_deriv.append(second)

            # If not specified, build the idx_max list
            if not idx_max_list:
                idx_max_list = []
                idx = 1
                while idx < self.current_energy_path.noi() - 1:
                    if first_deriv_fw[idx] < 0 and first_deriv_bw[
                            idx] > 0.01 * first_deriv_fw[idx]:
                        idx_max_list.append(idx)
                        idx += 1  # If we add something to idx_max list we increment the idx so that we do not also add the point right after that
                    idx += 1

            self.log("Clamp and refine! idx_list = {}".format(idx_max_list))

            for idx_max in idx_max_list:
                if (idx_max == 0 or idx_max == self.noi - 1):
                    self.log(
                        "Cannot clamp and refine, since idx_max (= {}) is either 0 or noi-1"
                        .format(idx_max))
                    return

                with state.State(self.input_file) as p_state:
                    self._prepare_state(p_state)
                    self.add_child(idx_max - 1, idx_max + 1, p_state)

                    # Attributes, that we dont copy
                    self.children[
                        -1].allow_split = False  # Dont allow splitting for clamp and refine
                    self.children[
                        -1].path_shortening_constant = -1  # No path shortening for clamp and refine
                    self.children[-1].target_noi = target_noi
                    self.children[-1].convergence = convergence
                    self.children[
                        -1].max_total_iterations = max_total_iterations

                    if apply_ci and not self._ci:

                        def before_gneb_cb(gnw, p_state):
                            from spirit import parameters
                            self.before_gneb_callback(gnw, p_state)
                            gnw.log("Setting image type")
                            parameters.gneb.set_climbing_falling(
                                p_state,
                                parameters.gneb.IMAGE_CLIMBING,
                                idx_image=int((target_noi - 1) / 2))

                        self.children[-1]._ci = True
                    else:

                        def before_gneb_cb(gnw, p_state):
                            self.before_gneb_callback(gnw, p_state)

                    self.children[-1].before_gneb_callback = before_gneb_cb

            self.run_children()

        except Exception as e:
            self.log("Exception during 'clamp_and_refine': {}".format(
                str(e)))  # Log the exception and re-raise
            self.log(traceback.format_exc())
            raise e
Exemplo n.º 22
0
    from subprocess import call
    call("cp data_x.txt data.txt", shell=True)
    Run_PovRay_Script("Show_Spins", 1000, 1000)
    call("cp Show_Spins.png spins_x.png", shell=True)

    call("cp data_y.txt data.txt", shell=True)
    Run_PovRay_Script("Show_Spins", 1000, 1000)
    call("cp Show_Spins.png spins_y.png", shell=True)

    call("cp data_z.txt data.txt", shell=True)
    Run_PovRay_Script("Show_Spins", 1000, 1000)
    call("cp Show_Spins.png spins_z.png", shell=True)

    call("rm -f Data.txt Show_Spins.png", shell=True)


cfgfile = "input/input.cfg"
# cfgfile = "input/markus-paper.cfg"
# cfgfile = "input/gideon-master-thesis-anisotropic.cfg"
# cfgfile = "input/daniel-master-thesis-isotropic.cfg"

with state.State(cfgfile) as p_state:
    ### Setup initial configurations
    configurations(p_state)
    ### Run simulations
    simulations(p_state)
    ### Evaluate the results
    # evaluations(p_state)
    ### Create snapshots of the system
    # snapshots(p_state)
Exemplo n.º 23
0
def main():
    in_var = 0
    config_fname = ''
    #initial parameters
    x_size = 0
    y_size = 0
    Mtd = 1
    convThr = 1e-12  # Convergence condition
    tS = 1e-4  # LLG time step
    k_val = 0.0  # Anisotropy
    Kdir = [0.0, 0.0, 1.0]  # Anisotropy direction
    Exchange_mm = 18.16
    DMI_mm = 1.87
    Dij = []
    lc = 6.0
    symmetry = 4

    print('Welcome to spirit sandbox.\n')

    while in_var != -1:  # TODO: remove from loop
        read_config = collect_input(int, 'read in a config file?(0/1): ')
        if read_config == 1:
            config_fname = input('enter config your_file_name.txt: ')
            in_var = collect_input(
                int, 'Generate new r_pos, h, and anisotropy file (0/1)?: ')
            if in_var == 1:
                x_size = collect_input(int, 'x lattice size: ')
                y_size = collect_input(int, 'y lattice size: ')
                #set lattice constant

                with file_parser.Parse_File('gen_config.txt') as fp:
                    lc = fp.file_readline(None, 'lattice_constant')
                    lc = float(lc.split()[1])
                #update bravis vector
                with file_parser.Parse_File('gen_config.txt') as fp:
                    line_num = fp.find_line_number('bravais_vectors')
                    fp.write_to_file('bravais_vectors\n', line_num)
                    fp.write_to_file('{:d} 0 0\n'.format(x_size))
                    fp.write_to_file('0 {:d} 0\n'.format(y_size))
                    fp.write_to_file('0 0 1\n')

                generate_configs.gen_r_pos(x_size, y_size)

                in_var = collect_input(int, 'Use a custom DMI (0/1)?: ')
                if in_var == 1:
                    # TODO: add lc / 10 for dmi and exchange for lattice scale
                    DMI_mm = collect_input(float, 'Enter value for DMI: ')
                    DMI_atom = float(
                        DMI_mm * 1.602e+04 * lc / 10.0) / float(symmetry)
                    Exchange_mm = collect_input(float,
                                                'Enter value for Exchange: ')
                    Exchange_atom = float(Exchange_mm * 1.602e+13 * lc /
                                          10.0) / float(2 * symmetry)
                    print('DMI = {:5f}\nExchange = {:9.8f}'.format(
                        DMI_atom, Exchange_atom))

                    with file_parser.Parse_File('gen_config.txt') as fp:
                        fp.set_config_var('#DMI', '{:<8.5f}\n'.format(DMI_mm))
                        fp.set_config_var('#EXCHANGE',
                                          '{:<18.17f}\n'.format(Exchange_mm))
                        fp.set_config_var('interaction_pairs_file', 'h.txt\n')
                    #read periodic boundary conditions
                    with file_parser.Parse_File(config_fname) as fp:
                        bc = fp.file_readline(None,
                                              'boundary_conditions').split()
                    generate_configs.gen_h_file(x_size, y_size,
                                                Exchange_atom, DMI_atom,
                                                int(bc[1]), int(bc[2]))
                else:
                    with file_parser.Parse_File('gen_config.txt') as fp:
                        fp.set_config_var('interaction_pairs_file', '.\n')

                in_var = collect_input(int, 'Use a custom anis (0/1)?: ')

                if in_var == 1:
                    in_var = collect_input(
                        int,
                        'Use random or pattern generated anisotropy (0/1)?: ')
                    if in_var == 1:
                        pattern = input(
                            'Enter math expression here in terms of x\nEnter an integer for a box: '
                        )
                        width = collect_input(int, 'Enter width of pattern: ')
                        k_val = collect_input(float, 'Enter K value: ')
                        generate_configs.gen_anis_pattern(
                            x_size, y_size, pattern, width, 0.9)
                    elif in_var == 0:
                        k_val = collect_input(float, 'Enter value for K: ')
                        #convert K
                        k_val = k_val * DMI_mm**2 / (4 * Exchange_mm)
                        k_val = k_val * 1.6021766e-05  # J/m^3 -> meV
                        print('K = {:f}\n'.format(k_val))
                        sigma = collect_input(
                            float, 'Enter value for sigma in percent of K: ')
                        generate_configs.gen_anis_random(
                            x_size, y_size, k_val, sigma)

                    with file_parser.Parse_File('gen_config.txt') as fp:
                        fp.set_config_var('anisotropy_file',
                                          'anisotropy.txt\n')
                else:
                    with file_parser.Parse_File('gen_config.txt') as fp:
                        fp.set_config_var('anisotropy_file', '.\n')

                file_parser.concatenate_files('gen_config.txt', 'r_pos.txt',
                                              config_fname)
                #generate new config file
            #read a config file

            elif in_var == 0:
                prev_vals = []
                #TODO: complete functionality
                #Load previously used values to current values from old
                #config file. Can be modified to add as many values as needed.
                search = ['#DMI', '#EXCHANGE', 'lattice_constant']
                with file_parser.Parse_File(config_fname) as fp:
                    for searchterm in search:
                        cur_line = (fp.file_readline(None, searchterm)).split()
                        prev_vals.append(float(cur_line[1]))
# TODO: add object to assign each value in loop and not by name after loop
                    DMI_mm = prev_vals[0]
                    Exchange_mm = prev_vals[1]
                    lc = prev_vals[2]

                    cur_line = fp.file_readline(None, 'bravais_vectors', True)
                    cur_line = cur_line.split()
                    x_size = int(cur_line[0])
                    cur_line = fp.file_readline()
                    cur_line = cur_line.split()
                    y_size = int(cur_line[1])

                    print(
                        'loaded values:\nlattice size: {:f}x{:f}\nDMI_mm: {:f}\nExchange_mm: {:18.17f}\nlattice constant: {:f}\n'
                        .format(x_size, y_size, DMI_mm, Exchange_mm, lc))
        #if read_config == 1

        alphaD = collect_input(float, 'enter alpha: ')  # Damping

        if read_config:
            betaD = collect_input(float, 'enter beta: ')
            with file_parser.Parse_File(config_fname) as fp:
                fp.set_config_var('llg_beta', str(betaD))
                pass
        else:
            x_size = collect_input(int, 'x lattice size: ')
            y_size = collect_input(int, 'y lattice size: ')

        Slvr = collect_input(int, 'enter solver num(1-4): ')
        #running quiet = true for less text
        with state.State(configfile=config_fname, quiet=False) as i_state:
            sim_script.run_simulation(i_state, Mtd, Slvr, convThr, tS, k_val,
                                      Kdir, Exchange_mm, DMI_mm, Dij, alphaD,
                                      x_size, y_size, read_config, lc)

        return (0)  #main() TODO: fix this so its not in a loop
Exemplo n.º 24
0
 def test(self):
     with state.State(cfgfile) as p_state:
         pass
    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
Exemplo n.º 26
0
 def test_log_message(self):
     with state.State() as p_state:
         log.send(p_state, log.LEVEL_SEVERE, log.SENDER_ALL, "Test Message")
Exemplo n.º 27
0
 def test_log_message(self):
     with state.State() as p_state:
         log.Send(p_state, 1, 0, "Test Message")
Exemplo n.º 28
0
    sample_temperatures,
    np.linspace(6 + 0.5 * T_step,
                10 - 0.5 * T_step,
                num=n_temperatures - (n_temperatures / 4) * 2))
sample_temperatures = np.append(
    sample_temperatures,
    np.linspace(10 + 0.5 * T_step, T_end, num=n_temperatures / 4))

energy_samples = []
magnetization_samples = []
susceptibility_samples = []
specific_heat_samples = []
binder_cumulant_samples = []

cfgfile = "ui-python/input.cfg"  # Input File
with state.State(cfgfile, quiet=True) as p_state:  # State setup
    # Set parameters
    parameters.mc.setOutputGeneral(p_state, False)  # Disallow any output
    geometry.setNCells(p_state, [system_size, system_size, system_size])

    NOS = system.Get_NOS(p_state)

    # Ferromagnet in z-direction
    configuration.PlusZ(p_state)
    # configuration.Random(p_state)

    # Loop over temperatures
    for iT, T in enumerate(sample_temperatures):
        parameters.mc.setTemperature(p_state, T)

        # Cumulative average variables
Exemplo n.º 29
0
Arquivo: llg.py Projeto: DTolm/spirit
### 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 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