Beispiel #1
0
    def __init__(self, atoms, kpts=(1,1,1), run_type=None, input_data={},
                 xc='PBE', command=None, tprnfor=True, tstress=True, **kwargs):
        if command is None:
            command = 'mpirun -np $NCORES pw.x -in PREFIX.pwi > PREFIX.pwo'

        gbrv_pp = {}
        ppdir = os.environ['ESPRESSO_PSEUDO']
        sym = list(set(atoms.get_chemical_symbols()))

        for s in sym:
            for f in os.listdir(ppdir):
                keys = f.split('_')
                if keys[0] == s.lower() and keys[1] == xc.lower():
                    gbrv_pp[s] = f

        indat = {'control':{'disk_io': 'none',
                            'restart_mode': 'from_scratch'},
                 'system':{'ecutwfc': 40.,
                           'ecutrho': 200.,
                           'input_dft': xc,
                           'occupations': 'smearing',
                           'smearing': 'gaussian',
                           'degauss': 0.001},
                 'electrons':{'electron_maxstep': 250,
                              'scf_must_converge': False,
                              'mixing_beta': 0.1,
                              'conv_thr': 1e-7},
                 }

        indat.update(input_data)
        Espresso.__init__(self, kpts=kpts, pseudopotentials=gbrv_pp,
                          input_data=indat, tprnfor=tprnfor, tstress=tstress,
                          **kwargs)
        self.command = command
def espresso_calculator(element):
    """
    Preprocessor to generate input scrit file for Quantum Espresso code

    Returns the ESPRESSO calculator object
    """
    pseudopotentials = {
        'Ar': 'ar_pbe.UPF',
        'Cu': 'cu_pbe.UPF',
        'Li': 'li_pbe.UPF',
        'N': 'n_pbe.UPF'
    }

    espresso_settings = {
        'pseudo_dir': './',
        'input_dft': 'RVV10',
        'prefix': f'{element}',
        'electron_maxstep': 100000,
        'tstress': False,
        'tprnfor': False,
        'verbosity': 'low',
        'occupations': 'smearing',
        'degauss': 0.05,
        'nspin': 2,
        'starting_magnetization': 1,
        'smearing': 'marzari-vanderbilt',
        'ecutwfc': 100
    }
    espresso_calculator = Espresso(restart=None,
                                   pseudopotentials=pseudopotentials,
                                   input_data=espresso_settings)

    return espresso_calculator
def calculate_target_repulsion(atoms, rc):
    N = len(atoms)
    pos = atoms.get_positions()
    sym = atoms.get_chemical_symbols()

    esp = 0.0
    for sp in sym:
        espc = subprocess.getoutput(
            "awk '{if($1==\"" + str(sp) +
            "\"){print $2}}' energy_data_for_isolated_atom_references"
        )  #python3
        esp += float(espc)

    # First perform a regular SCF run
    gbrv_pp = {}
    ppdir = os.environ['ESPRESSO_PSEUDO']
    sym = list(set(atoms.get_chemical_symbols()))

    for s in sym:
        for f in os.listdir(ppdir):
            keys = f.split('_')
            if keys[0] == s.lower() and keys[1] == xc.lower():
                gbrv_pp[s] = f

    calc = Espresso(
        kpts=(1, 1, 1),
        pseudopotentials=gbrv_pp,
        tstress=True,
        tprnfor=True,  # kwargs added to parameters
        input_data=input_data)
    atoms.calc = calc

    e, f = 0., np.zeros((N, 3))
    e = atoms.get_potential_energy() - esp
    print("cohesive energy [eV] = ", e)
    f = atoms.get_forces()
    powers = np.arange(6)

    #e, f = 0., np.zeros((N, 3))
    #coeff = np.array([0., 0., 0., 14., -5., 2.])
    #powers = np.arange(len(coeff))

    #for i in range(N):
    #    for j in range(N):
    #        r = atoms.get_distance(i, j)
    #        if sym[i] == sym[j] or r > rc:
    #            continue
    #        e += 0.5 * (coeff * (rc - r) ** powers).sum()
    #        dedr = -coeff[1:] * powers[1:] * (rc - r) ** (powers[1:] - 1)
    #        drdx = (pos[i] - pos[j]) / r
    #        f[i] += -dedr.sum() * drdx
    return e, f
