예제 #1
0
def viewStructs(name, directory, kind = 'gen'):
    """
    View collection of structures as a "trajectory"

    Args:
        - name (str): substring unique to structures (.gen, POSCAR, slab, etc)
        - directory (str): Directory where the structures live
        - kind: kind of output froim list of (vasp, gen)
        
    Opens viewer with loaded trajectory (if remote, need X server)
    """
    geometries = []
    files = os.listdir(directory)

    if kind == 'gen':
        pattern = r"{}.*.gen".format(name)
    elif kind == 'vasp':
        pattern = r"{}".format(name)
    else:
        raise ValueError("file kind must be from (vasp, gen)")

    for i in files:
        key = re.search(pattern, i)

        if key:
            if kind == 'gen':
                geometries +=  [gen.read_gen(directory + i)]
            elif kind == 'vasp':
                geometries +=  [vasp.read_vasp(directory + i)]
            else:
                raise ValueError("file kind must be from (vasp, gen)")
    view(geometries)
예제 #2
0
def getabBondcountStructure(data, idx, element):
    """
    Gets a struture with 'charges' equal to nbonds between a (fixed) and b(``element``) 
    data needs geom, coordlabels, and (optionally) wantedIndices columns
    geom is Atoms object of structure
    coordlabels is a raw output from the coordlabeller function (relcoords and raw bonds)
    element is desired secondary element (primary element determined by input)
    Calls view() on resulting geometry
    Returns the structure
    """
    coordlabels = data.loc[idx, 'coordlabels']
    geometry = data.loc[idx, 'geom']
    if 'wantedIndices' in data:
        indices = data.loc[idx, 'wantedIndices']
    else:
        indices = np.arange(len(geometry))
    
    bondcounts = {key: np.sum(
            np.array([geometry[i].symbol for i in value]) == element
        ) for key, value in 
         pd.Series(coordlabels[1])[indices].items()
        }
    charges = [0] * len(geometry)
    for i in range(len(charges)):
        charges[i] = bondcounts.get(i, -1)
    geometry.set_initial_charges(charges)
    view(geometry)
    return geometry
예제 #3
0
def test_03():

    lammps_setting = {'data_lmp':'data.lmp', 
                      'in_lmp':'in.min',
                       'lammps_exe' :'/opt/lmpizarro/GitHub/lammps/src/lmp_serial'}

    setting ={'elements':['Al', 'Fe'], 'pot':'zhou', \
              'pca':[20], 'nAtoms':250,\
              #'structure':'bcc',\
              #'positions':'rnd','a':3.0, 'period':[5,5,5]}

              'structure':'rnd',\
              'positions':'rnd','a':4.2, 'period':[5,5,5],\
              'lammps_setting':lammps_setting }

    
    sys = System(setting)
    print sys.setting['elements']
    print sys.setting['nAt']
    print sys.setting['pca']
    print 'atoms', sys.elsProps
    print 'bulk', sys.bulk

    view(sys.bulk)

    print sys.Interaction()
예제 #4
0
def test_replay(testdir):
    # Distance between Cu atoms on a (100) surface:
    d = 3.6 / sqrt(2)
    a = Atoms('Cu',
              positions=[(0, 0, 0)],
              cell=(d, d, 1.0),
              pbc=(True, True, False))
    a *= (2, 2, 1)  # 2x2 (100) surface-cell

    # Approximate height of Ag atom on Cu(100) surfece:
    h0 = 2.0
    a += Atom('Ag', (d / 2, d / 2, h0))

    if 0:
        view(a)

    constraint = FixAtoms(range(len(a) - 1))
    a.calc = EMT()
    a.set_constraint(constraint)

    with QuasiNewton(a, trajectory='AgCu1.traj', logfile='AgCu1.log') as dyn1:
        dyn1.run(fmax=0.1)

    a = read('AgCu1.traj')
    a.calc = EMT()
    print(a.constraints)

    with QuasiNewton(a, trajectory='AgCu2.traj', logfile='AgCu2.log') as dyn2:
        dyn2.replay_trajectory('AgCu1.traj')
        dyn2.run(fmax=0.01)
예제 #5
0
def viewSuperCell(atoms):
    P = build.find_optimal_cell_shape_pure_python(atoms.cell, 32, "sc")
    atoms = build.make_supercell(atoms, P)
    atoms[0].symbol = "Mg"
    atoms[1].symbol = "Mg"
    atoms[2].symbol = "Mg"
    view(atoms, viewer="Avogadro")
예제 #6
0
def main():
    cif_dir = "//data/GOO.cif"
    zeolite = Zeotype.build_from_cif_with_labels(cif_dir)
    view(zeolite)
    iz = zeolite.get_imperfect_zeotype()
    iz = iz.create_silanol_defect(95)
    view(iz)
예제 #7
0
def main( uid ):
    db_name = "ce_hydrostatic.db"
    db_name = "almg_217.db"
    db = connect( db_name )
    atoms = db.get_atoms( id=uid )
    print ( "Chemical formula {}".format(atoms.get_chemical_formula()) )
    view(atoms)
def create_relaxed_Na_cluster(N, view=False):
    print(f'************ Na{N} ************')
    start = time.time()
    #**** Initialize system ****#
    if N==6:
        clust = Atoms('Na'*6, positions=[(1,1,0),(1,-1,0),(-1,-1,0),(-1,1,0),(0,0,1),(0,0,-1)], cell=(d, d, d))
    else:
        clust = Atoms('Na'*N, positions=[np.random.randn(3) for i in range(N)], cell=(d, d, d))  # random initialization
    clust.center()
    if view:
        view(clust)
    #**** Define the calculator ****#
    calc = GPAW(nbands=10,
                h=0.25,
                txt=f'Na{N}_out.txt',
                occupations=FermiDirac(0.05),
                setups={'Na': '1'},
                mode='lcao',
                basis='dzp')
    #**** Relax the system ****#
    clust.set_calculator(calc)
    dyn = GPMin(clust, trajectory=f'Na{N}_relax_clust.traj', logfile='Na{N}_relax_clust.log')
    print(f'**** Relaxing system of {N} atoms ****')
    dyn.run(fmax=0.02, steps=100)
    #**** Calculate energy and wavefunction ****#
    e = clust.get_potential_energy()  # Note opposite signa from ga.py
    e_file = open(f'Na{N}_e_cluster.txt', 'w')
    print(f'Na{N} cluster energy: {e} eV', file=e_file)
    calc.write(f'Na{N}_cluster.gpw', mode='all')
    end = time.time()
    print(f'**** Elapsed time: {end-start} s ****')
    print('*****************************\n')
예제 #9
0
def view_all():
    a = 4.05
    c = 6.0
    cell = [[2.0 * a, 0, 0], [0.0, np.sqrt(3) * a, 0.0], [0.0, 0.0, c]]

    hcp_sites = [
        [a / 2.0, 0.0, 0.0], [3.0 * a / 2.0, 0.0, 0.0],
        [0.0, np.sqrt(3.0) * a / 2.0, 0.0],
        [2.0 * a, np.sqrt(3.0) * a / 2.0,
         0.0], [a / 2.0, np.sqrt(3.0) * a,
                0.0], [3.0 * a / 2.0, np.sqrt(3.0) * a, 0.0],
        [a, np.sqrt(3.0) * a / 2.0,
         0.0], [a, a * (0.5 * np.sqrt(3) - 1 / np.sqrt(3.0)), c / 2.0],
        [a / 2.0, 0.5 * a * (np.sqrt(3) + 1.0 / np.sqrt(3.0)), c / 2.0],
        [3.0 * a / 2.0, 0.5 * a * (np.sqrt(3) + 1.0 / np.sqrt(3.0)), c / 2.0]
    ]

    bcc_sites = [[0.0, 0.0, 0.0], [2.0 * a, 0.0, 0.0],
                 [0.0, np.sqrt(3.0) * a, 0.0],
                 [2.0 * a, np.sqrt(3.0) * a, 0.0],
                 [a, 0.5 * np.sqrt(3) * a, c / 2.0]]

    hcp_symbs = ["V" for _ in range(len(hcp_sites))]
    bcc_symbs = ["Si" for _ in range(len(bcc_sites))]
    symbs = hcp_symbs + bcc_symbs
    sites = hcp_sites + bcc_sites
    atoms = Atoms(symbs, sites)
    atoms.set_cell(cell)
    view(atoms)
