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 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
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 chain_append_from_file(p_state, filename):
    # TODO: chain_read with insert_idx seems to be broken
    raise NotImplementedError()
    from spirit import io, chain
    noi_file = io.n_images_in_file(p_state, filename)
    noi = chain.get_noi(p_state)
    chain.image_to_clipboard(p_state)
    chain.set_length(p_state, noi + noi_file)
    io.chain_read(p_state, filename, insert_idx=noi)
    chain.update_data(p_state)
def chain_append_to_file_from_file(p_state, filename_out, filename_in):
    """Reads the chain from `filename_in` and appends it to `filename_out`"""
    from spirit import io, chain
    noi_file = io.n_images_in_file(p_state, filename_in)
    chain.image_to_clipboard(p_state)
    chain.set_length(p_state, noi_file)
    io.chain_read(p_state, filename_in)

    # TODO: io.chain_append seems to be broken, so we use image_append...
    for i in range(noi_file):
        io.image_append(p_state, filename_out, idx_image=i)
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 )
    def _prepare_state(self, p_state):
        """Prepares the state and reads in the chain."""
        from spirit import parameters, io

        # Set the output folder for the files created by spirit
        set_output_folder(p_state, self.output_folder, self.output_tag)

        # Set the gneb convergence parameter
        parameters.gneb.set_convergence(p_state, self.convergence)

        if self.moving_endpoints is not None:
            parameters.gneb.set_moving_endpoints(p_state,
                                                 self.moving_endpoints)
            if self.translating_endpoints is not None:
                parameters.gneb.set_translating_endpoints(
                    p_state, self.translating_endpoints)
            if self.delta_Rx_left is not None and self.delta_Rx_right is not None:
                parameters.gneb.set_equilibrium_delta_Rx(
                    p_state, self.delta_Rx_left, self.delta_Rx_right)

        # The state prepare callback can be used to change the state before execution of any other commands
        # One could e.g. use the hamiltonian API to change interaction parameters instead of relying only on the input file
        if self.state_prepare_callback:
            self.state_prepare_callback(self, p_state)

        # Before we run we must make sure that the chain.ovf file exists now
        if not os.path.exists(self.chain_file):
            raise Exception("Chain file does not exist!")

        if self.path_shortening_constant > 0:
            parameters.gneb.set_path_shortening_constant(
                p_state, self.path_shortening_constant)

        # Read the file
        io.chain_read(p_state, self.chain_file)

        # Set image types
        for idx_image, image_type in self.image_types:
            self.log("Set type of image {} to {}".format(
                idx_image, image_type))
            parameters.gneb.set_climbing_falling(p_state, image_type,
                                                 idx_image)
Exemple #8
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