def test_main():
    silicon = bulk('Si')
    calc = Espresso(pseudopotentials=PSEUDO, ecutwfc=50.0)
    silicon.set_calculator(calc)
    silicon.get_potential_energy()

    assert calc.get_fermi_level() is not None
    assert calc.get_ibz_k_points() is not None
    assert calc.get_eigenvalues(spin=0, kpt=0) is not None
    assert calc.get_number_of_spins() is not None
    assert calc.get_k_point_weights() is not None
Beispiel #5
0
    def calc(self, **kwargs):
        from ase.calculators.espresso import Espresso
        command = '{} -in PREFIX.pwi > PREFIX.pwo'.format(self.executable)
        pseudopotentials = {}
        for path in self.pseudo_dir.glob('*.UPF'):
            fname = path.name
            # Names are e.g. si_lda_v1.uspp.F.UPF
            symbol = fname.split('_', 1)[0].capitalize()
            pseudopotentials[symbol] = fname

        kw = self._base_kw()
        kw.update(kwargs)
        return Espresso(command=command, pseudo_dir=str(self.pseudo_dir),
                        pseudopotentials=pseudopotentials,
                        **kw)
Beispiel #6
0
def qe_calc():
    # set up executable
    label = 'scf'
    input_file = label + '.pwi'
    output_file = label + '.pwo'
    no_cpus = 1
    pw = os.environ.get('PWSCF_COMMAND')
    os.environ['ASE_ESPRESSO_COMMAND'] = f'{pw} < {input_file} > {output_file}'

    # set up input parameters
    input_data = {
        'control': {
            'prefix': label,
            'pseudo_dir': 'test_files/pseudos/',
            'outdir': './out',
            'calculation': 'scf'
        },
        'system': {
            'ibrav': 0,
            'ecutwfc': 20,
            'ecutrho': 40,
            'smearing': 'gauss',
            'degauss': 0.02,
            'occupations': 'smearing'
        },
        'electrons': {
            'conv_thr': 1.0e-02,
            'electron_maxstep': 100,
            'mixing_beta': 0.7
        }
    }

    # pseudo-potentials
    ion_pseudo = {'H': 'H.pbe-kjpaw.UPF', 'He': 'He.pbe-kjpaw_psl.1.0.0.UPF'}

    # create ASE calculator
    dft_calculator = Espresso(pseudopotentials=ion_pseudo,
                              label=label,
                              tstress=True,
                              tprnfor=True,
                              nosym=True,
                              input_data=input_data,
                              kpts=(1, 1, 1))

    yield dft_calculator
    del dft_calculator
Beispiel #7
0
def main():
    gold = bulk('Au')
    input_data = {
        'system': {
            'occupations': 'smearing',
            'smearing': 'fermi-dirac',
            'degauss': 0.02
        }
    }
    calc = Espresso(pseudopotentials=PSEUDO, input_data=input_data)
    gold.set_calculator(calc)
    gold.get_potential_energy()

    assert calc.get_fermi_level() is not None
    assert calc.get_ibz_k_points() is not None
    assert calc.get_eigenvalues(spin=0, kpt=0) is not None
    assert calc.get_number_of_spins() is not None
    assert calc.get_k_point_weights() is not None
eV2Ry = 0.073498618

#| - QE Calculator
pseudopotentials = {
    "C": "C.UPF",
    "Fe": "Fe.UPF",
    "H": "H.UPF",
}

calc = Espresso(
    kpts=(3, 3, 3),
    ecutwfc=400 * eV2Ry,

    # 'smearing', 'tetrahedra', 'tetrahedra_lin', 'tetrahedra_opt', 'fixed', 'from_input',
    occupations="smearing",
    # 'gaussian', 'methfessel-paxton', 'marzari-vanderbilt', 'fermi-dirac'
    smearing="gaussian",
    degauss=0.05 * eV2Ry,
    tstress=True,
    tprnfor=True,
    pseudopotentials=pseudopotentials,
)
atoms.set_calculator(calc)
# __|

atoms.get_potential_energy()