예제 #10
0
def test_adsorbate_placer():
    from ase.io import read
    from ase.build import molecule
    import numpy as np
    from carmm.build.adsorbate_placer import place_adsorbate, rotate_and_place_adsorbate
    from ase import Atoms

    molecule = molecule('CH3CH2OH')
    h_atom = Atoms('H', positions=[(0, 0, 0)])

    site = read("data/H-Y_cluster/H-Y_cluster.xyz")

    zeolite, rotated_ads = place_adsorbate(h_atom, site, 0, 0, 1.0)

    ads_and_site, rotated_ads = rotate_and_place_adsorbate(
        molecule, zeolite, 1.0, 2, 0, 0, rotation=[-45, 0, -45])

    comp_pos1 = np.array([2.00311656e+01, 5.31509397e+00, 1.89702619e+00])
    comp_pos2 = np.array([2.04405930e+01, 4.53669268e+00, 2.54385921e+00])

    error_pos1 = np.linalg.norm(comp_pos1 - rotated_ads.positions[0], axis=-1)
    error_pos2 = np.linalg.norm(comp_pos2 - rotated_ads.positions[-1], axis=-1)

    assert np.isclose(error_pos1, 0, rtol=0,
                      atol=1e-06), f"Error = {error_pos1}"
    assert np.isclose(error_pos2, 0, rtol=0,
                      atol=1e-06), f"Error = {error_pos2}"

    from ase.visualize import view
    view(ads_and_site)
예제 #11
0
    def open_file(self):
        # select a file name in the selected folder :
        name = askopenfilename(initialdir=self.dirname)
        try:
            datatype = name.split('.')[-1]
        except:
            datatype = 'error'
        # text files
        if datatype == 'txt' or datatype == 'dat' or datatype == 'out' or name.find(
                'README') != -1:
            with open(name, 'r') as UseFile:
                s = UseFile.read()
                self.text.delete("1.0", "end")
                self.text.insert(END, s)
                self.text.pack()
                #self.display.pack()
                #self.text.grid(column=0,row=0)
                #self.columnconfigure(1, weight=1)
                #self.columnconfigure(3, pad=7)
                #self.rowconfigure(3, weight=1)
                #self.rowconfigure(5, pad=7)

                #self.text.grid(row=0, columnspan=2, rowspan=4,padx=5, sticky=E+W+S+N)
                #self.display.grid(row=0, columnspan=2, rowspan=4,padx=5, sticky=E+W+S+N)

                self.text.update()
                self.newwin.update()
                self.newwin.deiconify()
        # material structural formats using ase
        if datatype == 'xyz' or datatype == 'cif':
            struct = read(name)
            view(struct)
예제 #12
0
def convert_to_cubic(setting_prim):
    conc_args = {
        "conc_ratio_min_1":[[64,0,0]],
        "conc_ratio_max_1":[[24,40,0]],
        "conc_ratio_min_2":[[64,0,0]],
        "conc_ratio_max_2":[[22,21,21]]
    }
    setting_cubic = BulkCrystal( crystalstructure="fcc", a=4.05, size=[3,3,3], basis_elements=[["Mg","Si","Al",]], \
    conc_args=conc_args, db_name=db_name_cubic, max_cluster_size=4, cubic=True )
    view(setting_cubic.atoms)
    atoms = setting_prim.atoms.copy()
    a = 4.05
    atoms.set_cell([[4*a,0,0],[0,4*a,0],[0,0,4*a]])
    atoms.wrap()
    view(atoms)
    print (setting_prim.atoms.get_cell())
    exit()
    out_file = "data/temp_out.xyz"
    target_cell = setting_cubic.atoms.get_cell()
    cubic_str_gen = struc_generator = GenerateStructures( setting_cubic, struct_per_gen=10 )
    db = connect(db_name)
    for row in db.select(converged=1):
        energy = row.energy
        atoms = row.toatoms()
        atoms.set_cell(target_cell)
        atoms.wrap()
        write(out_file,atoms)
        calc = SinglePointCalculator(atoms,energy=energy)
        atoms.set_calculator(calc)
        cubic_str_gen.insert_structure(init_struct=out_file,final_struct=atoms)
예제 #13
0
def prebeta_spacegroup(n_template_structs=0):
    atoms = bulk("Al", cubic=True)

    # Add one site at the center
    L = atoms.get_cell()[0,0]
    at = Atoms( "X", positions=[[L/2,L/2,L/2]] )
    atoms.extend(at)
    view(atoms)
    sp_gr = get_spacegroup(atoms)
    print(sp_gr)
    print(atoms.get_scaled_positions())

    sc = atoms*(6,6,6)
    jump_moves = CollectiveJumpMove(mc_cell=sc)
    jump_moves.view_columns()
    temp_atoms = atoms*(2,2,2)
    print(len(temp_atoms))
    view(temp_atoms)

    if n_template_structs > 0:
        symbs = ["Al","Mg","Si"]
        for i in range(n_template_structs):
            atoms = bulk("Al",cubic=True,a=4.05)
            selection = [symbs[randint(low=0,high=3)] for _ in range(len(atoms))]
            for indx in range(len(atoms)):
                atoms[indx].symbol = selection[indx]
            at = Atoms( "X", positions=[[L/2,L/2,L/2]] )
            atoms.extend(at)
            atoms = atoms*(2,2,2)
            fname = "data/prebeta_template{}.xyz".format(i)
            write(fname,atoms)
            print("Template structure written to {}".format(fname))
예제 #14
0
def remove_CO(CONTCAR_filename, view_flag=True):
    '''
    Read the old CONTCAR file with a CO onto it
    remove the CO and save as a new CONTCAR
    '''
    old_name = CONTCAR_filename  #'pd20-ceria-co-CONTCAR'
    atoms = read(old_name)

    # find number of Pd
    # find C atom index
    nPd = 0

    for i, atom in enumerate(atoms):
        if atom.symbol == 'Pd':
            nPd = nPd + 1
        if atom.symbol == 'C':
            C_in_CO = i

    C_O_Dist = []
    O_in_CO = []

    for k, atom in enumerate(atoms):
        if atom.symbol == 'O':
            dist = atoms.get_distance(C_in_CO, k)
            C_O_Dist.append(dist)
            O_in_CO.append(k)

    O_in_CO = O_in_CO[C_O_Dist.index(min(C_O_Dist))]

    del atoms[[O_in_CO, C_in_CO]]
    write('pd' + str(nPd) + '-no-CO-CONTCAR', atoms)

    # View the atom object if the flag is true
    if view_flag:
        view(atoms)
예제 #15
0
파일: jasp_neb.py 프로젝트: biliu/jasp
def plot_neb(self, show=True):
    '''
    retrieve the energies and atoms from the band
    by default shows the plot figure
    '''
    import jasp
    try:
        images, energies = self.get_neb()
    except (jasp.VaspQueued):
        # let's get a snapshot of the progress
        calc = read_neb_calculator()

        images = calc.neb_images
        energies = []
        energies += [float(open('00/energy').readline())]
        for i in range(1,len(images)-1):
            f = open('0{0}/OUTCAR'.format(i))
            elines = []
            for line in f:
                if 'energy w' in line:
                    elines += [line]
            f.close()

            # take last line
            fields = elines[-1].split()
            energies += [float(fields[-1])]
        energies += [float(open('0{0}/energy'.format(len(images)-1)).readline())]

    energies = np.array(energies) - energies[0]

    # add fitted line to band energies. we make a cubic spline
    # interpolating function of the negative energy so we can find the
    # minimum which corresponds to the barrier
    from scipy.interpolate import interp1d
    from scipy.optimize import fmin
    f = interp1d(range(len(energies)),
                 -energies,
                 kind='cubic', bounds_error=False)
    x0 = len(energies)/2. #guess barrier is at half way
    xmax = fmin(f, x0)

    xfit = np.linspace(0,len(energies)-1)
    bandfit = -f(xfit)

    import matplotlib.pyplot as plt
    p = plt.plot(energies-energies[0],'bo ',label='images')
    plt.plot(xfit, bandfit,'r-',label='fit')
    plt.plot(xmax,-f(xmax),'* ',label='max')
    plt.xlabel('Image')
    plt.ylabel('Energy (eV)')
    s = ['$\Delta E$ = {0:1.3f} eV'.format(float(energies[-1]-energies[0])),
         '$E^\ddag$ = {0:1.3f} eV'.format(float(-f(xmax)))]

    plt.title('\n'.join(s))
    plt.legend(loc='best', numpoints=1)
    if show:
        from ase.visualize import view
        view(images)
        plt.show()
    return p
예제 #16
0
파일: mmbjmp.py 프로젝트: jboes/ase
    def __getitem__(self, name):
        d = self.data[name]
        # the index of label in labels less one
        # (compound is already as key in d)
        a = d[self.labels.index("aexp") - 1]
        if name in ["Cr2CoGa", "Mn2CoAl", "Mn2CoGe", "Fe2CoSi"]:
            # http://en.wikipedia.org/wiki/Space_group
            sg = 216
        else:
            sg = 225
        symbols = string2symbols(name)
        symbols.pop(0)
        b = crystal(
            symbols=symbols,
            basis=[(1.0 / 4, 1.0 / 4, 1.0 / 4), (0.0, 0.0, 0.0), (1.0 / 2, 1.0 / 2, 1.0 / 2)],
            spacegroup=sg,
            cellpar=[a, a, a, 90, 90, 90],
            primitive_cell=True,
        )
        # set average moments on all atoms (add + 2.0)
        magmom = d[self.labels.index("mexp") - 1] + 2.0
        m = [magmom / len(b)] * len(b)
        # break spin symmetry between atoms no. 1 and 2
        m[1] = m[1] + m[2]
        m[2] = -m[2]
        b.set_initial_magnetic_moments(m)
        if 0:
            from ase.visualize import view

            view(b)

        return b
