Exemple #1
0
def example_run_on_queue():
    frames = files.read_xyz("acetic_acid_dimer.xyz")
    return orca.job("aa_dimer_queue",
                    "! HF-3c Opt",
                    atoms=frames,
                    queue='shared',
                    procs=2)
Exemple #2
0
def opt_water():
    frames = files.read_xyz('water.xyz')
    return g09.job('water',
                   'HSEH1PBE/cc-pVTZ OPT=() SCRF(Solvent=Toluene)',
                   atoms=frames,
                   queue=None,
                   force=True)
Exemple #3
0
def fire(frames=files.read_xyz("CNH_HCN.xyz"), maxiter=1000):
    new_opt_params = {'dt': 0.1, 'euler': False, 'maxiter': maxiter}
    return neb.NEB("neb_test",
                   frames,
                   "! HF-3c",
                   opt="FIRE",
                   new_opt_params=new_opt_params)
Exemple #4
0
def compile(name, index, only=None):
    '''
    This function will compile together the xyz frames of a given index from
    MD NEB.

    **Parameters**

        name: *str*
            The NEB simulation name.
        index: *int*
            The index you wish to combine.
        only: *list, int, optional*
            Whether you only want certain indices or not.

    **Returns**

        frames: *list, list,* :class:`structure.Atom`
            The frames of said NEB.
    '''
    # Step 1 - Find how many frames exist
    fptrs = [
        f for f in os.listdir("lammps")
        if f.startswith("%s-%d-" % (name, index))
    ]
    if index == 0:
        fptrs = fptrs[1:-1]
    start = files.read_xyz("lammps/%s-0-0/%s_0.xyz" % (name, name))
    end = files.read_xyz("lammps/%s-0-%d/%s_%d.xyz" %
                         (name, len(fptrs) + 1, name, len(fptrs) + 1))

    if only is not None:
        start = [s for i, s in enumerate(start) if i in only]
        end = [s for i, s in enumerate(end) if i in only]

    frames = [start]
    for i, f in enumerate(fptrs):
        frame = files.read_xyz("lammps/%s-%d-%d/%s_%d.xyz" %
                               (name, index, i + 1, name, i + 1))
        if only is not None:
            frame = [s for j, s in enumerate(frame) if j in only]
        frames.append(frame)
    frames.append(end)

    return frames
Exemple #5
0
def quick_min(frames=files.read_xyz("CNH_HCN.xyz"), maxiter=1000):
    new_opt_params = {
        'dt': 0.1,
        'verbose': False,
        'euler': False,
        'maxiter': maxiter
    }
    return neb.NEB("neb_test",
                   frames,
                   "! HF-3c",
                   opt="QM",
                   new_opt_params=new_opt_params)
Exemple #6
0
def sd(frames=files.read_xyz("CNH_HCN.xyz"), maxiter=1000):
    new_opt_params = {
        'step_size': 0.1,
        'step_size_adjustment': 0.5,
        'max_step': 0.2,
        'linesearch': 'backtrack',
        'accelerate': True,
        'maxiter': maxiter
    }
    return neb.NEB("neb_test",
                   frames,
                   "! HF-3c",
                   opt="SD",
                   new_opt_params=new_opt_params)
Exemple #7
0
def example_2():
    # In this example, we illustrate how we can automate the generation of
    # gifs of the reactions in example_1

    print("Step 4 - Generating gifs...")

    # Generate a scratch folder for image generation
    scratch_folder = "./tmp"
    if os.path.exists(scratch_folder):
        shutil.rmtree(scratch_folder)

    print("    rotated_pathway.gif")
    os.mkdir(scratch_folder)
    ovito_xyz_to_gif(files.read_xyz("rotated_pathway.xyz"),
                     scratch_folder,
                     fname="rotated_pathway",
                     camera_pos=(0, 0, -10),
                     camera_dir=(0, 0, 1))
    shutil.rmtree(scratch_folder)

    print("    procrustes_pathway.gif")
    os.mkdir(scratch_folder)
    ovito_xyz_to_gif(files.read_xyz("procrustes_pathway.xyz"),
                     scratch_folder,
                     fname="procrustes_pathway",
                     camera_pos=(0, 0, -10),
                     camera_dir=(0, 0, 1))
    shutil.rmtree(scratch_folder)

    print("    smoothed_pathway.gif")
    os.mkdir(scratch_folder)
    ovito_xyz_to_gif(files.read_xyz("smoothed_pathway.xyz"),
                     scratch_folder,
                     fname="smoothed_pathway",
                     camera_pos=(0, 0, -10),
                     camera_dir=(0, 0, 1))
    shutil.rmtree(scratch_folder)