# try:
#     atoms.get_forces()
#     print("Getting forces worked!!")
# except:
Beispiel #9
0
def prepare_calculator_from_namelist(namelist):
    """
    PREPARE ASE CALCULATOR
    ======================
    
    This function prepares the ASE calculator for the execution.
    It requires a namelist for the setup.
    
    Parameters
    ----------
        namelist : dict
            The parsed namelist.
    
    Returns
    -------
        ase_calc :
            The ASE calculator.
    """

    # Check if the namelist has the correct keys
    if not __CALCULATOR_HEAD__ in namelist.keys():
        raise ValueError(
            "Error, to setup a calculator the section %s must be declared." %
            __CALCULATOR_HEAD__)

    c_info = namelist[__CALCULATOR_HEAD__]
    ks = c_info.keys()

    # Check if the disable check is present
    check = True
    if __DISABLE_CHECK__ in ks:
        check = bool(c_info[__DISABLE_CHECK__])

    # Define defaults
    KPTS = (1, 1, 1)
    KOFFS = (0, 0, 0)

    # Get the keywords
    if __KPTS_HEAD__ in ks:
        KPTS = [int(x) for x in c_info[__KPTS_HEAD__]]
        if len(KPTS) != 3:
            raise ValueError("Error, %s must be a 3 dimensional list" %
                             __KPTS_HEAD__)

    if __KOFF_HEAD__ in ks:
        KOFFS = [int(x) for x in c_info[__KOFF_HEAD__]]
        if len(KOFFS) != 3:
            raise ValueError("Error, %s must be a 3 dimensional list" %
                             __KOFF_HEAD__)

    # Setup the pseudopotentials
    pseudopotentials = {}
    pseudo_keys = [x for x in ks if __PSEUDO_LIST__ in x]
    for pkey in pseudo_keys:
        pvalue = c_info[pkey]
        patom = pkey.replace(__PSEUDO_LIST__, "", 1)
        patom = patom[0].upper() + patom[1:]
        pseudopotentials[patom] = pvalue

    is_binary = False
    if __BINARY__ in ks:
        is_binary = True
        binary = c_info[__BINARY__]

    # Setup the calculator
    ase_calc = None
    tot_keys = __ALLOWED_KEYS__
    if __CALCULATOR_TYPE__ in ks:
        if not c_info[__CALCULATOR_TYPE__] in __CALCULATOR_SYNONIMOUS__.keys():
            print("List of supported calculators:",
                  __CALCULATOR_SYNONIMOUS__.keys)
            raise ValueError(
                "Error, the specified calculator '%s' is not in supported." %
                c_info[__CALCULATOR_TYPE__])

        calc = __CALCULATOR_SYNONIMOUS__[c_info[__CALCULATOR_TYPE__]]

        if calc == __CALC_QE__:
            tot_keys = __ALLOWED_KEYS__ + __QE_ALLOWED_KEYS__
            # Check all the qe allowed keys
            input_data = {}
            qe_keys = [x for x in __QE_ALLOWED_KEYS__ if x in ks]
            for x in qe_keys:
                input_data[x] = c_info[x]

            ase_calc = Espresso(pseudopotentials=pseudopotentials,
                                input_data=input_data,
                                kpts=KPTS,
                                koffset=KOFFS)

            if is_binary:
                ase_calc.command = binary

    # Check the allowed keys
    for k in ks:
        if __PSEUDO_LIST__ in k:
            continue
        if (not k in tot_keys) and check:
            print("Error with the key:", k)
            print("Did you mean something like:",
                  difflib.get_close_matches(k, tot_keys))
            raise IOError("Error in calculator namespace: key '" + k +
                          "' not recognized.")

    # Check for mandatory keys
    for req_key in __REQUESTED_KEYS__:
        if not req_key in ks:
            raise IOError(
                "Error, the calculator configuration namelist requires the keyword: '"
                + req_key + "'")

    return ase_calc
Beispiel #10
0
### Constraints ###
from ase.constraints import FixAtoms

z_atoms = atoms_info.get_positions()[:, 2]
ase_union.set_constraint(
    FixAtoms(indices=np.where(z_atoms <= z_bottom_2nd[1])[0]))

### Quantum Espresso ###
from ase.calculators.espresso import Espresso

calculation = input_sol["control"]["calculation"]
kpts = input_ase["kpts"]
command = input_ase["command"]
if calculation == 'scf':
    qe = Espresso(input_data=input_sol,
                  pseudopotentials=pseudopotentials,
                  kpts=kpts,
                  command=command)
elif calculation == 'relax':
    qe = Espresso(input_data=input_sol,
                  pseudopotentials=pseudopotentials,
                  kpts=kpts,
                  command=command)
elif calculation == 'bands':
    qe = Espresso(input_data=input_sol,
                  pseudopotentials=pseudopotentials,
                  kpts=kpts,
                  command=command)
ase_union.calc = qe
ase_union.calc.write_input(atoms_info)
try:
    ase_union.get_potential_energy()  # run pw.x
