#! /usr/bin/env python
import friction_tools as ft

# create the simulation containing two atoms
simu = ft.FrictionSimulation()
simu.create_atoms(element='C', positions=[[0, 0, 0], [6, 0, 0]])

# create an interaction between the two atoms
simu.create_interaction(['C', 'C'], strength=10.0, equilibrium_distance=5.0)

# give the atoms some initial velocities
vs = [[0.1, 0, 0], [-0.1, 0, 0]]
simu.set_velocities(indices=range(2), velocity=vs)

# tell that we want to run the simulation with default settings
simu.create_dynamics()

# tell that we want to record the movement of the atoms
simu.save_trajectory_during_simulation(interval=5)

# run the simulation for 1000 fs
print "starting simulation"
simu.run_simulation(time=1000.0)
print "finished simulation"

# after finishing, create an xyz-file for viewing what happened
ft.trajectory_to_xyz()
def main(fixed_strength):

    def create_lj_interactions(strengths):
        """
        Creates Lernnard-Jones potential interactions between materials.
        @param strengths: {'material': 1.0} - dict of material-strength pairs.
        """
        sim.create_interaction(
            [fixed_slab_material, fixed_slab_material],
            strengths.get(fixed_slab_material, 0.0),
            10 / (fixed_slab_xy * (2 ** 0.5))
        )
        sim.create_interaction(
            [moving_slab_material, moving_slab_material],
            strengths.get(moving_slab_material, 0.0),
            10 / (moving_slab_xy * (2 ** 0.5))
        )
        sim.create_interaction(
            [fixed_slab_material, moving_slab_material],
            1.0,
            2.0
        )

    def create_coulomb_interactions(charges):
        """
        Creates Coulombs summation interactions between materials.
        @param charges: {'material': 1.0} - dict of material-charge pairs.
        """
        def charge_by_elements(element):
            """
            Maps elements with their according charges.
            """
            return charges.get(element, 0.0)

        # Set charges
        sim.system.set_charges(
            map(charge_by_elements, sim.system.get_chemical_symbols())
        )
        # Create instance of the CoulombSummation class
        coulomb_sum = pysic.CoulombSummation()
        # Find good enough computational parameters
        parameters = pysic.interactions.coulomb.estimate_ewald_parameters()
        # Set the parameters to the summation object
        coulomb_sum.set_parameter_values(list(parameters))
        # Add the created CoulombSummation object to the Pysic calculator objec
        sim.calc.set_coulomb_summation(coulomb_sum)

    def friction_initial_velocity_x(threshold_x, initial_velocity_x=0.1):
        """
        Measures friction by giving the moving slab an initial velocity in
        x-direction and simulating until the slab has stopped moving.
        @param threshold_x: 1.0 - values below threshold count as being stopped
        """
        # Set initial velocity in x-direction
        sim.set_velocities(
            indices=moving_mat_indices,
            velocity=[initial_velocity_x, 0, 0]
        )
        print('Slab is now moving. Simming until it stops...')
        while sim.get_avg_velocity(moving_mat_indices)[0] > threshold_x:
            print('Velocities are now: '+str(
                sim.get_avg_velocity(moving_mat_indices)
            ))
            sim.run_simulation(300)

        print('Velocities are now: '+str(
            sim.get_avg_velocity(moving_mat_indices)
        ))

    def friction_constant_velocity_x(indices, constant_velocity_x):

        sim.fix_velocities(
            indices=indices,
            velocity=[constant_velocity_x, 0, 0]
        )

        print('Slab is now moving in constant velocity...')

        sim.run_simulation(1000)

    moving_slab_material = 'Ag'
    moving_slab_xy = 3  # 3
    moving_slab_z = 2  # 2

    fixed_slab_material = 'Au'
    fixed_slab_xy = 5  # 5
    # fixed_slab_z = 2  # 2

    element_lj_strengths = {
        'Au': fixed_strength,
        'Ag': 1.0
    }

    # Create simulation object
    sim = ft.FrictionSimulation()

    # Calculate thresholds for being in touch with the surface
    contact_threshold = math.ceil(10.0 / float(moving_slab_xy)) * moving_slab_z
    # velocity_threshold_x = 0.04

    # Create the two slabs and store their indices
    # TODO: Edit to use z-config
    sim.create_slab(
        element=fixed_slab_material,
        xy_cells=fixed_slab_xy,
        z_cells=2,
        top_z=0.0
    )
    sim.create_slab(
        element=moving_slab_material,
        xy_cells=moving_slab_xy,
        z_cells=2,
        bottom_z=5.0
    )

    # fixed_mat_indices = sim.get_indices_by_element(fixed_slab_material)
    moving_mat_indices = sim.get_indices_by_element(moving_slab_material)

    # TODO: Edit to use z-config
    # Bottom row of fixed materials atoms
    bottom_indices = sim.get_indices_z_less_than(-2)
    # Top row of moving materials atoms
    top_indices = sim.get_indices_z_more_than(8.0)

    # Create interactions
    create_lj_interactions(element_lj_strengths)
    # create_coulomb_interactions(element_charges)  # Currently too slow!

    # Create dynamics and configure the setup
    sim.create_dynamics(dt=1.0, temperature=300)

    # Fix the bottom slab and make the top slab move down
    sim.fix_positions(bottom_indices)
    sim.add_constant_force(top_indices, [0, 0, -0.1])
    # sim.fix_velocities(top_indices, [0, 0, -0.005], [True, True, True])

    sim.set_temperature(300)  # Try to reset the temperature

    # Save tmps, print stats and time the simulation
    # sim.save_trajectory_during_simulation(interval=50.0)
    # sim.print_stats_during_simulation(interval=50.0)
    # t0 = time.time()

    print('Starting the simulation')
    print(sim.get_avg_forces(moving_mat_indices))
    while len(sim.get_indices_z_more_than(contact_threshold)):
        print(len(sim.get_indices_z_more_than(contact_threshold)))
        print(sim.get_avg_velocity(moving_mat_indices))
        print(sim.get_avg_forces(moving_mat_indices))
        sim.run_simulation(300)

    print('Moving slab hit the fixed slab.')
    sim.remove_constraints()
    print('Starting friction measurement phase.')
    xpos0 = [p[0] for p in sim.get_positions(indices=moving_mat_indices)]
    friction_initial_velocity_x(0.005, 0.1)
    xpos1 = [p[0] for p in sim.get_positions(indices=moving_mat_indices)]
    xdiff = []
    for i in range(0, len(xpos0)):
        xdiff.append(xpos1[i] - xpos0[i])
    xdiffavg = sum(xdiff) / len(xdiff)

    out = open('dataout_fixed_slab.txt', 'a')
    out.write('\n{0}    {1}     {2}'.format(fixed_strength, numpy.mean(xdiff), numpy.var(xdiff)))
    out.close()

    #out2 = open('dataout_{0}.txt'.format(fixed_strength), 'a')
    #for i in range(0, len(xdiff)):
    #    out2.write('\n{0}'.format(xdiff[i]))
    #out2.close()

    print(xpos0, xpos1)

    print('All done, generating simulation file.')