Exemple #8
0
def scipy(method="slsqp", frames=files.read_xyz("CNH_HCN.xyz"), maxiter=1000):
    new_opt_params = {
        'disp': False,
        'gtol': units.convert_energy("Ha", "eV", 1e-3),
        'eps': 1.4901161193847656e-08,
        'return_all': False,
        'maxiter': maxiter,
        'norm': 2.0,
        'ftol': 0.0
    }
    return neb.NEB("scipy",
                   frames,
                   "! HF-3c",
                   opt="scipy_" + method,
                   new_opt_params=new_opt_params)
Exemple #9
0
def minimize_benzene():
    '''
    This function will use LAMMPs minimize to ensure that our endpoints
    are minimized.
    '''

    P, mol1 = files.read_cml("benzene.cml", new_method=True)
    box = structures.System(name="benz", box_size=(20, 20, 20), periodic=True)
    mol1 = mol1[0]
    box.add(mol1)
    box.set_types(P)

    input_script = """units real
atom_style full
pair_style lj/cut/coul/cut 10.0
bond_style harmonic
angle_style harmonic
dihedral_style opls

boundary p p p
read_data benz.data

pair_modify mix geometric

""" + box.dump_pair_coeffs() + """

dump 1 all xyz 1 benzene.xyz
dump_modify 1 element """ + ' '.join(box.get_elements(P)) + """

minimize 1.0e-4 1.0e-6 1000 10000
"""
    input_script = input_script.strip()
    j = lammps_job.job("benz",
                       input_script,
                       system=box,
                       procs=1,
                       queue=None,
                       hybrid_angle=False,
                       params=P,
                       pair_coeffs_included=False,
                       no_echo=True)
    j.wait(1)

    new_atoms = files.read_xyz("lammps/benz/benzene.xyz")[-1]
    for a, b in zip(mol1.atoms, new_atoms):
        a.x, a.y, a.z = b.x, b.y, b.z

    files.write_cml(mol1, name="benzene_opt")
Exemple #10
0
def conjugate_gradient(frames=files.read_xyz("CNH_HCN.xyz"), maxiter=1000):
    new_opt_params = {
        'step_size': 0.1,
        'step_size_adjustment': 0.5,
        'max_step': 0.2,
        'linesearch': 'backtrack',
        'accelerate': True,
        'maxiter': maxiter,
        'method': 'FR',
        'linesearch': 'backtrack'
    }
    return neb.NEB("squid_cg",
                   frames,
                   "! HF-3c",
                   opt="CG",
                   new_opt_params=new_opt_params)
Exemple #11
0
def lbfgs(frames=files.read_xyz("CNH_HCN.xyz"), maxiter=1000):
    new_opt_params = {
        'step_size': 1.0,
        'step_size_adjustment': 0.5,
        'max_step': 0.04,
        'linesearch': None,
        'accelerate': True,
        'reset_step_size': 20,
        'maxiter': maxiter
    }
    return neb.NEB("neb_test",
                   frames,
                   "! HF-3c",
                   opt="LBFGS",
                   queue=None,
                   procs=1,
                   new_opt_params=new_opt_params,
                   ci_neb=True,
                   no_energy=False)