Beispiel #11
0
pw_data['diagonalization']  = 'david'
pw_data['diago_david_ndim'] = 2
pw_data['mixing_beta']      = 0.2
pw_data['mixing_mode']      = 'local-TF'
pw_data['electron_maxstep'] = 500

pseudos = {}

pseudos['Rh'] = 'Rh_ONCV_PBE-1.0.oncvpsp.UPF'
pseudos['C']  = 'C.pbe-n-kjpaw_psl.1.0.0.UPF'
pseudos['O']  = 'O.pbe-n-kjpaw_psl.0.1.UPF'
pseudos['H']  = 'H.pbe-rrkjus_psl.1.0.0.UPF'
pseudos['H']  = 'Al.pbe-n-kjpaw_psl.1.0.0.UPF'

calc = Espresso(input_data       = pw_data,
                pseudopotentials = pseudos,
                kpts             = kpts)

atoms.set_calculator(calc)

################################################################################
# WRITE ESPRESSO INPUT
################################################################################

write_esperesso_input = True

if write_esperesso_input is True:
    calc.write_input(atoms)
    os.rename('espresso.pwi', 'pw.inp')

################################################################################
Beispiel #12
0
 def get_potential_energy(self, atoms=None, force_consistent=True):
     return Espresso.get_potential_energy(self, atoms=atoms)
Beispiel #13
0
# by default ase will look for them in $HOME/espresso/pseudo
pseudo = {"H": "H.pbe-rrkjus_psl.0.1.UPF", "O": "O.pbe-n-rrkjus_psl.0.1.UPF"}

# Setup some info on the calculator (the wavefunction and density cutoff)
# Note they are super below convergence
# Good values would be (45, 45*8) for the cutoffs, and (3,3,2) for the k points
esp_info = {"ecutwfc": 25, "ecutrho": 25 * 4, "disk_io": "none"}
K_POINTS = (1, 1, 1)  # Only gamma calculation

# Setup the quantum espresso command for run (parallel on 4 processors here)
cmd = "/usr/bin/mpirun -np 2 $HOME/Downloads/QuantumESPRESSO/qe-6.3/bin/pw.x -in PREFIX.pwi > PREFIX.pwo"

# Setup the calculator
calc = Espresso(pseudopotentials=pseudo,
                tstress=True,
                tprnfor=True,
                kpts=K_POINTS,
                input_data=esp_info,
                command=cmd)

#Now load the initial dynamical matrix
dyn_start = CC.Phonons.Phonons("../ensemble_data_test/dyn")
T = 0  # Temperature of the calculation
N_RAND = 500  # number of random configurations

# Setup the ensemble
ens = sscha.Ensemble.Ensemble(dyn_start, T)

# Generate the ensemble
ens.generate(N_RAND)

# Get forces and energy using the quantum espresso calculator
Beispiel #14
0
#os.environ['ASE_ESPRESSO_COMMAND'] = 'srun -n {0} --mpi=pmi2 {1} -npool {2} < {3} > {4}'.format(no_cpus, 
#                            pw_loc, npool, input_file_name, output_file_name)
os.environ['ASE_ESPRESSO_COMMAND'] = '{0} < {1} > {2}'.format(pw_loc, input_file_name, output_file_name)

# set up input parameters
input_data = {'control':   {'prefix': label, 
                            'pseudo_dir': 'test_files/pseudos/',
                            'outdir': './out',
                            #'verbosity': 'high',
                            'calculation': 'scf'},
              'system':    {'ibrav': 0, 
                            'ecutwfc': 20, # 45,
                            'ecutrho': 40, # 181,
                            'smearing': 'gauss',
                            'degauss': 0.02,
                            'occupations': 'smearing'},
              'electrons': {'conv_thr': 1.0e-03,
                            #'startingwfc': 'file',
                            'electron_maxstep': 100,
                            'mixing_beta': 0.5}}

# pseudo-potentials              
ion_pseudo = {'Ag': 'Ag.pbe-n-kjpaw_psl.1.0.0.UPF', 
              'I':  'I.pbe-n-kjpaw_psl.1.0.0.UPF'}

# create ASE calculator
dft_calc = Espresso(pseudopotentials=ion_pseudo, label=label, 
                    tstress=True, tprnfor=True, nosym=True, #noinv=True,
                    input_data=input_data, kpts=(1,1,1)) 