Example #3
0
def init_simulation(simulation_time=1000,
                    element_surf='Au',
                    dims_surf=(20, 8, 5),
                    element_obj='C',
                    dims_obj=(3, 3, 3),
                    set_force=[0.0, 0.0, -0.02],
                    set_interval=10,
                    root_path='/u/76/tolland1/unix/Desktop/',
                    set_folder_name='initialise_number'):
    """
    Initialises a surface without periodic boundary conditions and a brick on top of the surface:

    :param simulation_time: Simulation time
    :param element_surf: Chemical symbol for the surface element.
    :param dims_surf: Dimensions in (x, y, z) format
    :param element_obj: Chemical symbol for the object element.
    :param dims_obj: Dimensions in (x, y, z) format
    :param set_force: Force acting on the object.
    :param set_interval: Interval for gathering data. (How often the gathered data is saved.)
    :param root_path: Root path for saving data.
    :param set_folder_name: The folder where the simulations is initialised. If already exists, existing one is overwritten
    :return: Trajectory of the initialised simulation saved in the folder defined.
    """

    # Lennard-Jones constants
    lennardjones_surf = [1.0, 1.414]
    lennardjones_obj = [1.0, 1.414]
    lennardjones_surfojb = [0.1, 1.414]

    '''
    Define the initialise folder and save it to initialise.pkl
    Save simulation details and sate to file
    '''
    folder_path = root_path + set_folder_name + '/'
    et.init_dir(path=folder_path)

    output = open('initialise.pkl', 'wb')
    pickle.dump(obj=folder_path, file=output)
    output.close()

    configs = [element_surf,
               dims_surf,
               element_obj,
               dims_obj,
               set_force,
               lennardjones_surf,
               lennardjones_obj,
               lennardjones_surfojb]

    output = open(folder_path + 'simulation_config.pkl', 'wb')
    pickle.dump(obj=configs, file=output)
    output.close()

    date_and_time = datetime.datetime.today()
    get_date = date_and_time.strftime('%d.%m.%Y')
    get_time = date_and_time.strftime('%H:%M:%S')
    output = open(folder_path + 'info.txt', 'w')
    info = 'Date: {0}\nTime: {1}\nSimulation time: {2}\nSurface: {3} {4}\nObject: {5} {6}\nForce: {7}'
    output.write(info.format(get_date,
                             get_time,
                             simulation_time,
                             element_surf,
                             dims_surf,
                             element_obj,
                             dims_obj,
                             set_force))
    output.close()

    '''
    Simulation
    '''
    simulation = ft.FrictionSimulation()

    '''
    Non-periodic Surface.
    Bottom of the surface is fixed in its initial position.
    '''
    positions_surf = et.brick(x_width=dims_surf[0],
                              y_width=dims_surf[1],
                              z_width=dims_surf[2],
                              x_pos=0,
                              y_pos=0,
                              z_pos=-2 * dims_surf[2])

    simulation.create_atoms(element=element_surf,
                            positions=positions_surf)

    # Fix positions of the bottom
    bottom_indices = simulation.get_indices_z_less_than(z_limit=-2 * dims_surf[2] + 0.5)
    simulation.fix_positions(indices=bottom_indices, xyz=[True, True, True])

    # For restricting thermostat
    indices_surf_unfixed = simulation.get_indices_z_more_than(z_limit=-2 * dims_surf[2])

    '''
    Object.
    '''
    positions_obj = et.brick(x_width=dims_obj[0],
                             y_width=dims_obj[1],
                             z_width=dims_obj[2],
                             x_pos=2,
                             y_pos=dims_surf[1] - dims_obj[1],
                             z_pos=2)

    simulation.create_atoms(element=element_obj,
                            positions=positions_obj)

    indices_obj = simulation.get_indices_by_element(element=element_obj)

    # Force
    if set_force is None:
        print 'Force is not set.\nRemember to add a force when running the actual simulation'
    else:
        simulation.add_constant_force(indices=indices_obj, force=set_force)

    # Interacting lennard-jones forces between the particles.
    simulation.create_interaction([element_surf, element_surf],
                                  strength=lennardjones_surf[0],
                                  equilibrium_distance=lennardjones_surf[1])

    simulation.create_interaction([element_obj, element_obj],
                                  strength=lennardjones_obj[0],
                                  equilibrium_distance=lennardjones_obj[1])

    simulation.create_interaction([element_surf, element_obj],
                                  strength=lennardjones_surfojb[0],
                                  equilibrium_distance=lennardjones_surfojb[1])

    simulation.list_atoms()

    simulation.create_dynamics(dt=1.0,
                               temperature=300,
                               coupled_indices=indices_surf_unfixed,
                               strength=0.01)

    # Trajectory
    simulation.save_trajectory_during_simulation(interval=set_interval,
                                                 filename=folder_path + 'simulation.traj')

    simulation.print_stats_during_simulation(interval=5.0)

    # Time the simulation
    t0 = time.time()
    simulation.run_simulation(time=simulation_time)
    t1 = time.time()

    runtime = "{ti} s".format(ti=str(int(t1 - t0)))
    output = open(folder_path + 'info.txt', 'a')
    output.write('\nRuntime: {0}'.format(runtime))
    output.close()
    print 'Time taken {0}'.format(runtime)

    # Convert .traj to .xyz
    ft.trajectory_to_xyz(filename_in=folder_path + 'simulation.traj',
                         filename_out=folder_path + 'simulation.xyz')