Exemple #12
0
def job(run_name, atoms, ecut, ecutrho=None, atom_units="Ang", route=None,
        pseudopotentials=None, periodic_distance=15,
        dumps="dump End Ecomponents ElecDensity",
        queue=None, walltime="00:30:00", procs=1, threads=None,
        redundancy=False,
        previous=None, mem=2000, priority=None, xhost=None,
        allocation=None):
    '''
    Wrapper to submitting a JDFTx simulation.

    **Parameters**

        run_name: *str*
            Name of the simulation to be run.
        atoms: *list,* :class:`squid.structures.atom.Atom` *, or str*
            A list of atoms for the simulation.  If a string is passed, it is
            assumed to be an xyz file (relative or full path).  If None is
            passed, then it is assumed that previous was specified.
        ecut: *float*
            The planewave cutoff energy in Hartree.
        ecutrho: *float, optional*
            The charge density cutoff in Hartree.  By default this is 4 * ecut.
        atom_units: *str, optional*
            What units your atoms are in.  JDFTx expects bohr; however,
            typically most work in Angstroms.  Whatever units are converted to
            bohr here.
        route: *str, optional*
            Any additional script to add to the JDFTx simulation.
        pseudopotentials: *list, str, optional*
            The pseudopotentials to use in this simulation.  If nothing is
            passed, a default set of ultra-soft pseudo potentials will be
            chosen.
        periodic_distance: *float, optional*
            The periodic box distance in Bohr.
        dumps: *str, optional*
            The outputs for this simulation.
        queue: *str, optional*
            What queue to run the simulation on (queueing system dependent).
        procs: *int, optional*
            How many processors to run the simulation on.
        threads: *int, optional*
            How many threads to run the simulation on.  By default this
            is procs.
        redundancy: *bool, optional*
            With redundancy on, if the job is submitted and unique_name is
            on, then if another job of the same name is running, a pointer
            to that job will instead be returned.
        previous: *str, optional*
            Name of a previous simulation for which to try reading in
            information using the MORead method.
        mem: *float, optional*
            Amount of memory per processor that is available (in MB).
        priority: *int, optional*
            Priority of the simulation (queueing system dependent).  Priority
            ranges (in NBS) from a low of 1 (start running whenever) to a
            high of 255 (start running ASAP).
        xhost: *list, str or str, optional*
            Which processor to run the simulation on(queueing system
            dependent).
        allocation: *str, optional*
            Whether to use a slurm allocation for this job or not.
            If so, specify the name.

    **Returns**

        job: :class:`squid.jobs.container.JobObject`
            Teturn the job container.
    '''
    raise Exception("NEEDS TO BE DONE!")

    if len(run_name) > 31 and queue is not None:
        raise Exception("Job name too long (%d) for NBS. \
Max character length is 31." % len(run_name))

    jdftx_path, jdftx_path_scripts = get_jdftx_obj()

    # Generate the orca input file
    os.system('mkdir -p jdftx/%s' % run_name)

    if previous is not None:
        shutil.copyfile(
            "jdftx/%s/%s.xyz" % (previous, previous),
            "jdftx/%s/%s.xyz" % (run_name, previous))
        shutil.copyfile(
            "jdftx/%s/%s.xyz" % (previous, previous),
            "jdftx/%s/%s.xyz" % (run_name, run_name))
        shutil.copyfile(
            "jdftx/%s/%s.ionpos" % (previous, previous),
            "jdftx/%s/%s.ionpos" % (run_name, previous))
        shutil.copyfile(
            "jdftx/%s/%s.lattice" % (previous, previous),
            "jdftx/%s/%s.lattice" % (run_name, previous))

    os.chdir('jdftx/%s' % run_name)

    # Start from a blank output file
    if os.path.isfile("%s.out" % run_name):
        os.system("mv %s.out %s_prev.out" % (run_name, run_name))

    if threads is None:
        threads = procs

    if jdftx_path.endswith("/"):
        jdftx_path = jdftx_path[:-1]

    if jdftx_path_scripts.endswith("/"):
        jdftx_path_scripts = jdftx_path_scripts[:-1]

    if atoms is not None:
        if not isinstance(atoms, str):
            for a in atoms:
                a.element = units.elem_i2s(a.element)
            files.write_xyz(atoms, "%s.xyz" % run_name)
        else:
            atoms = files.read_xyz(atoms)
            for a in atoms:
                a.element = units.elem_i2s(a.element)
            files.write_xyz(atoms, "%s.xyz" % run_name)

    if run_name.endswith(".xyz"):
        run_name = run_name.split(".xyz")[0]

    # NOTE! xyzToIonposOpt will convert xyz Angstroms to Bohr
    os.system("%s/xyzToIonposOpt %s.xyz %d > xyzToIonpos.log"
              % (jdftx_path_scripts, run_name, periodic_distance))

    previous_name = None
    if previous:
        previous_name = previous
        previous = "initial-state %s.$VAR" % previous

    # First, read in the xyz file to determine unique elements
    if pseudopotentials is None and atoms is not None:
        pseudopotentials = []
        elements = geometry.reduce_list([a.element.lower() for a in atoms])
        all_pps = [fname for fname in os.listdir(
            "%s/pseudopotentials/GBRV" % jdftx_path)
            if fname.endswith("uspp") and "pbe" in fname]
        for e in elements:
            potential_pps = []
            for pp in all_pps:
                if pp.startswith("%s_" % e):
                    potential_pps.append(pp)
            if len(potential_pps) < 1:
                raise Exception(
                    "Unable to automatically grab potential for element %s."
                    % e)
            else:
                # In theory this should be the "largest" number based on
                # the naming convention.
                potential_pps.sort()
                pseudopotentials.append("GBRV/" + potential_pps[0])

    if atoms is None:
        pseudopotentials = '''ion-species GBRV/$ID_pbe_v1.2.uspp
ion-species GBRV/$ID_pbe_v1.01.uspp
ion-species GBRV/$ID_pbe_v1.uspp'''
    else:
        pseudopotentials = "\n".join([
            "ion-species %s" % pp for pp in pseudopotentials])

    script = '''
# --------------- Molecular Structure ----------------

$$ATOMS$$
coords-type cartesian

$$PREVIOUS$$

# --------------- System Parameters ----------------

elec-cutoff $$ECUT$$ $$ECUTRHO$$

# Specify the pseudopotentials (this defines species O and H):
$$PSEUDOPOTENTIALS$$

# --------------- Outputs ----------------

dump-name $$NAME$$.$VAR              #Filename pattern for outputs
$$DUMPS$$  #Output energy components and electron density at the end
'''

    atom_str = '''include $$NAME$$.lattice
include $$NAME$$.ionpos'''

    if atoms is not None:
        atom_str = atom_str.replace("$$NAME$$", run_name)
    else:
        if previous_name is None:
            raise Exception("Forgot to specify previous when atoms is None!")
        atom_str = atom_str.replace("$$NAME$$", previous_name)
    script = script.replace("$$ATOMS$$", atom_str)

    while "$$NAME$$" in script:
        script = script.replace("$$NAME$$", run_name)
    if ecutrho is None:
        ecutrho = ""
    while "$$ECUTRHO$$" in script:
        script = script.replace("$$ECUTRHO$$", str(ecutrho))
    while "$$ECUT$$" in script:
        script = script.replace("$$ECUT$$", str(ecut))
    while "$$PSEUDOPOTENTIALS$$" in script:
        script = script.replace("$$PSEUDOPOTENTIALS$$", pseudopotentials)
    if previous is not None:
        script = script.replace("$$PREVIOUS$$", previous)
    else:
        script = script.replace("$$PREVIOUS$$", "")
    script = script.replace("$$DUMPS$$", dumps)

    if route is not None:
        script += "\n# --------------- Outputs ----------------\n\n"
        script += route.strip() + "\n\n"

    fptr = open("%s.in" % run_name, 'w')
    fptr.write(script)
    fptr.close()

    # Run the simulation
    if queue is None:
        process_handle = subprocess.Popen(
            "%s/jdftx -i %s.in -o %s.out"
            % (jdftx_path, run_name, run_name), shell=True
        )
    elif queue == 'debug':
        print('Would run %s' % run_name)
    else:
        job_to_submit =\
            "source ~/.zshrc\nmpirun -n %d jdftx -c %d -i %s.in -o %s.out"\
            % (procs, threads, run_name, run_name)

        jobs.submit_job(run_name, job_to_submit,
                        procs=procs,
                        queue=queue,
                        mem=mem,
                        priority=priority,
                        walltime=walltime,
                        xhosts=xhost,
                        redundancy=redundancy,
                        unique_name=True,
                        allocation=allocation)
        time.sleep(0.5)
    # Copy run script
    fname = sys.argv[0]
    if '/' in fname:
        fname = fname.split('/')[-1]
    try:
        shutil.copyfile('../../%s' % fname, fname)
    except IOError:
        # Submitted a job oddly enough that sys.argv[0]
        # is not the original python file name, so don't do this
        pass

    # Return to the appropriate directory
    os.chdir('../..')

    if queue is None:
        return jobs.Job(run_name, process_handle=process_handle)
    else:
        return jobs.Job(run_name)