dft_calc.parameters['parallel'] = False
Beispiel #15
0
###DFT Setup, Optimization, and Plotting
pseudopotentials = {'Al': pot_file2}
input_data = {
    'system': {
        'ecutwfc': 29,
        'ecutrho': 143,
        'occupations': 'smearing',
        'smearing': 'mp',
        'degauss': 0.02
    },
    'disk_io': 'low'
}
calc = Espresso(pseudopotentials=pseudopotentials,
                tstress=True,
                tprnfor=True,
                kpts=(4, 4, 1),
                input_data=input_data)

for image in imagesEAM:
    image.set_calculator(
        Espresso(pseudopotentials=pseudopotentials,
                 tstress=True,
                 tprnfor=True,
                 kpts=(4, 4, 1),
                 input_data=input_data))

print(imagesEAM[len(imagesEAM) - 1].get_potential_energy())
pes = np.zeros(no_images)
pos = np.zeros((no_images, len(imagesEAM[0]), 3))
DFTForces = np.zeros((no_images, len(imagesEAM[0]), 3))
Beispiel #16
0
no_cpus = 32
npool = 32
pw_loc = os.environ.get('PWSCF_COMMAND')
#pw_loc = '/n/home08/xiey/q-e/bin/pw.x'
os.environ['ASE_ESPRESSO_COMMAND'] = 'srun -n {0} --mpi=pmi2 {1} -npool {2} < {3} > {4}'.format(no_cpus, 
                            pw_loc, npool, input_file_name, output_file_name)
#os.environ['ASE_ESPRESSO_COMMAND'] = '{0} < {1} > {2}'.format(pw_loc, input_file_name, output_file_name)

# set up input parameters
input_data = {'control':   {'prefix': label, 
                            'pseudo_dir': './',
                            'outdir': './out',
                            #'verbosity': 'high',
                            'calculation': 'scf'},
              'system':    {'ibrav': 0, 
                            'ecutwfc': 60,
                            'ecutrho': 360},
              'electrons': {'conv_thr': 1.0e-9,
                            #'startingwfc': 'file',
                            'electron_maxstep': 100,
                            'mixing_beta': 0.7}}

# pseudo-potentials              
ion_pseudo = {'C': 'C.pz-rrkjus.UPF'}

# create ASE calculator
dft_calc = Espresso(pseudopotentials=ion_pseudo, label=label, 
                    tstress=True, tprnfor=True, nosym=True, #noinv=True,
                    input_data=input_data, kpts=(8, 8, 8)) 

# In this example we use a UNIX socket.  See other examples for INET socket.
# UNIX sockets are faster then INET sockets, but cannot run over a network.
# UNIX sockets are files.  The actual path will become /tmp/ipi_ase_espresso.
unixsocket = 'ase_espresso'

# Configure pw.x command for UNIX or INET.
#
# UNIX: --ipi {unixsocket}:UNIX
# INET: --ipi {host}:{port}
#
# See also QE documentation, e.g.:
#
#    https://www.quantum-espresso.org/Doc/pw_user_guide/node13.html
#
command = ('pw.x < PREFIX.pwi --ipi {unixsocket}:UNIX > PREFIX.pwo'.format(
    unixsocket=unixsocket))

espresso = Espresso(command=command,
                    ecutwfc=30.0,
                    pseudopotentials=pseudopotentials,
                    pseudo_dir=pseudo_dir)

opt = BFGS(atoms, trajectory='opt.traj', logfile='opt.log')

with SocketIOCalculator(espresso, log=sys.stdout,
                        unixsocket=unixsocket) as calc:
    atoms.calc = calc
    opt.run(fmax=0.05)