예제 #17
0
def _import_ase(filename, **kwargs):
    """
    Imports a structure in a number of formats using the ASE routines.
    """
    from os.path import abspath
    from aiida.orm.data.structure import StructureData

    try:
        import ase.io
    except ImportError:
        echo.echo_critical("You have not installed the package ase. \n"
                           "You can install it with: pip install ase")

    store = kwargs.pop('store')
    view_in_ase = kwargs.pop('view')

    echo.echo('importing structure from: \n  {}'.format(abspath(filename)))
    filepath = abspath(filename)

    try:
        asecell = ase.io.read(filepath)
        new_structure = StructureData(ase=asecell)

        if store:
            new_structure.store()
        if view_in_ase:
            from ase.visualize import view
            view(new_structure.get_ase())
        echo.echo('  Succesfully imported structure {}, '
                  '(PK = {})'.format(new_structure.get_formula(),
                                     new_structure.pk))

    except ValueError as err:
        echo.echo_critical(err)
예제 #18
0
def main():
    aluminum = build.bulk("Al", crystalstructure="fcc") * 4
    print(len(aluminum))

    # Extract 3 111 planes
    planes = build.cut(aluminum, (1, -1, 0), (1, 1, -2), nlayers=3)
    view(planes, viewer="Avogadro")
예제 #19
0
def _import_pwi(filename, **kwargs):
    """
    Imports a structure from a quantumespresso input file.
    """
    from os.path import abspath
    try:
        from qe_tools.parsers.pwinputparser import PwInputFile
    except ImportError:
        echo.echo_critical("You have not installed the package qe-tools. \n"
                           "You can install it with: pip install qe-tools")

    store = kwargs.pop('store')
    view_in_ase = kwargs.pop('view')

    echo.echo('importing structure from: \n  {}'.format(abspath(filename)))
    filepath = abspath(filename)

    try:
        inputparser = PwInputFile(filepath)
        new_structure = inputparser.get_structuredata()

        if store:
            new_structure.store()
        if view_in_ase:
            from ase.visualize import view
            view(new_structure.get_ase())
        echo.echo('  Succesfully imported structure {}, '
                  '(PK = {})'.format(new_structure.get_formula(),
                                     new_structure.pk))

    except ValueError as err:
        echo.echo_critical(err)
예제 #20
0
def main1():
    traj = read('MFI_2Al_replaced.traj', ':')
    traj_CuOCu = []
    for atoms in traj:
        inserted_atoms = insert_CuOCu(atoms)
        traj_CuOCu.append(inserted_atoms)
    view(traj_CuOCu)
예제 #21
0
def view_avo(atoms):
    from ase.visualize import view
    if atoms._calc and atoms.calc.__module__ == 'gausspy.gaussian':
        os.system("avogadro {f}".format(f=atoms.calc.label + '.log'))
    else:
        print('Viewing xyz file')
        view(atoms,viewer='avogadro')
예제 #22
0
def chemical_potential_sweep(ceBulk, eci, chem_pots=None):
    solver = Solver(ceBulk, eci, verbose=True, chem_pot={"Mg": 0.0})
    ceBulk.atoms[0].symbol = "Mg"
    model = solver.get_model()

    if (not chem_pots is None):
        for chem in chem_pots:
            print("Current: chemical potential {}".format(chem))
            solver.update_chemical_potentials(model, {"Mg": chem})
            solver.solve("gurobi", model)
            view(ceBulk.atoms)
    else:
        lower = 0.0
        upper = 0.1
        # Find upper and lower bounds for pure phase
        for i in range(0, 100):
            current = (lower + upper) / 2.0
            model = solver.update_chemical_potentials(model, {"Mg": current})

            # Bisection
            solver.solve("gurobi", model)
            elms = solver.get_atoms_count()
            if (elms["Mg"] >= 32):
                lower = current
            else:
                upper = current
            if (elms["Mg"] < 64 and elms["Mg"] > 16):
                break
        view(ceBulk.atoms)
        print(lower, upper)
예제 #23
0
def view_avo(atoms):
    from ase.visualize import view
    if atoms._calc and atoms.calc.__module__ == 'gausspy.gaussian':
        os.system("avogadro {f}".format(f=atoms.calc.label + '.log'))
    else:
        print('Viewing xyz file')
        view(atoms, viewer='avogadro')
예제 #24
0
def addAdsorbate(constraint="1"):
    constrnts = AND(COMPLETED, RELAX, SURFACE, SYMMETRIC(False), constraint)

    ads = {'H': ['O1']}

    output = db.query(['fwid', 'params_json', 'finaltraj_pckl'], constrnts)
    question = 'Are you sure you want to add adsorbates to %d slabs?' % len(
        output)

    if ask(question):
        for fw, paramStr, ftraj in output:
            params = json.loads(paramStr)

            newsurf = surfFuncs.adsorbedSurface(
                ftraj, json.loads(params['facet_json']), ads)
            if jobs.Job(params).spinpol():
                newsurf.set_initial_magnetic_moments([
                    3 if e in misc.magElems else 0
                    for e in newsurf.get_chemical_symbols()
                ])
            ase.visualize.view(newsurf)

            params['name'] += '_' + printAds(ads)
            params['surfparent'] = fw
            params['inittraj_pckl'] = pickle.dumps(newsurf)
            params['adsorbates_json'] = json.dumps(ads)
            job = jobs.Job(params)
            if job.new():
                viz.view(newsurf)
                question = 'Does this structure look right?\n' + abbreviateDict(
                    params)
                if ask(question):
                    job.check()
                    job.submit()
        misc.launch()
예제 #25
0
def wan(calc):
    centers = [([0.125, 0.125, 0.125], 0, 1.5),
               ([0.125, 0.625, 0.125], 0, 1.5),
               ([0.125, 0.125, 0.625], 0, 1.5),
               ([0.625, 0.125, 0.125], 0, 1.5)]
    w = Wannier(4, calc,
                nbands=4,
                verbose=False,
                initialwannier=centers)
    w.localize()
    x = w.get_functional_value()
    centers = (w.get_centers(1) * k) % 1
    c = (centers - 0.125) * 2
    #print w.get_radii()  # broken! XXX
    assert abs(c.round() - c).max() < 0.03
    c = c.round().astype(int).tolist()
    c.sort()
    assert c == [[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]]
    if 0:
        from ase.visualize import view
        from ase import Atoms
        watoms = calc.atoms + Atoms(symbols='X4',
                                    scaled_positions=centers,
                                    cell=calc.atoms.cell)
        view(watoms)
    return x
예제 #26
0
def hilighter(event):
    # if we did not hit a node, bail
    if not hasattr(event, 'nodes') or not event.nodes:
        return

    # pull out the graph,
    graph = event.artist.graph

    # clear any non-default color on nodes
    for node, attributes in graph.nodes.data():
        attributes.pop('color', None)

    for u, v, attributes in graph.edges.data():
        attributes.pop('width', None)

    for node in event.nodes:
        graph.nodes[node]['color'] = 'C1'
        #print(node)

        for edge_attribute in graph[node].values():
            edge_attribute['width'] = 3

    # update the screen
    event.artist.stale = True
    event.artist.figure.canvas.draw_idle()
    print(event.nodes)

    simulation_id = event.nodes[0]
    simulation = simulations[str(simulation_id)]
    pp(simulation)
    print("simulation id", simulation_id)
    atoms = atoms_dict_to_ase(simulation["atoms"])
    view(atoms)
예제 #27
0
def test_diag_symmetries():
    total_path = os.path.dirname(os.path.abspath(__file__))
    os.chdir(total_path)

    # Diagonalize the dynamical matrix in the supercell
    dyn = CC.Phonons.Phonons("../TestDiagonalizeSupercell/prova", 4)
    w, p = dyn.DiagonalizeSupercell()

    view(dyn.structure.get_ase_atoms())

    # Get the symmetries
    supercell_s = dyn.structure.generate_supercell(dyn.GetSupercell())
    spglib_syms = spglib.get_symmetry(dyn.structure.get_ase_atoms())
    syms = CC.symmetries.GetSymmetriesFromSPGLIB(spglib_syms)

    # Get the symmetries on the polarization vectors
    pols_syms = CC.symmetries.GetSymmetriesOnModes(syms, supercell_s, p)

    # Now complete the diagonalization of the polarization vectors
    # To fully exploit symmetries
    new_pols, syms_character = CC.symmetries.get_diagonal_symmetry_polarization_vectors(p, w, pols_syms)

    # TODO: Test if these new polarization vectors really rebuild the dynamical matrix

    # write the symmetry character
    n_modes, n_syms = syms_character.shape

    for i in range(n_modes):
        print("Mode {} | ".format(i), np.angle(syms_character[i,:], deg = True))
예제 #28
0
def show_stable(ids):
    atoms = []
    db = connect(sa_db)
    for i in ids:
        atoms.append(db.get(id=int(i)).toatoms())

    view(atoms)