def main(strengths):
    moving_slab_material = 'Ag'
    moving_slab_xy = 3  # 3
    moving_slab_z = 2  # 2

    fixed_slab_material = 'Au'
    fixed_slab_xy = 5  # 5
    fixed_slab_z = 2  # 2

    element_charges = {'Au': 0.01, 'Ag': 0.005}

    element_lj_strengths = strengths
    """= {
        'Au': 1.0,
        'Ag': 0.5
    }"""

    # Create simulation object
    sim = ft.FrictionSimulation()

    # Calculate thresholds for being in touch with the surface
    contact_threshold = math.ceil(10.0 / float(moving_slab_xy)) * moving_slab_z
    velocity_threshold_x = 0.04

    # Create the two slabs and store their indices
    # TODO: Edit to use z-config
    sim.create_slab(element=fixed_slab_material,
                    xy_cells=fixed_slab_xy,
                    z_cells=2,
                    top_z=0.0)
    sim.create_slab(element=moving_slab_material,
                    xy_cells=moving_slab_xy,
                    z_cells=2,
                    bottom_z=5.0)

    fixed_mat_indices = sim.get_indices_by_element(fixed_slab_material)
    moving_mat_indices = sim.get_indices_by_element(moving_slab_material)

    # TODO: Edit to use z-config
    bottom_indices = sim.get_indices_z_less_than(
        -2)  # Bottom row of fixed materials atoms
    top_indices = sim.get_indices_z_more_than(
        8.0)  # Top row of moving materials atoms

    # Create interactions
    create_lj_interactions(element_lj_strengths)
    # create_coulomb_interactions(element_charges)  # Currently too slow!

    # Create dynamics and configure the setup
    sim.create_dynamics(dt=1.0, temperature=300)

    # Fix the bottom slab and make the top slab move down
    sim.fix_positions(bottom_indices)
    sim.add_constant_force(top_indices, [0, 0, -0.1])
    # sim.fix_velocities(top_indices, [0, 0, -0.005], [True, True, True])

    sim.set_temperature(300)  # Try to reset the temperature

    # Save tmps, print stats and time the simulation
    sim.save_trajectory_during_simulation(interval=50.0)
    sim.print_stats_during_simulation(interval=50.0)
    t0 = time.time()

    print('Starting the simulation')
    print(sim.get_avg_forces(moving_mat_indices))
    while len(sim.get_indices_z_more_than(contact_threshold)):
        print(len(sim.get_indices_z_more_than(contact_threshold)))
        print(sim.get_avg_velocity(moving_mat_indices))
        print(sim.get_avg_forces(moving_mat_indices))
        sim.run_simulation(500)

    print('Moving slab hit the fixed slab.')
    sim.remove_constraints()
    print('Starting friction measurement phase.')
    xpos0 = [p[0] for p in sim.get_positions(indices=moving_mat_indices)]
    friction_initial_velocity_x(0.005, 0.1)
    xpos1 = [p[0] for p in sim.get_positions(indices=moving_mat_indices)]
    xdiff = []
    for i in range(0, len(xpos0)):
        xdiff.append(xpos1[i] - xpos0[i])

    out = open('ownpos.txt', 'w')
    for i in range(0, len(xpos0)):
        out.write('{0}\n'.format(xpos0[i], xpos1[i]))
    out.close()

    print('All done, generating simulation file.')
    print(sim.get_avg_forces(moving_mat_indices))
    sim.write_positions_to_file(indices=moving_mat_indices)
    sim.write_average_position_to_file(indices=moving_mat_indices)
    sim.write_velocities_to_file(indices=moving_mat_indices)
    ft.trajectory_to_xyz()