# Note: QE does not generally quit cleanly - expect nonzero exit codes.
Beispiel #18
0
def read_pw_in(fileobj):
    """Parse a Quantum ESPRESSO input files, '.in', '.pwi'.

    ESPRESSO inputs are generally a fortran-namelist format with custom
    blocks of data. The namelist is parsed as a dict and an atoms object
    is constructed from the included information.

    Parameters
    ----------
    fileobj : file | str
        A file-like object that supports line iteration with the contents
        of the input file, or a filename.

    Returns
    -------
    atoms : Atoms
        Structure defined in the input file.

    Raises
    ------
    KeyError
        Raised for missing keys that are required to process the file
    """
    # TODO: use ase opening mechanisms
    if isinstance(fileobj, str):
        fileobj = open(fileobj, 'rU')

    # parse namelist section and extract remaining lines
    data, card_lines = read_fortran_namelist(fileobj)

    # get the cell if ibrav=0
    if 'system' not in data:
        raise KeyError('Required section &SYSTEM not found.')
    elif 'ibrav' not in data['system']:
        raise KeyError('ibrav is required in &SYSTEM')
    elif data['system']['ibrav'] == 0:
        # celldm(1) is in Bohr, A is in angstrom. celldm(1) will be
        # used even if A is also specified.
        if 'celldm(1)' in data['system']:
            alat = data['system']['celldm(1)'] * units['Bohr']
        elif 'A' in data['system']:
            alat = data['system']['A']
        else:
            alat = None
        cell, cell_alat = get_cell_parameters(card_lines, alat=alat)
    else:
        alat, cell = ibrav_to_cell(data['system'])

    positions_card = get_atomic_positions(card_lines,
                                          n_atoms=data['system']['nat'],
                                          cell=cell,
                                          alat=alat)

    symbols = [label_to_symbol(position[0]) for position in positions_card]
    tags = [label_to_tag(position[0]) for position in positions_card]
    positions = [position[1] for position in positions_card]
    constraint_idx = [position[2] for position in positions_card]
    constraint = get_constraint(constraint_idx)

    pseudos = get_pseudopotentials(card_lines, n_types=data['system']['ntyp'])

    # Switch from using 'input_data' to a flat dictionary
    data = {k: v for block in data.values() for k, v in block.items()}

    # Don't store ntyp and nat because these are derivable from the atoms object
    data.pop('ntyp', None)
    data.pop('nat', None)

    # TODO: put more info into the atoms object
    # e.g magmom, forces.
    atoms = Atoms(symbols=symbols,
                  positions=positions,
                  cell=cell,
                  constraint=constraint,
                  pbc=True,
                  tags=tags,
                  calculator=Espresso(pseudopotentials=pseudos, **data))
    atoms.calc.atoms = atoms

    if any(['k_points' in l.lower() for l in card_lines]):
        for k, v in zip(['kpts', 'koffset', 'gamma_only'],
                        get_kpoints(card_lines, cell=atoms.cell)):
            atoms.calc.parameters[k] = v

    return atoms
    'tprnfor': True,
    'outdir': 'qe_at_gamma',
    'input_data': {
        'system': {
            'ecutwfc': 16.0
        },
        'electrons': {
            'conv_thr': 1e-10,
            'mixing_beta': 0.5
        },
        'disk_io': 'low',
        'pseudo_dir': 'potentials'
    },
    'kpts': None,
}
calc = Espresso(**calculator_inputs)
if not os.path.exists('structures'):
    os.mkdir('structures/')

# Generate initial structure
atoms_prim = bulk('Si', 'diamond', a=a0)
n_prim = atoms_prim.get_masses().shape[0]
# Replicate the unit cell 'nrep'=3 times
nrep = 3
supercell = np.array([nrep, nrep, nrep])
initial_structure = atoms_prim.copy() * (supercell[0], 1, 1) * (
    1, supercell[1], 1) * (1, 1, supercell[2])
replicated_structure = initial_structure.copy()

######## Set up the standard rattle (random displacement) scheme #######
# seed_int_struct = np.random.randint(1, 100000, size=1, dtype=np.int64)[0]
# Prepare the espresso calculator
# NOTE: these files should be located in the cluster $HOME/espresso/pseudo directory
pseudo = {"H": "H.pbe-rrkjus_psl.0.1.UPF",
                    "O": "O.pbe-n-rrkjus_psl.0.1.UPF"}

input_data = {"ecutwfc" : 45,
              "ecutrho" : 45*8,
              "conv_thr" : 1e-8,
              "occupations" : "fixed",
              "tstress" : True,
              "diskio" : "none",
              "tprnfor" : True}
KPTS = (3,3,2) # K points

calc = Espresso(input_data = input_data, pseudopotentials = pseudo, kpts = KPTS)

# Prepare the cluster
# marconi (setted from .ssh_config) => [email protected]
# No pwd, login with private key
cluster = sscha.Cluster.Cluster("marconi", partition_name="knl_usr_prod",
                                binary="$HOME/qe-6.2.1/bin/pw.x -npool $NPOOL -i PREFIX.pwi > PREFIX.pwo")