예제 #29
0
    def test_cap_atom(self):
        with self.subTest(msg="test hydrogen capping"):
            iz = Zeolite(
                Atoms('OSiOSi',
                      positions=[[0, 0, 0], [0, 0, -1], [0, 0, 1], [1, 1, 1]]))
            iz = iz.delete_atoms(2)  # delete Si
            iz = iz.cap_atoms()
            x = 0
            # self.assertEqual(len(iz), 3)
            for atom in iz:
                if atom.symbol == "H":
                    pass
                    # self.assertTrue(np.all(atom.position == np.array([0, 0, 1])))
                if atom.symbol == "O":
                    pass
                    # self.assertTrue(np.all(atom.position == np.array([0, 0, -1])))

        with self.subTest('oxygen and hydrogen capping'):
            cha = Zeolite.make('CHA')
            cha = cha.delete_atoms([i for i in range(0, 10)])
            for atom in cha:
                if atom.symbol == 'O':
                    atom.symbol = 'Po'

            cha = cha.cap_atoms()
            view(cha)
예제 #30
0
    def plot(self, out_folder='.', unit_cell='POSCAR', code_name='vasp'):
        try:
            from ase.io.trajectory import Trajectory
            from ase.io import read, iread
            from ase.visualize import view
        except ImportError:
            raise ImportError(
                "\nThe parent directory of ase package must be included in 'sys.path'"
            )

        if code_name == 'espresso':
            code_name = 'espresso-in'  # aims, espresso-in, vasp

        atom = read(unit_cell, format=code_name)
        _current_position_true = atom.positions.copy()[
            self.process.unit_cell.atom_true]
        _mass_weight = self.process.unit_cell.mass_true.reshape(
            (-1, 3)) / self.process.unit_cell.mass_true.max()
        for mode_ind in self.mode_inds:
            traj = Trajectory(
                out_folder + "/Trajectory_{0}.traj".format(mode_ind), 'w')
            for ind, x in enumerate(
                    np.linspace(0, 2 * np.pi, self.num_images, endpoint=False),
                    1):
                atom.positions[self.process.unit_cell.atom_true] = _current_position_true \
                    + np.sin(x) * self.mode[mode_ind, :].reshape((-1, 3)).real / np.sqrt(_mass_weight)
                traj.write(atom)
            traj.close()
            atoms = iread(out_folder + "/Trajectory_{0}.traj".format(mode_ind))
            view(atoms)
예제 #31
0
def main():
    database = "aluminum.db"
    # Parse parameters from the database
    con = sqdb.connect(database)
    cur = con.cursor()
    cur.execute(
        "SELECT VIEW,CUTOFF,KPTS,LATTICEPARAM,_rowid_,STRUCTURE FROM PARAMS WHERE STATUS=?",
        ("RUN", ))
    jobs = cur.fetchall()
    con.close()
    print(jobs)

    for job in jobs:
        stamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        structure = job[5]
        a = job[3]
        show = job[0]
        b = a / 2.0

        if (structure == "FCC"):
            bulk = Atoms("Al",
                         cell=[[0, b, b], [b, 0, b], [b, b, 0]],
                         pbc=True)
        elif (structure == "BCC"):
            bulk = Atoms("Al",
                         cell=[[b, b, b], [b, b, -b], [b, -b, b]],
                         pbc=True)
        else:
            print("Unknown lattice type")
            continue

        if (show == 1):
            view(bulk)

        calcfile = "data/alum" + structure + stamp + ".txt"
        cutoff = job[1]
        k = job[2]
        calc = gp.GPAW(mode=gp.PW(cutoff),
                       kpts=(k, k, k),
                       txt=calcfile,
                       xc="LDA")

        bulk.set_calculator(calc)
        energy = bulk.get_potential_energy()

        gpwfile = "data/alum" + structure + stamp + ".gpw"
        calc.write(gpwfile)

        # Update the database
        aseDB = db.connect(database)
        lastID = aseDB.write(bulk)

        con = sqdb.connect(database)
        cur = con.cursor()
        row = int(job[4])
        cur.execute(
            "UPDATE PARAMS SET GPWFILE=?,TXTFILE=?,STATUS=?,ID=? WHERE _rowid_=?",
            (gpwfile, calcfile, "FINISHED", lastID, row))
        con.commit()
        con.close()
예제 #32
0
def main(argv):
    fname = argv[0]
    with open(fname, 'r') as infile:
        data = json.load(infile)

    pickle_name = fname.split(".")[0] + ".pkl"
    pickle_name = "data/bc_10x10x10_linvib.pkl"
    with open(pickle_name, 'rb') as infile:
        bc, cf, eci = pck.load(infile)

    # Plot heat capacities
    gr_spec = {"hspace": 0.0}
    fig, ax = plt.subplots(nrows=2, sharex=True, gridspec_kw=gr_spec)
    colors = [
        '#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c',
        '#fdbf6f', '#ff7f00', '#cab2d6'
    ]
    counter = 0
    mu = []
    max_T = []
    max_conc = []
    for key, value in data.iteritems():
        value = sort_based_on_temp(value)
        color = colors[counter % len(colors)]
        mu.append(value["mu_c1_0"])
        U = np.array(value["energy"]) * mol / (len(bc.atoms) * kJ)
        energy_interp = UnivariateSpline(value["temperature"], U, k=3, s=1)
        ax[0].plot(value["temperature"], U, "o", mfc="none", color=color)
        T = np.linspace(np.min(value["temperature"]),
                        np.max(value["temperature"]), 500)
        ax[0].plot(T, energy_interp(T), color=color)

        singl = np.array(value["singlet_c1_0"])
        x = 0.5 * (1.0 + singl)
        ax[1].plot(value["temperature"],
                   x,
                   label="{}".format(value["mu_c1_0"]),
                   color=color,
                   marker="o",
                   mfc="none")
        counter += 1
        #indx_max = np.argmax( Cv(T) )
        #max_T.append( T[indx_max] )
        #interp_conc = UnivariateSpline( value["temperature"], x, k=3, s=1 )
        #x_interp = interp_conc(T)
        #max_conc.append( x_interp[indx_max] )

    fig.subplots_adjust(wspace=0)
    ax[1].set_xlabel("Temperature (K)")
    ax[0].set_ylabel("Internal energy (kJ/mol)")
    ax[1].set_ylabel("Al conc.")
    ax[1].legend(frameon=False)
    isochemical_potential(data, max_T, max_conc)
    #mu_T_phase_diag( mu, max_T, 200.0, 900.0 )
    print(cf)
    calc = ClusterExpansion(bc, cluster_name_eci=eci, init_cf=cf, logfile=None)
    bc.atoms.set_calculator(calc)
    view(bc.atoms)
    free_energy(data, bc, eci)
    plt.show()
예제 #33
0
def wulff(fname):
    from ase.io import read, write
    from ase.visualize import view
    from cemc.tools import WulffConstruction
    from matplotlib import pyplot as plt
    atoms = read(fname)
    atoms = extract_largest_cluster(fname)
    surface_file = fname.rpartition(".")[0] + "_onlycluster.xyz"
    wulff = WulffConstruction(cluster=atoms, max_dist_in_element=5.0)
    wulff.filter_neighbours(num_neighbours=9, elements=["Mg", "Si"], cutoff=4.5)
    write(surface_file, wulff.cluster)
    print("Cluster written to {}".format(surface_file))
    surface = wulff.surface_atoms
    view(surface)
    mesh_file = fname.rpartition(".")[0]+"_surfmesh.msh"
    # wulff.fit_harmonics(show=True, order=100, penalty=0.1)
    wulff.interface_energy_poly_expansion(order=12, show=True, spg=225, 
                                          average_cutoff=20.0, penalty=0.1)
    wulff.save_surface_mesh(mesh_file)
    ref_dir = [0.57735027, 0.57735027, -0.57735027]
    gamma = 86.37379010832926/2.0
    theta = np.arccos(ref_dir[2])
    phi = np.arctan2(ref_dir[1], ref_dir[0])
    value = wulff.eval(theta, phi)
    wulff.wulff_plot(show=True, n_angles=60)
    wulff.path_plot(path=[90, 45], normalization=gamma/value)
    wulff.wulff_plot_plane(tol=5.0)
    plt.show()