#=====================
#>>>>> MAIN 2 <<<<<<<<
#=====================

#sim = ft.FrictionSimulation()

## Calculate thresholds for being in touch with the surface
#contact_threshold = math.ceil(10.0 / float(moving_slab_xy)) * moving_slab_z
#velocity_threshold_x = 0.04

## Create the two slabs and store their indices
## TODO: Edit to use z-config
#sim.create_slab(element=fixed_slab_material, xy_cells=fixed_slab_xy, z_cells=2, top_z=0.0)
#sim.create_slab(element=moving_slab_material, xy_cells=moving_slab_xy, z_cells=2, bottom_z=5.0)

#fixed_mat_indices = sim.get_indices_by_element(fixed_slab_material)
#moving_mat_indices = sim.get_indices_by_element(moving_slab_material)

## TODO: Edit to use z-config
#bottom_indices = sim.get_indices_z_less_than(-2)  # Bottom row of fixed materials atoms
#top_indices = sim.get_indices_z_more_than(8.0)  # Top row of moving materials atoms

## Create interactions
#create_lj_interactions(element_lj_strengths)
#create_coulomb_interactions(element_charges)  # Currently too slow!

## Create dynamics and configure the setup
#sim.create_dynamics(dt=1.0, temperature=300)

## Fix the bottom slab and make the top slab move down
#sim.fix_positions(bottom_indices)
#sim.add_constant_force(top_indices, [0, 0, -0.1])
## sim.fix_velocities(top_indices, [0, 0, -0.005], [True, True, True])