# Setup the working directory
cluster.workdir = "/marconi_work/IscrC_HydPD/tmp_calc"
cluster.n_nodes = 1
cluster.n_cpu = 32
cluster.account_name = "IscrB_COMRED"
cluster.n_pool = 4
cluster.load_modules = """module load autoload intel
module load autoload intelmpi
from ase.collections import dcdft
from ase.io import read, write, Trajectory

# making dimer.traj
traj = Trajectory('dimer.traj', 'w')  # create Trajectory object
dx = 0.1  #scaling factor
list1 = [0, 0, 0]  # position of first atom
list2 = [0, 0, 0.5]  # will store new position of second atom
vec_2 = np.array(list2) - np.array(list1)  # vector pointing from 1 to 2
norm_2 = np.linalg.norm(vec_2, ord=2)  # get norm
vec_2 = [x / norm_2 for x in vec_2]  # get unit vector
for i in range(4):
    ss = [dx * x for x in vec_2]  #scale vector
    list2 = np.array(list2) + np.array(ss)  # move second atom
    dimer = Atoms('CC', positions=[list1, list2])  # create ASE atom object
    dimer.calc = Espresso(pseudopotentials=pseudopotentials)
    dft_energy = dimer.get_potential_energy()
    traj.write(dimer,
               energy=(dft_energy))  # write dft energy to trajectory file
    dx += 0.1

# making bulk.traj
#https://wiki.fysik.dtu.dk/ase/tutorials/deltacodesdft/deltacodesdft.html?highlight=dft%20calculatin#ase.utils.deltacodesdft.delta
pseudopotentials = {'C': 'C.pbe-n-kjpaw_psl.1.0.0.UPF'}
for symbol in ['C']:
    traj = Trajectory('bulk.traj'.format(symbol), 'w')
    for s in range(94, 108, 2):
        bulk = dcdft[symbol]
        bulk.set_cell(bulk.cell * (s / 100.0)**(1.0 / 3.0), scale_atoms=True)
        bulk.calc = Espresso(pseudopotentials=pseudopotentials, kpts=(6, 6, 6))
        dft_energy = bulk.get_potential_energy()
Beispiel #22
0
    "S": "S.pbe-nl-rrkjus_psl.1.0.0.UPF"
}

input_data = {
    "ecutwfc": 35,
    "ecutrho": 350,
    "occupations": "smearing",
    "input_dft": "blyp",
    "mixing_beta": 0.2,
    "conv_thr": 1e-9,
    "degauss": 0.02,
    "smearing": "mp",
    "pseudo_dir": "."
}

calc = Espresso(pseudopotentials=pseudo, input_data=input_data, kspacing=0.06)

struct = CC.Structure.Structure()
struct.read_scf("H3S.scf")

ase_struct = struct.get_ase_atoms()
ase_struct.set_calculator(calc)

print("Computing the total energy...")
total_energy = ase_struct.get_total_energy()

phonons = """
&inputph
   ldisp = .true.
   nq1 = 2
   nq2 = 2
Beispiel #23
0
# %cd /content
!mkdir NaCl
# %cd NaCl
#----
!wget https://www.quantum-espresso.org/upf_files/Na.pbesol-spn-kjpaw_psl.1.0.0.UPF
!wget https://www.quantum-espresso.org/upf_files/Cl.pbesol-n-kjpaw_psl.1.0.0.UPF
#----
from ase.build import bulk
from ase.calculators.espresso import Espresso
from ase.constraints import UnitCellFilter
from ase.optimize import LBFGS
import ase.io 
pseudopotentials = {'Na': 'Na.pbesol-spn-kjpaw_psl.1.0.0.UPF',
                    'Cl': 'Cl.pbesol-n-kjpaw_psl.1.0.0.UPF'}  
rocksalt = bulk('NaCl', crystalstructure='rocksalt', a=6.0)
calc = Espresso(pseudopotentials=pseudopotentials,pseudo_dir = './',
                tstress=True, tprnfor=True, kpts=(3, 3, 3))
rocksalt.set_calculator(calc)
ucf = UnitCellFilter(rocksalt)
opt = LBFGS(ucf)
opt.run(fmax=0.005)
# cubic lattic constant
print((8*rocksalt.get_volume()/len(rocksalt))**(1.0/3.0))
#----
# %cd /content
!mkdir Cu
# %cd Cu
#----
!wget https://www.quantum-espresso.org/upf_files/Cu.pz-d-rrkjus.UPF
#----
from ase import Atoms
from ase.build import bulk
Beispiel #24
0
from ase.calculators.espresso import Espresso
pot_file = 'Al.pbe-n-rrkjus_psl.1.0.1.UPF'
pseudopotentials = {'Al': pot_file}
input_data = {
    'system': {
        'ecutwfc': 29,
        'ecutrho': 143,
        'occupations': 'smearing',
        'smearing': 'mp',
        'degauss': 0.02
    },
    'disk_io': 'low'
}
calc = Espresso(pseudopotentials=pseudopotentials,
                tstress=True,
                tprnfor=True,
                kpts=(4, 4, 1),
                input_data=input_data)