Exemple #13
0
def example_run_local():
    frames = files.read_xyz("acetic_acid_dimer.xyz")
    return orca.job("aa_dimer_local_2",
                    "! HF-3c Opt",
                    atoms=frames,
                    queue=None)
Exemple #14
0
def opt_CNH_start():
    # Read in the xyz file
    frames = files.read_xyz("CNH_start.xyz")
    # Run a simulation locally using the Hartree Fock method (with 3 corrections)
    return orca.job("CNH_start", "! HF-3c Opt", atoms=frames, queue="short")
Exemple #15
0
def procrustes():
    # Default Documentation
    help_info = '''
procrustes
---------
A command line tool to run procrustes along an xyz file.

procrustes [file.xyz] [Options]

    Flag            Default         Description
-help, -h        :            :  Print this help menu
-overwrite, -o   :            :  Overwrite the initial file
-append, -a      :   _proc    :  Change the appended name alteration
-interpolate, -i :            :  This will turn on linear interpolation
-rmax            :    0.5     :  The default max rms for interpolation
-fmax            :     25     :  The default max number of frames for
                                 interpolation
-nframes, -n     :            :  If specified, interpolate to exactly n
                                 frames.
-between, -b     :            :  If specified, then interpolation is only
                                 run between the two frames.  Note, this
                                 is [x, y) inclusive.

Default behaviour is to use procrustes on an xyz to best align
the coordinates, and then to save a new xyz file with the name
OLD_proc.xyz (where OLD is the original xyz file name).

NOTE! If you specify -o and -a, then appending will occur instead
of overwritting.

Ex.

procrustes demo.xyz
procrustes demo.xyz -i -n 20
procrustes demo.xyz -i -rmax 0.1 -fmax 30
procrustes demo.xyz -i -b 5 8 -n 6
'''

    # Parse Arguments
    if '-h' in argv or '-help' in argv or len(argv) < 2:
        print(help_info)
        exit()

    # Parse Arguments
    append = "_proc"

    path = os.getcwd()
    if not path.endswith("/"):
        path += "/"

    file_name = argv[1]
    interpolate = False
    rmax = 0.5
    fmax = 25
    nframes = None
    b_start, b_stop = None, None

    if ".xyz" in file_name:
        file_name = file_name.split(".xyz")[0]

    if "-o" in argv[2:]:
        append = ""
    elif "-overwrite" in argv[2:]:
        append = ""

    if "-i" in argv[2:]:
        interpolate = True
    elif "-interpolate" in argv[2:]:
        interpolate = True

    if "-a" in argv[2:]:
        append = argv[argv.index('-a') + 1]
    elif "-append" in argv[2:]:
        append = argv[argv.index('-append') + 1]

    if "-n" in argv[2:]:
        nframes = int(argv[argv.index('-n') + 1])
    elif "-nframes" in argv[2:]:
        nframes = int(argv[argv.index('-nframes') + 1])

    if "-b" in argv[2:]:
        b_start = int(argv[argv.index('-b') + 1])
        b_stop = int(argv[argv.index('-b') + 2])
    elif "-between" in argv[2:]:
        b_start = int(argv[argv.index('-between') + 1])
        b_stop = int(argv[argv.index('-between') + 2])

        assert b_start >= 0, "b_start must be >= 0."
        assert b_stop >= 2 + b_start, "b_stop must be >= 2 + b_start."

    if "-rmax" in argv[2:]:
        rmax = float(argv[argv.index('-rmax') + 1])

    if "-fmax" in argv[2:]:
        fmax = int(argv[argv.index('-fmax') + 1])

    frames = files.read_xyz(path + file_name + ".xyz")

    if interpolate:
        frames_hold = [copy.deepcopy(f) for f in frames]
        if b_start is not None:
            frames = frames[b_start:b_stop]
        frames = geometry.smooth_xyz(frames,
                                     R_max=rmax,
                                     F_max=fmax,
                                     N_frames=nframes,
                                     use_procrustes=True)
        if b_start is not None:
            a = frames_hold[:b_start]
            b = frames
            c = frames_hold[b_stop - 1:]
            if not isinstance(a[0], list):
                a = [a]
            if not isinstance(b[0], list):
                b = [b]
            if not isinstance(c[0], list):
                c = [c]
            frames = a + b + c

    _ = geometry.procrustes(frames)
    files.write_xyz(frames, path + file_name + append + ".xyz")