예제 #34
0
def test(size, R, nk):

    
    atoms_flat  =   get_square_uCell(size)
    
    view(atoms_flat)
    
    # CALCULATOR FLAT
    calc_f      =   Hotbit(SCC=False, kpts=(nk,nk,1),  \
                           txt= path + 'test_consistency/optimization_flat.cal')
    atoms_flat.set_calculator(calc_f)
    
    opt_f       =   BFGS(atoms_flat)
    opt_f.run(fmax = 0.05)
    e_flat      =   atoms_flat.get_potential_energy()
    

    
    
    atoms_c     =   atoms_flat.copy()
    
    L           =   atoms_c.get_cell().diagonal()
     
    atoms_c.set_cell(L) 
    angle       =   L[1]/R
    atoms_c.rotate('y', np.pi/2)
    atoms_c.translate((-atoms_c[0].x, 0, 0) )
    
    for a in atoms_c:
        r0      =   a.position
        phi     =   r0[1]/L[1]*angle
        a.position[0]   =   R*np.cos(phi)
        a.position[1]   =   R*np.sin(phi)
    
    
    atoms_c       =   Atoms(atoms = atoms_c, container = 'Wedge')
    atoms_c.set_container(angle = angle, height = L[0], physical = False, pbcz = True)
    
    if R < 100:
        view(atoms_c.extended_copy((8,1,3)))
    
    # CALCULATOR Cyl
    calc_c      =   Hotbit(SCC=False, kpts=(nk,1, nk), physical_k = False, \
                           txt= path + 'test_consistency/optimization_cyl.cal')
    atoms_c.set_calculator(calc_c)
    
    opt_c       =   BFGS(atoms_c)
    opt_c.run(fmax = 0.05)
    
    
    e_cyl       =   atoms_c.get_potential_energy()

    print 'R = %.2f' %R
    print 'energy flat     = %.6f' %e_flat
    print 'energy cylinder = %.6f' %e_cyl
    print 'energy dif (e_cylinder - eflat)/nAtoms  = %.6f \n' %(-(e_flat - e_cyl)/len(atoms_flat))
    
    return e_flat, e_cyl, len(atoms_flat)
예제 #35
0
    def view(self, index=None):
        """Visualize the calculation.

        """
        from ase.visualize import view
        if index is not None:
            return view(self.traj[index])
        else:
            return view(self.traj)
예제 #36
0
def gui_view():
        horizontal_dimension = int(horizon_sheet_variable.get())
        vertical_dimension = int(vertical_sheet_variable.get())
        symmetry_int = int(symmetry_var.get())
        atoms = build_sheet(horizontal_dimension, vertical_dimension, symmetry=symmetry_int)
        unsat_int = int(unsat_var.get())
        if unsat_int==0:
            daves_super_saturate(atoms)
        elif unsat_int==1:
            pass
        view(atoms, viewer="avogadro")
예제 #37
0
파일: utils.py 프로젝트: devonwa/twodee
def bp(info=None):
    """A breakpoint to view something and stop the rest of the script."""
    if isinstance(info, Atoms):
        view(info)    
    elif isinstance(info, list) and info:
        if all(isinstance(i, Atoms) for i in info):
            view(info)
        else:
            print(info)
    elif info is not None:
        print(info)

    sys.exit()
예제 #38
0
def hyster_study(edge, folder = None):

    if folder == None:  folder  =   os.getcwd()
        
    print folder
    for fileC in os.listdir(folder):
        if fileC[-6:] == '.simul':
            fileC       =   folder + fileC
            _, length, _, _, v, T, dt, fric, dtheta, \
            thresZ, interval, deltaY, theta, M, edge   =   read_simul_params_file(fileC)
            mdfile      =   fileC[:-6] + '.traj'
            traj        =   PickleTrajectory(mdfile, 'r')
            atoms_init  =   traj[0]
            
            
            constraints, _, twist, rend_b, rend_t  =   get_constraints(atoms_init, edge, \
                                                                   bond, None, key = 'twist_p')
            
            #constraints, _, rend_b, rend_t     =   get_constraints(atoms_init, edge, \
            #                                                       bond, None, key = 'twist_p')
            atoms       =   traj[-1]
            atoms.set_constraint(constraints)
            
            
            
            vels        =   (traj[-2].positions - traj[-1].positions) / (interval * dt)
            atoms.set_velocities(vels)
            
            calc        =   LAMMPS(parameters=get_lammps_params()) 
            atoms.set_calculator(calc)
            
            view(atoms)
            dyn         =   Langevin(atoms, dt*units.fs, T*units.kB, fric)
            twist.set_angle(theta)
            dyn.run(10 * interval)
            view(atoms)
            
            traj_new=   PickleTrajectory(fileC[:-6] + '_hyst.traj', 'w', atoms)
            mdlogf  =   fileC[:-6] + '_hyst.log'
            
            
            
            do_dynamics(mdlogf, atoms, dyn, rend_b, rend_t, v, dt, deltaY, \
                        theta, dtheta, length, thresZ, \
                        interval, traj_new, M, twist)
            
            mdhystf =   fileC[:-6] + '_hyst.traj'
            logfile =   fileC[:-6] + '.log'
            
            append_files(logfile, mdlogf, logfile[:-4] + '_comp.log')
            call(['ase-gui', mdfile, mdhystf, '-o', logfile[:-4] + '_comp.traj'])            
예제 #39
0
파일: task.py 프로젝트: hess8/pythonscripts
    def run(self, names):
        """Run task far all names.

        The task will be one of these four:

        * Open ASE's GUI
        * Write configuration to file
        * Write summary
        * Do the actual calculation
        """

        names = self.expand(names)
        names = names[self.slice]
        names = self.exclude(names)

        if self.gui:
            for name in names:
                view(self.create_system(name))
            return

        if self.write_to_file:
            if self.write_to_file[0] == ".":
                for name in names:
                    filename = self.get_filename(name, self.write_to_file)
                    write(filename, self.create_system(name))
            else:
                assert len(names) == 1
                write(self.write_to_file, self.create_system(names[0]))
            return

        if self.write_summary:
            self.read(names)
            self.analyse()
            self.summarize(names)
            return

        atoms = None
        for name in names:
            if self.use_lock_files:
                lockfilename = self.get_filename(name, ".json")
                fd = opencew(lockfilename)
                if fd is None:
                    self.log("Skipping", name)
                    continue
                fd.close()
            atoms = self.run_single(name)

        return atoms
예제 #40
0
파일: neb.py 프로젝트: jkitchin/vasp
def plot_neb(self, show=True):
    """Return a list of the energies and atoms objects for each image in

    the band.

    by default shows the plot figure
    """
    images, energies = self.get_neb()
    # add fitted line to band energies. we make a cubic spline
    # interpolating function of the negative energy so we can find the
    # minimum which corresponds to the barrier
    from scipy.interpolate import interp1d
    from scipy.optimize import fmin
    f = interp1d(range(len(energies)),
                 -energies,
                 kind='cubic', bounds_error=False)
    x0 = len(energies) / 2.  # guess barrier is at half way
    xmax = fmin(f, x0)

    xfit = np.linspace(0, len(energies) - 1)
    bandfit = -f(xfit)

    import matplotlib.pyplot as plt
    p = plt.plot(energies - energies[0], 'bo ', label='images')
    plt.plot(xfit, bandfit, 'r-', label='fit')
    plt.plot(xmax, -f(xmax), '* ', label='max')
    plt.xlabel('Image')
    plt.ylabel('Energy (eV)')
    s = ['$\Delta E$ = {0:1.3f} eV'.format(float(energies[-1]
                                                 - energies[0])),
         '$E^\ddag$ = {0:1.3f} eV'.format(float(-f(xmax)))]

    plt.title('\n'.join(s))
    plt.legend(loc='best', numpoints=1)
    if show:
        from ase.calculators.singlepoint import SinglePointCalculator
        from ase.visualize import view
        # It seems there might be some info on the atoms that causes
        # an error here. Making a copy seems to get rid of the
        # issue. Hacky.
        tatoms = [x.copy() for x in images]
        for i, x in enumerate(tatoms):
            x.set_calculator(SinglePointCalculator(x, energy=energies[i]))
        view(tatoms)
        plt.show()
    return p
예제 #41
0
def plot_fig1():
    
    mdfile  =   '/space/tohekorh/ShearSlide/files/LJ_10/ac_twistTaito/w=7/md_L=24_v=0.20_00.traj'
    #mdfile  =   '/space/tohekorh/ShearSlide/files/KC_10/ac_stickTaito/w=7/r=20/md_L=145_stL=27_00.traj'
    
    traj    =   PickleTrajectory(mdfile)
    
    z_init  =   np.average(traj[0].positions[:,2])
    xrange  =   [np.min(traj[0].positions[:,0]), np.max(traj[0].positions[:,0])]
    yrange  =   [np.min(traj[0].positions[:,1]), np.max(traj[0].positions[:,1])]
    
    from ase.structure import graphene_nanoribbon
    from ase.visualize import view
    from ase import Atoms
    base    =   graphene_nanoribbon(70, 50, type='armchair', saturated=False,
                                    C_C=bond, main_element='N')
    
    base.rotate([1,0,0], np.pi/2)
    base.positions[:,2]     =   z_init - 3.8 
    atoms_v =   Atoms()
    n       =   int(len(traj)/1.3)
    #n       =   
    
    nsnap   =   3
    
    atoms_use   =   [traj[i] for i in np.array(range(nsnap))*n/nsnap]
    
    for i, atoms in enumerate(atoms_use):
        
        atoms.positions[:,1] = -atoms.positions[:,1] - i*20 
        #atoms.positions[:,0] = -atoms.positions[:,0] 
        
        atoms_v +=  atoms
    
    cent_atoms  =   np.array([np.average(atoms_v.positions[:,0]), np.average(atoms_v.positions[:,1]), 0])
    cent_base   =   np.array([np.average(base.positions[:,0]), np.average(base.positions[:,1]), 0])
    base.translate(cent_atoms - cent_base)
        
    #atoms_v +=  base
    view(atoms_v, viewer = 'vmd')