#create structure as FCC surface with addsorbate
from ase.build import fcc111, add_adsorbate
slab = fcc111('Al', size=(2, 2, 3))
add_adsorbate(slab, 'Al', 2, 'hcp')
slab.center(vacuum=5.0, axis=2)

#view and set calculator
from ase.visualize import view
view(slab, viewer='x3d')
slab.set_calculator(calc)
slab.get_potential_energy()
                              stretch_max=0.15,
                              toll_rotation=5e-2)

kpts = calculate_kpts(atoms=atoms,
                      cell=support.cell,
                      kpts=kpts,
                      scale_kpts='xy')

################################################################################
# WRITE QUANTUM ESPRESSO INPUT
################################################################################

calc = Espresso(input_data=input_data,
                pseudopotentials=pseudos,
                kpts=kpts,
                koffset=koffset,
                calculation='vc-relax',
                restart_mode='from_scratch',
                max_seconds=1700)

calc.write_input(atoms)
os.rename('espresso.pwi', 'pw.inp')

################################################################################
# RUN QUANTUM ESPRESSO
################################################################################

run_qe = False

if run_qe is True:
    os.system("run pw -fs -n=2 -t=0.5")
Beispiel #26
0
# -*- coding: utf-8 -*-
"""
Created on Sun Feb  9 16:28:02 2020

@author: srava
"""
from ase.build import molecule, bulk
from ase.visualize import view
from ase.optimize import BFGSLineSearch, QuasiNewton
from ase.calculators.espresso import Espresso
from ase.constraints import UnitCellFilter
from ase.optimize import LBFGS

pseudopotentials = {
    'Na': 'Na_pbe_v1.uspp.F.UPF',
    'Cl': 'Cl.pbe-n-rrkjus_psl.1.0.0.UPF'
}
rocksalt = bulk('NaCl', crystalstructure='rocksalt', a=6.0)
calc = Espresso(pseudopotentials=pseudopotentials,
                tstress=True,
                tprnfor=True,
                kpts=(3, 3, 3))
rocksalt.calc = calc

ucf = UnitCellFilter(rocksalt)
opt = LBFGS(ucf)
opt.run(fmax=0.005)

# cubic lattic constant
print((8 * rocksalt.get_volume() / len(rocksalt))**(1.0 / 3.0))
Beispiel #27
0
        'input_dft': xc,
        'occupations': 'smearing',
        'smearing': 'gaussian',
        'degauss': 0.001
    },
    'electrons': {
        'electron_maxstep': 250,
        'scf_must_converge': False,
        'mixing_beta': 0.1,
        'conv_thr': 1e-7
    },
}

calc = Espresso(
    kpts=kpts,
    pseudopotentials=gbrv_pp,
    tstress=True,
    tprnfor=True,  # kwargs added to parameters
    input_data=input_data)

atoms.calc = calc
atoms.get_potential_energy()

# Get the valence band maximum
efermi = calc.get_fermi_level()
Nk = len(calc.get_ibz_k_points())
Ns = calc.get_number_of_spins()
eigval = np.array([[calc.get_eigenvalues(kpt=k, spin=s) for k in range(Nk)]
                   for s in range(Ns)])
evbm = np.max(eigval[eigval < efermi])

# Next, a band structure calculation
Beispiel #28
0
pseudopotentials = {"H": "H.pbe-kjpaw_psl.0.1.UPF",
                    "O": "O.pbe-n-kjpaw_psl.0.1.UPF"}

import ase.io
from ase.calculators.espresso import Espresso
from ase.optimize import LBFGS

input_data = {
    'system': {
        'ecutwfc': 30.0,
        'ecutrho': 120.0
    },
    'disk_io': 'none',
    'pseudo_dir': '/home/efefer/pseudo/PSLIB'
}

calc = Espresso(pseudopotentials=pseudopotentials,
                tstress=True, tprnfor=True,
                input_data=input_data)

atoms = ase.io.read("H2O_centered.xyz")
atoms.calc = Espresso(pseudopotentials=pseudopotentials,
                tstress=True, tprnfor=True)

opt = LBFGS(atoms)
opt.run(fmax=0.005)