Exemple #16
0
from squid import orca
from squid import files


if __name__ == "__main__":
    # First, calculate relevant information
    frames = files.read_xyz('water.xyz')
    job_handle = orca.job(
        'water',
        '! PW6B95 def2-TZVP D3BJ OPT NumFreq',
        atoms=frames,
        queue=None)
    job_handle.wait()

    # Next, post process it
    orca.mo_analysis(
        "water", orbital=[6, 7, 8],
        H**O=True, LUMO=True,
        wireframe=False, hide=True, iso=0.04,
        vmd_file_name="water", run_vmd=False
    )
Exemple #17
0
# System imports
import os
import copy

# Squid imports
from squid import files
from squid import geometry

# First we want to read in the manually made iterations
fptrs = [int(f.split(".xyz")[0]) for f in os.listdir("reaction_coordinate")]
fptrs.sort()

# Now, we loop through all files in numerical order and append to our reaction coordinate
rxn = []
for f in fptrs:
    rxn.append(files.read_xyz("reaction_coordinate/%d.xyz" % f))

# Save an example of this rough reaction we made
files.write_xyz(rxn, "reaction_coordinate_rough")

# Now, we smooth it out.  There are many ways of doing so.  We'll only show the main two methods here
# Here we just make a copy of the frames for the second method
held_rough_reaction = copy.deepcopy(rxn)