#sim.set_temperature(300)  # Try to reset the temperature

## Save tmps, print stats and time the simulation
#sim.save_trajectory_during_simulation(interval=50.0)
#sim.print_stats_during_simulation(interval=50.0)
#t0 = time.time()

#print('Starting the simulation')

#while len(sim.get_indices_z_more_than(contact_threshold)):
#print(len(sim.get_indices_z_more_than(contact_threshold)))
#print(sim.get_avg_velocity(moving_mat_indices))
#sim.run_simulation(500)

#print('Moving slab hit the fixed slab.')

#print('Starting friction measurement phase.')
#friction_constant_velocity_x([initial_velocity, 0.0, 0.0])

#print('All done, generating simulation file.')
#ft.trajectory_to_xyz()
Example #5
0
def read_and_run_simulation(simulation_time=1000,
                            set_velocity=[0.50, 0.0, 0.0],
                            set_force=None,
                            set_interval=1,
                            root_path='/u/76/tolland1/unix/Desktop/',
                            set_folder_name='simulation_number'):
    """
    Run a simulation from initialised trajectory.

    :param simulation_time: Simulation time
    :param set_velocity: The velocity given to object.
    :param set_force: The force acting on the object. Default is None, which loads the force used in the initialising. If value is given it will be used instead of the force in the initialisement.
    :param set_interval: Interval for gathering data. (How often the gathered data is saved.)
    :param root_path: Root path for saving data.
    :param set_folder_name: The folder where the simulations is saved. If already exists, existing one is overwritten
    :return: Trajectory of the simulation saved in the folder defined.
    """

    # Initialise folder to root path
    folder_path = root_path + set_folder_name + '/'
    et.init_dir(path=folder_path)

    # load initialised simulation
    infile = open('initialise.pkl', 'rb')
    folder_load = pickle.load(file=infile)
    infile.close()

    infile = open(folder_load + 'simulation_config.pkl', 'rb')
    configs = pickle.load(file=infile)
    infile.close()

    [
        element_surf, dims_surf, element_obj, dims_obj, get_force,
        lennardjones_surf, lennardjones_obj, lennardjones_surfojb
    ] = configs

    if set_force is None:
        set_force = get_force

    date_and_time = datetime.datetime.today()
    get_date = date_and_time.strftime('%d.%m.%Y')
    get_time = date_and_time.strftime('%H:%M:%S')
    output = open(folder_path + 'info.txt', 'w')
    info = 'Date: {0}\nTime: {1}\nSimulation time: {2}\nSurface: {3} {4}\nObject: {5} {6}\nForce: {7}\nVelocity: {8}'
    output.write(
        info.format(get_date, get_time, simulation_time, element_surf,
                    dims_surf, element_obj, dims_obj, set_force, set_velocity))
    output.close()
    '''
    Simulation
    '''
    simulation = ft.FrictionSimulation()

    simulation.continue_from_trajectory(filename=folder_load +
                                        'simulation.traj')

    # Fix positions of the bottom slab
    bottom_indices = simulation.get_indices_z_less_than(
        z_limit=-2 * dims_surf[2] + 0.1)
    simulation.fix_positions(indices=bottom_indices, xyz=[True, True, True])

    # For restricting thermostat
    indices_surf_unfixed = simulation.get_indices_z_more_than(z_limit=-2 *
                                                              dims_surf[2])

    # Velocities
    indices_obj = simulation.get_indices_by_element(element=element_obj)
    velocities_obj = np.ones([len(indices_obj), 3], dtype='float')
    velocities_obj = velocities_obj * np.array(set_velocity)
    simulation.set_velocities(indices=indices_obj, velocity=velocities_obj)

    # Force
    if set_force is None:
        print 'Force is not set.'
    else:
        simulation.add_constant_force(indices=indices_obj, force=set_force)

    # Interacting lennard-jones forces between the particles.
    simulation.create_interaction([element_surf, element_surf],
                                  strength=lennardjones_surf[0],
                                  equilibrium_distance=lennardjones_surf[1])

    simulation.create_interaction([element_obj, element_obj],
                                  strength=lennardjones_obj[0],
                                  equilibrium_distance=lennardjones_obj[1])

    simulation.create_interaction([element_surf, element_obj],
                                  strength=lennardjones_surfojb[0],
                                  equilibrium_distance=lennardjones_surfojb[1])

    #
    simulation.list_atoms()

    #
    simulation.create_dynamics(dt=1.0,
                               temperature=300,
                               coupled_indices=indices_surf_unfixed,
                               strength=0.01)

    # Trajectory
    simulation.save_trajectory_during_simulation(interval=set_interval,
                                                 filename=folder_path +
                                                 'simulation.traj')
    # Energy and Temperature
    simulation.gather_energy_and_temperature_during_simulation(
        interval=set_interval, filename=folder_path + 'energy.txt')
    # Work
    simulation.gather_total_work_during_simulation(
        interval=set_interval,
        indices=indices_surf_unfixed,
        filename=folder_path + 'work_tot_surf.txt')
    simulation.gather_total_work_during_simulation(interval=set_interval,
                                                   indices=indices_obj,
                                                   filename=folder_path +
                                                   'work_tot_obj.txt')

    # Average positions
    simulation.gather_average_position_during_simulation(
        interval=set_interval,
        filename=folder_path + 'avr_positions_surf.txt',
        indices=indices_surf_unfixed)
    simulation.gather_average_position_during_simulation(
        interval=set_interval,
        filename=folder_path + 'avr_positions_obj.txt',
        indices=indices_obj)

    # Velocities
    simulation.gather_velocities_during_simulation(
        interval=simulation_time,
        filename=folder_path + 'velocities_surf.txt',
        indices=indices_surf_unfixed)
    simulation.gather_velocities_during_simulation(interval=simulation_time,
                                                   filename=folder_path +
                                                   'velocities_obj.txt',
                                                   indices=indices_obj)

    # Print Stats during simulation
    simulation.print_stats_during_simulation(interval=5.0)

    # Time the simulation
    t0 = time.time()
    simulation.run_simulation(time=simulation_time)
    t1 = time.time()

    runtime = "{ti} s".format(ti=str(int(t1 - t0)))
    output = open(folder_path + 'info.txt', 'a')
    output.write('\nRuntime: {0}'.format(runtime))
    output.close()
    print 'Time taken {0}'.format(runtime)

    # Convert .traj to .xyz
    ft.trajectory_to_xyz(filename_in=folder_path + 'simulation.traj',
                         filename_out=folder_path + 'simulation.xyz')