예제 #42
0
    def run(args, parser):
        if args.vacuum0:
            parser.error('Please use -V or --vacuum instead!')

        if '.' in args.name:
            # Read from file:
            atoms = read(args.name)
        elif args.crystal_structure:
            atoms = build_bulk(args)
        else:
            atoms = build_molecule(args)

        if args.magnetic_moment:
            magmoms = np.array(
                [float(m) for m in args.magnetic_moment.split(',')])
            atoms.set_initial_magnetic_moments(
                np.tile(magmoms, len(atoms) // len(magmoms)))

        if args.modify:
            exec(args.modify, {'atoms': atoms})

        if args.repeat is not None:
            r = args.repeat.split(',')
            if len(r) == 1:
                r = 3 * r
            atoms = atoms.repeat([int(c) for c in r])

        if args.gui:
            view(atoms)

        if args.output:
            write(args.output, atoms)
        elif sys.stdout.isatty():
            write(args.name + '.json', atoms)
        else:
            con = connect(sys.stdout, type='json')
            con.write(atoms, name=args.name)
예제 #43
0
    # initial approximation:
    n = int(mc.L/2)
    # hollow core-shell initial structure
    s = 4
    mc.GRID[(n-s):(n+s), (n-s):(n+s), (n-s):(n+s)] = mc.chems[0]
    s = 3
    mc.GRID[(n-s):(n+s), (n-s):(n+s), (n-s):(n+s)] = mc.chems[1] # mc.chems[0]
    s = 2
    mc.GRID[(n-s):(n+s), (n-s):(n+s), (n-s):(n+s)] = mc.chems[1] # 0
    if True: # test move change 13
        print('Test MoveChange13')
        move = MoveChange13()
        move.setup(mc.GRID, n, n, n, mc.chems[0])
        move()
        from ase.visualize import view
        view(mc.get_atoms())
        raw_input('Press enter')
        print('Test reject')
        move.reject()
        view(mc.get_atoms())
        raw_input('Press enter')

    target_CN = np.zeros(4)
    target_CN[0] = 2.8  # Cu-Cu
    target_CN[1] = 4.0  # Pt-Cu
    target_CN[2] = 1.8  # Cu-Pt
    target_CN[3] = 6.2  # Pt-Pt
    #i = 0
    #for B in mc.chems:
    #    for A in mc.chems:
    #        print('CN [',A,'-',B,'] = ', target_CN[i])
예제 #44
0
from __future__ import print_function
from ase.visualize import view
from ase.constraints import FixAtoms
from ase.optimize import QuasiNewton
from ase.lattice.surface import fcc100, add_adsorbate
from gpaw import GPAW, PW

# Initial state:
# 2x2-Al(001) surface with 1 layer and an
# Au atom adsorbed in a hollow site:
slab = fcc100('Al', size=(2, 2, 2))
slab.center(axis=2, vacuum=3.0)
add_adsorbate(slab, 'Au', 1.6, 'hollow')

# Make sure the structure is correct:
view(slab)

# Fix the Al atoms:
mask = [atom.symbol == 'Al' for atom in slab]
print(mask)
fixlayer = FixAtoms(mask=mask)
slab.set_constraint(fixlayer)

# Use GPAW:
calc = GPAW(mode=PW(200), kpts=(2, 2, 1), xc='PBE', txt='hollow.txt')
slab.set_calculator(calc)

qn = QuasiNewton(slab, trajectory='hollow.traj')

# Find optimal height.  The stopping criterion is: the force on the
# Au atom should be less than 0.05 eV/Ang
예제 #45
0
파일: step0.py 프로젝트: impurity80/ase
cell = [[1,0,0],[0,1,0],[0,0,1]]
atoms = BodyCenteredCubic('Fe', directions=cell)
atoms.set_initial_magnetic_moments([5,5])
atoms.set_cell([a, a, a], scale_atoms=True)

carbon = Atom('C', position=(0,0.5*a,0.75*a), charge=0.4)
atoms = atoms*(2,2,2) + carbon

constraint = FixAtoms(indices=[3,5,7,8,10,11,12,13,14,15,16])

atoms.set_constraint(constraint)

atoms[-1].position = [0, 0.5*a, 0.25*a]
init = atoms.copy()
view(init)

atoms[-1].position = [0, 0.5*a, 0.75*a]
final = atoms.copy()
view(final)

def save( filename, arg ):
    f = open(filename, 'a+t')
    f.write('{0} \n'.format(arg))
    f.close()

os.system('mkdir result')

print atoms.get_cell()

예제 #46
0
mol = atoms[mask]
del atoms[mask]
mol.cell[0:2, ] = mol.cell[0:2, ]*1/3.0
mol.cell[2][2] = 3
mol[-1].z = mol[-3].z
mol[-1].position = mol[-1].position + mol.cell[0]/6 + mol.cell[1]/6
mol.translate([0, 0, -mol[1].z])
mol = mol*[3, 3, 2]
mol = sortz(mol)

mol1 = mol.copy()
mol1.translate([0, 0, atoms[-1].z + 2.0])


atoms = atoms + mol1
view(atoms)

constraint = FixAtoms(mask=[atom.symbol != 'O' and atom.symbol != 'C'
                            for atom in atoms])
atoms.set_constraint(constraint)

with jasp('442-coo2-sm5',
          xc='PBE',
          encut=350,
          kpts=[1, 1, 1],
          gamma='true',
          ismear=0,
          sigma=0.1, # this is small for a molecule
          prec='normal',
          algo='fast',
          lreal='atuo',
예제 #47
0
파일: neb.py 프로젝트: rosswhitfield/ase


fmax = 0.05
nimages = 3

print([a.get_potential_energy() for a in Trajectory('H.traj')])
images = [Trajectory('H.traj')[-1]]
for i in range(nimages):
    images.append(images[0].copy())
images[-1].positions[6, 1] = 2 - images[0].positions[6, 1]
neb = NEB(images)
neb.interpolate()
if 0:  # verify that initial images make sense
    from ase.visualize import view
    view(neb.images)

for image in images:
    image.set_calculator(MorsePotential())

dyn = BFGS(neb, trajectory='mep.traj')  # , logfile='mep.log')

dyn.run(fmax=fmax)

for a in neb.images:
    print(a.positions[-1], a.get_potential_energy())

neb.climb = True
dyn.run(fmax=fmax)

# Check NEB tools.
예제 #48
0
파일: gpawscript.py 프로젝트: qsnake/gpaw
def run(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    elif isinstance(argv, str):
        argv = argv.split()
        
    parser = build_parser()
    opt, args = parser.parse_args(argv)
    
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    name = args[0]

    if world.rank == 0:
        out = sys.stdout#open('%s-%s.results' % (name, opt.identifier), 'w')
    else:
        out = devnull

    a = None
    try:
        symbols = string2symbols(name)
    except ValueError:
        # name was not a chemical formula - must be a file name:
        atoms = read(name)
    else:
        if opt.crystal_structure:
            a = opt.lattice_constant
            if a is None:
                a = estimate_lattice_constant(name, opt.crystal_structure,
                                              opt.c_over_a)
                out.write('Using an estimated lattice constant of %.3f Ang\n' %
                          a)

            atoms = bulk(name, opt.crystal_structure, a, covera=opt.c_over_a,
                         orthorhombic=opt.orthorhombic, cubic=opt.cubic)
        else:
            try:
                # Molecule?
                atoms = molecule(name)
            except NotImplementedError:
                if len(symbols) == 1:
                    # Atom
                    atoms = Atoms(name)
                elif len(symbols) == 2:
                    # Dimer
                    atoms = Atoms(name, positions=[(0, 0, 0),
                                                   (opt.bond_length, 0, 0)])
                else:
                    raise ValueError('Unknown molecule: ' + name)

    if opt.magnetic_moment:
        magmom = opt.magnetic_moment.split(',')
        atoms.set_initial_magnetic_moments(np.tile(magmom,
                                                   len(atoms) // len(magmom)))

    if opt.repeat is not None:
        r = opt.repeat.split(',')
        if len(r) == 1:
            r = 3 * r
        atoms = atoms.repeat([int(c) for c in r])

    if opt.gui:
        view(atoms)
        return

    if opt.write_to_file:
        write(opt.write_to_file, atoms)
        return

    if opt.effective_medium_theory:
        Runner = EMTRunner
    else:
        Runner = GPAWRunner

    if opt.fit:
        strains = np.linspace(0.98, 1.02, 5)
    else:
        strains = None

    if opt.constrain_tags:
        tags = [int(t) for t in opt.constrain_tags.split(',')]
        constrain = FixAtoms(mask=[t in tags for t in atoms.get_tags()])
        atoms.constraints = [constrain]

    runner = Runner(name, atoms, strains, tag=opt.identifier,
                    clean=not opt.read,
                    fmax=opt.relax, out=out)

    if not opt.effective_medium_theory:
        # Import stuff that eval() may need to know:
        from gpaw.wavefunctions.pw import PW
        from gpaw.occupations import FermiDirac, MethfesselPaxton
            
        if opt.parameters:
            input_parameters = eval(open(opt.parameters).read())
        else:
            input_parameters = {}
        for key in defaults:
            value = getattr(opt, key)
            if value is not None:
                try:
                    input_parameters[key] = eval(value)
                except (NameError, SyntaxError):
                    input_parameters[key] = value

        runner.set_parameters(vacuum=opt.vacuum,
                              write_gpw_file=opt.write_gpw_file,
                              **input_parameters)

    runner.run()

    runner.summary(plot=opt.plot, a0=a)

    return runner
예제 #49
0
from ase import Atoms
from ase.visualize import view
from ase.calculators.aims import Aims, AimsCube
from ase.optimize import QuasiNewton

water = Atoms('HOH', [(1,0,0), (0,0,0), (0,1,0)])

water_cube = AimsCube(points=(29,29,29),
                      plots=('total_density','delta_density',
                             'eigenstate 5','eigenstate 6'))

calc=Aims(xc='pbe',
          sc_accuracy_etot=1e-6,
          sc_accuracy_eev=1e-3,
          sc_accuracy_rho=1e-6,
          sc_accuracy_forces=1e-4,
          species_dir='/home/hanke/codes/fhi-aims/fhi-aims.workshop/species_defaults/light/',
          run_command='aims.workshop.serial.x',
          cubes=water_cube)

water.set_calculator(calc)
dynamics = QuasiNewton(water,trajectory='square_water.traj')
dynamics.run(fmax=0.01)

view(water)
예제 #50
0
import ase.build as ab
from pyramids.io.output import writeSiesta
from ase.visualize import view

atom = ab.mx2()
view(atom)
writeSiesta('structure.fdf',atom)
예제 #51
0
파일: build.py 프로젝트: rosswhitfield/ase
def main():
    parser = optparse.OptionParser(usage="%prog [options] name/input-file [output-file]")
    add = parser.add_option
    add("-M", "--magnetic-moment", metavar="M1,M2,...", help="Magnetic moment(s).  " + 'Use "-M 1" or "-M 2.3,-2.3".')
    add(
        "--modify",
        metavar="...",
        help="Modify atoms with Python statement.  " + 'Example: --modify="atoms.positions[-1,2]+=0.1".',
    )
    add(
        "-v",
        "--vacuum",
        type=float,
        default=3.0,
        help="Amount of vacuum to add around isolated atoms " "(in Angstrom).",
    )
    add("--unit-cell", help='Unit cell.  Examples: "10.0" or "9,10,11" ' + "(in Angstrom).")
    add("--bond-length", type=float, help="Bond length of dimer in Angstrom.")
    add(
        "-x",
        "--crystal-structure",
        help="Crystal structure.",
        choices=[
            "sc",
            "fcc",
            "bcc",
            "hcp",
            "diamond",
            "zincblende",
            "rocksalt",
            "cesiumchloride",
            "fluorite",
            "wurtzite",
        ],
    )
    add("-a", "--lattice-constant", default="", help="Lattice constant(s) in Angstrom.")
    add("--orthorhombic", action="store_true", help="Use orthorhombic unit cell.")
    add("--cubic", action="store_true", help="Use cubic unit cell.")
    add("-r", "--repeat", help='Repeat unit cell.  Use "-r 2" or "-r 2,3,1".')
    add("-g", "--gui", action="store_true")

    opts, args = parser.parse_args()
    if len(args) == 0 or len(args) > 2:
        parser.error("Wrong number of arguments!")

    name = args.pop(0)

    if "." in name:
        # Read from file:
        atoms = read(name)
    elif opts.crystal_structure:
        atoms = build_bulk(name, opts)
    else:
        atoms = build_molecule(name, opts)

    if opts.magnetic_moment:
        magmoms = np.array([float(m) for m in opts.magnetic_moment.split(",")])
        atoms.set_initial_magnetic_moments(np.tile(magmoms, len(atoms) // len(magmoms)))

    if opts.modify:
        exec(opts.modify, {"atoms": atoms})

    if opts.repeat is not None:
        r = opts.repeat.split(",")
        if len(r) == 1:
            r = 3 * r
        atoms = atoms.repeat([int(c) for c in r])

    if opts.gui:
        view(atoms)

    if args:
        write(args[0], atoms)
    elif sys.stdout.isatty():
        write(name + ".json", atoms)
    else:
        con = connect(sys.stdout, type="json")
        con.write(atoms, name=name)
예제 #52
0
def run_moldy(N, save = False):
    
    # 
    params      =   {'bond':bond, 'a':a, 'h':h}
    
    # DEFINE FILES
    mdfile, mdlogfile, mdrelax  =   get_fileName(N, 'tear_E_rebo+KC_v', taito, v, edge)  
    
    # GRAPHENE SLAB
    atoms               =   make_graphene_slab(a,h,width,length,N, \
                                               edge_type = edge, h_pass = True, \
                                               stacking = 'abc')[3]
    
    view(atoms)
    #exit()
    params['ncores']    =   ncores
    params['positions'] =   atoms.positions.copy() 
    params['pbc']       =   atoms.get_pbc()
    params['cell']      =   atoms.get_cell().diagonal()
    params['ia_dist']   =   10
    params['chemical_symbols']  \
                        =   atoms.get_chemical_symbols()
    
    # FIX
    constraints =   []
    print 'hii'
    left        =   get_ind(atoms.positions.copy(), 'left', 2, bond)
    top         =   get_ind(atoms.positions.copy(), 'top', fixtop - 1, left)
    rend_t      =   get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), 1, edge)
    rend        =   get_ind(atoms.positions.copy(), 'rend', atoms.get_chemical_symbols(), fixtop, edge)
    
    print rend
    print 'hoo' 
    exit()
    
    fix_left    =   FixAtoms(indices = left)
    fix_top     =   FixAtoms(indices = top)
    
    add_kc      =   KC_potential_p(params)

    
    for ind in rend:
        fix_deform  =   FixedPlane(ind, (0., 0., 1.))
        constraints.append(fix_deform)
    
    for ind in rend_t:
        fix_deform  =   FixedPlane(ind, (0., 0., 1.))
        constraints.append(fix_deform)
    
    constraints.append(fix_left)
    constraints.append(fix_top)
    constraints.append(add_kc)
    # END FIX
    
    # CALCULATOR LAMMPS 
    parameters = {'pair_style':'rebo',
                  'pair_coeff':['* * CH.airebo C H'],
                  'mass'      :['1 12.0', '2 1.0'],
                  'units'     :'metal', 
                  'boundary'  :'f p f'}
    
    calc    =   LAMMPS(parameters=parameters) 
    atoms.set_calculator(calc)
    # END CALCULATOR
    
    #view(atoms)
    
    # TRAJECTORY
    if save:    traj    =   PickleTrajectory(mdfile, 'w', atoms)
    else:       traj    =   None
    
    #data    =   np.zeros((M/interval, 5))
    
    # RELAX
    atoms.set_constraint(add_kc)
    dyn     =   BFGS(atoms, trajectory = mdrelax)
    dyn.run(fmax=0.05)
    
    # FIX AFTER RELAXATION
    atoms.set_constraint(constraints)
    
    # DYNAMICS
    dyn     =   Langevin(atoms, dt*units.fs, T*units.kB, fric)
    n       =   0
    header  =   '#t [fs], d [Angstrom], epot_tot [eV], ekin_tot [eV], etot_tot [eV] \n'
    log_f   =   open(mdlogfile, 'w')
    log_f.write(header)            
    log_f.close()

    if T != 0:
        # put initial MaxwellBoltzmann velocity distribution
        mbd(atoms, T*units.kB)
    
    
    print 'Start the dynamics for N = %i' %N
    
    for i in range(0, M):
        
        if T == 0:
            for ind in rend:
                atoms[ind].position[2] -= dz 
        elif T != 0:
            if tau < i*dt:
                hw   =   i*dz
                for ind in rend:
                    atoms[ind].position[2] -= dz 
            
        dyn.run(1)
        
        if i%interval == 0:

            epot, ekin  =   saveAndPrint(atoms, traj, False)[:2]
            
            if T != 0:
                if tau < i*dt:  hw   =   i*dz - tau*v
                else: hw =   0
            else:   hw = i*dz
                
            data        =   [i*dt, hw, epot, ekin, epot + ekin]
            
            if save:
                log_f   =   open(mdlogfile, 'a')
                stringi =   ''
                for k,d in enumerate(data):
                    if k == 0:           
                        stringi += '%.2f ' %d
                    elif k == 1:
                        stringi += '%.6f ' %d
                    else:
                        stringi += '%.12f ' %d
                
                log_f.write(stringi +  '\n')
                log_f.close()
                  

            n += 1
        
        
        if save and T != 0 and i*dt == tau:
            log_f   =   open(mdlogfile, 'a')
            log_f.write('# Thermalization complete. ' +  '\n')
            log_f.close()
            
            
        if 1e2 <= M:    
            if i%(int(M/100)) == 0: print 'ready = %.1f' %(i/(int(M/100))) + '%' 
예제 #53
0
파일: test_nuts.py 프로젝트: s-dale/pyIID
    def check_nuts(self, value):
        """
        Test NUTS simulation

        Parameters
        ----------
        value: list or tuple
            The values to use in the tests
        """
        print(self.traj_file)
        ideal_atoms, _ = value[0]
        ideal_atoms.set_velocities(np.zeros((len(ideal_atoms), 3)))
        s = ElasticScatter(verbose=True)
        if value[1] == 'PDF':
            target_data = s.get_pdf(ideal_atoms)
            exp_func = s.get_pdf
            exp_grad = s.get_grad_pdf
            calc = Calc1D(target_data=target_data,
                          exp_function=exp_func, exp_grad_function=exp_grad,
                          potential='rw', conv=30)
        elif value[1] == 'FQ':
            target_data = s.get_pdf(ideal_atoms)
            exp_func = s.get_pdf
            exp_grad = s.get_grad_pdf
            calc = Calc1D(target_data=target_data,
                          exp_function=exp_func, exp_grad_function=exp_grad,
                          potential='rw', conv=30)
        else:
            calc = value[1]
        ideal_atoms.positions *= 1.02

        ideal_atoms.set_calculator(calc)
        start_pe = ideal_atoms.get_potential_energy()

        if value[2]:
            traj_name = self.traj_file.name
        else:
            traj_name = None
        nuts = NUTSCanonicalEnsemble(ideal_atoms, escape_level=4, verbose=True,
                                     seed=seed, trajectory=traj_name)
        traj, metadata = nuts.run(5)
        print(traj[0].get_momenta())
        pe_list = []
        for atoms in traj:
            pe_list.append(atoms.get_potential_energy())
        min_pe = np.min(pe_list)

        print(len(traj))
        print(min_pe, start_pe)

        if start_pe != 0.0:
            if not min_pe < start_pe:
                view(traj)
            assert min_pe < start_pe

        self.traj_file.close()
        if value[2]:
            assert os.path.exists(self.traj_file.name)
            read_traj = TrajectoryReader(self.traj_file.name)
            print(len(traj), len(read_traj))
            assert len(traj) == len(read_traj)
            for i, (atoms1, atoms2) in enumerate(zip(read_traj, traj)):
                for att in ['get_positions', 'get_potential_energy',
                            'get_forces', 'get_momenta']:
                    print(i, att)
                    assert_allclose(*[getattr(a, att)() for a in [atoms1, atoms2]])
        del traj
예제 #54
0
파일: app.py 프로젝트: PHOTOX/fuase
def gui(id):
    if open_ase_gui:
        atoms = connection.get_atoms(id)
        view(atoms)
    return '', 204, []
예제 #55
0
파일: task.py 프로젝트: PHOTOX/fuase
    def run(self, names=None):
        """Run task for all names.

        The task will be one of these four:

        * Open ASE's GUI
        * Write configuration to file
        * Write summary
        * Do the actual calculation
        """

        if self.lock is None:
            # Create lock object:
            self.lock = Lock(self.get_filename(ext='lock'))

        if self.clean:
            self.clean_json_file(names)
            return

        if names is None or len(names) == 0:
            names = self.collection.keys()

        names = self.expand(names)
        names = names[self.slice]
        names = self.exclude(names)

        if self.gui:
            for name in names:
                view(self.create_system(name))
            return

        if self.write_to_file:
            if self.write_to_file[0] == '.':
                for name in names:
                    filename = self.get_filename(name, self.write_to_file)
                    write(filename, self.create_system(name))
            else:
                assert len(names) == 1
                write(self.write_to_file, self.create_system(names[0]))
            return

        if self.write_summary:
            self.read()
            self.analyse()
            self.summarize(names)
            return

        atoms = None
        for name in names:
            if self.use_lock_files:
                try:
                    filename = self.get_filename(ext='json')
                    self.lock.acquire()
                    if os.path.isfile(filename):
                        data = read_json(filename)
                        if name not in data:
                            data[name] = {}
                            write_json(filename, data)
                        else:
                            self.log('Skipping', name)
                            continue
                    else:
                        write_json(filename, {name: {}})
                finally:
                    self.lock.release()

            if atoms is not None:
                del atoms.calc
            atoms = self.run_single(name)

        return atoms
예제 #56
0
from ase.lattice import surface
from ase.constraints import FixAtoms
from ase.calculators.vasp import Vasp
from ase.visualize import view
from ase.io import write
from ase.io import read

#sigma=0.01 for gases and edif=13-8

calc = Vasp(xc='PBE', kpts=(3,3,1), lwave=False, lcharg=False,lvtot=False, nwrite=1
            , encut=400, algo='Fast', ismear=0, sigma=0.0031, voskown=1, istart=0, nelm=400, nelmdl=-10, ediff=1e-8, ispin=2
            ,nsw=1, isif=2, ibrion=5, nfree=2, potim=0.015, ediffg=-0.05, isym=0
            ,lvdw=True, vdw_version=3
            ,lreal='Auto')

slab = read('../CONTCAR')


slab.center(vacuum=20.0,axis=2)

view(slab) # View the slab, frozen atoms will be marked with a "X"


#slab.set_calculator(calc)

calc.initialize(slab)
calc.write_incar(slab)
calc.write_potcar()
calc.write_kpoints()
write('POSCAR', calc.atoms_sorted)  # this will write a "sorted" POSCAR
예제 #57
0
파일: neb2.py 프로젝트: misdoro/python-ase
a = 4.0614
b = a / sqrt(2)
h = b / 2
initial = Atoms('Al2',
                positions=[(0, 0, 0),
                           (a / 2, b / 2, -h)],
                cell=(a, b, 2 * h),
                pbc=(1, 1, 0))
initial *= (2, 2, 2)
initial.append(Atom('Al', (a / 2, b / 2, 3 * h)))
initial.center(vacuum=4.0, axis=2)

final = initial.copy()
final.positions[-1, 0] += a

view([initial, final])

# Construct a list of images:
images = [initial]
for i in range(5):
    images.append(initial.copy())
images.append(final)

# Make a mask of zeros and ones that select fixed atoms (the
# two bottom layers):
mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h
constraint = FixAtoms(mask=mask)
print(mask)

for image in images:
    # Let all images use an EMT calculator:
예제 #58
0
from ase.optimize import QuasiNewton, BFGS
from ase.visualize import view

# http://jcp.aip.org/resource/1/jcpsa6/v97/i10/p7507_s1
doo = 2.74
doht = 0.957
doh = 0.977
angle = radians(104.5)
initial = Atoms('HOHOH',
                positions=[(-sin(angle) * doht, 0., cos(angle) * doht),
                           (0., 0., 0.),
                           (0., 0., doh),
                           (0., 0., doo),
                           (sin(angle) * doht, 0., doo - cos(angle) * doht)])
if 0:
    view(initial)

final = Atoms('HOHOH',
              positions=[(-sin(angle) * doht, 0., cos(angle) * doht),
                         (0., 0., 0.),
                         (0., 0., doo - doh),
                         (0., 0., doo),
                         (sin(angle) * doht, 0., doo - cos(angle) * doht)])
if 0:
    view(final)

# Make band:
images = [initial.copy()]
for i in range(3):
    images.append(initial.copy())
images.append(final.copy())
예제 #59
0
파일: Gas.py 프로젝트: JLans/ASE_Scripts
from ase.optimize import LBFGS
from ase.calculators.vasp import Vasp
from ase.io.vasp import write_vasp
from ase.visualize import view
from ase.io import write

calc = Vasp(xc='PBE', kpts=(1,1,1), nwrite=1, lwave=False, lcharg=False,lvtot=False
            , encut=400, algo='Fast', ismear=0, sigma=0.003, voskown=1, istart=0, nelm=400, nelmdl=-10, ediff=1e-6, ispin=2
            ,nsw=1000, isif=2, ibrion=1, nfree=2, potim=0.2,lvdw=True, vdw_version=3
            ,isym=0
            ,lreal='Auto')

# Create a c(2x2) surface with 4 layers and 14 Angstrom of vacuum
d=0.9575
t = np.pi/180*104.51
molecule = Atoms('H2O',
              positions=[(d, 0, 0),(d * np.cos(t), d * np.sin(t), 0),(0, 0, 0)])

molecule.center(vacuum=20.0)
view(molecule) # View the slab, frozen atoms will be marked with a "X"


#slab.set_calculator(calc)

calc.initialize(molecule)
calc.write_incar(molecule)
calc.write_potcar()
calc.write_kpoints()
write('POSCAR', calc.atoms_sorted)  # this will write a "sorted" POSCAR