# Method 1 - Procrustes to minimize rotations and translations between consecutive frames
geometry.procrustes(rxn)
files.write_xyz(rxn, "reaction_coordinate_procrustes")

# Method 2 - Procrustes plus linear interpolation
# Note, R_MAX is the maximum average change in atomic positions between adjacent frames (in angstroms)
#       F_MAX is the maximum number of frames we want in the final reaction coordinate
Exemple #18
0
    b_start = int(argv[argv.index('-b') + 1])
    b_stop = int(argv[argv.index('-b') + 2])
elif "-between" in argv[2:]:
    b_start = int(argv[argv.index('-between') + 1])
    b_stop = int(argv[argv.index('-between') + 2])

    assert b_start >= 0, "b_start must be >= 0."
    assert b_stop >= 2 + b_start, "b_stop must be >= 2 + b_start."

if "-rmax" in argv[2:]:
    rmax = float(argv[argv.index('-rmax') + 1])

if "-fmax" in argv[2:]:
    fmax = int(argv[argv.index('-fmax') + 1])

frames = files.read_xyz(path + file_name + ".xyz")

if interpolate:
    frames_hold = [copy.deepcopy(f) for f in frames]
    if b_start is not None:
        frames = frames[b_start:b_stop]
    frames = geometry.smooth_xyz(frames,
                                 R_MAX=rmax,
                                 F_MAX=fmax,
                                 PROCRUSTES=True,
                                 N_FRAMES=nframes)
    if b_start is not None:
        a = frames_hold[:b_start]
        b = frames
        c = frames_hold[b_stop - 1:]
        if not isinstance(a[0], list):
Exemple #19
0
def opt_water_orca():
    frames = files.read_xyz('water.xyz')
    return orca.job('water',
                    '! pw6b95 def2-TZVP D3BJ OPT NumFreq',
                    atoms=frames,
                    queue=None)